#!/usr/bin/python
import sys, time
sys.path.insert(0,'/usr/lib/entropy/libraries')
sys.path.insert(0,'/usr/lib/entropy/client')
sys.path.insert(0,'../libraries')
sys.path.insert(0,'../client')
# disable pid management
sys.argv.append("--no-pid-handling")
do_ssl = False
do_stdout_logging = True
if "--ssl" in sys.argv:
    do_ssl = True
if "--nostdout" in sys.argv:
    do_stdout_logging = False

import entropyTools, exceptionTools
from entropy import RepositorySocketServerInterface, phpBB3AuthInterface, phpbb3Authenticator, phpbb3Commands, DistributionUGCCommands


connection_data = {
    'hostname': 'localhost',
    'port': 3306,
    'username': 'phpbb_user',
    'password': 'mypassword',
    'dbname': 'phpbb_db'
}
ugc_connection_data = {
  'hostname': 'localhost',
  'username': 'entropy',
  'password': 'password',
  'dbname': 'entropy',
  'google_email': 'your@gmail.com', # valid google account
  'google_password': 'yourgmailpassword', # valid google e-mail
  'google_developer_key': 'xxxxx', # valid google developer key
  'google_client_id': 'xxxx', # valid google client id connected to the developer key
}
ugc_store_path = "/path/to/your/ugc/store"
ugc_store_url = "http://www.yoursite.com"
ugc_args = [ugc_connection_data,ugc_store_path,ugc_store_url]

# configure my repositories
repositories = {
    ('sabayonlinux.org','amd64','standard','3.5',): {
        'dbpath': '/home/fabio/new.sabayonlinux.org/standard/amd64/3.5',
        'cmethod': 'bz2',
    },
}

def run_srv(s):
    try:
        s.go()
    except (KeyboardInterrupt, SystemExit,):
        s.killall()

sock_auth = (phpbb3Authenticator,[],connection_data)
srv_ssl = None
srv = RepositorySocketServerInterface(
        do_ssl = False,
        repositories = repositories,
        stdout_logging = do_stdout_logging,
        sock_auth = sock_auth,
        external_cmd_classes = [phpbb3Commands,(DistributionUGCCommands,ugc_args,)]
    )
if do_ssl:
    srv_ssl = RepositorySocketServerInterface(
        do_ssl = True,
        repositories = repositories,
        stdout_logging = do_stdout_logging,
        sock_auth = sock_auth,
        external_cmd_classes = [phpbb3Commands,(DistributionUGCCommands,ugc_args,)]
    )

task = entropyTools.parallelTask(run_srv, srv)
task.setName('repodaemon')
task.start()
if srv_ssl != None:
    task = entropyTools.parallelTask(run_srv, srv_ssl)
    task.setName('repodaemon_ssl')
    task.start()

while 1:
    try:
        time.sleep(1)
        found = False
        threads = entropyTools.threading.enumerate()
        for thread in threads:
            if thread.getName() in ["repodaemon","repodaemon_ssl"]:
                found = True
                break
        if not found:
            break
    except (KeyboardInterrupt, SystemExit,):
        threads = entropyTools.threading.enumerate()
        for thread in threads:
            if thread.getName() in ["repodaemon","repodaemon_ssl"]:
                thread.args[0].killall()
        raise SystemExit
