#!/usr/bin/env python

# Load apt-proxy application
#
# There are two ways apt-proxy can be started:
#  1. twistd -y apt-proxy
#     - twistd will load this file and execute the app
#       in 'application' variable
#  2. from command line
#     - __name__ will be '__main__' 

import pwd,sys

from twisted.application import service, internet, app
from twisted.internet import reactor
from twisted.manhole.telnet import ShellFactory
from twisted.python import usage, log

from apt_proxy.apt_proxy_conf import apConfig
from apt_proxy.apt_proxy import Factory

config_file = None

if __name__ == '__main__':
    # Parse command line parameters when started on command line
    class AptProxyOptions(usage.Options):
        optFlags = [
            ['help', 'h'],
            ]
        optParameters = [
            ['config-file', 'c', None, "Configuration file"],
            ]
        longdesc="apt-proxy is a proxy for saving bandwidth for apt users"
        def opt_version(self):
            print "apt-proxy 1.9.x"
            sys.exit(0)
    
    opts = AptProxyOptions()
    try:
        opts.parseOptions()
    except usage.UsageError, ue:
        print '%s: %s' % (sys.argv[0], ue)
        sys.exit(1)

    config_file = opts.opts['config-file']

config = apConfig(config_file)
factory = Factory(config)
uid,gid = pwd.getpwnam(config.username)[2:4]

if config.telnet_port:
    shell = ShellFactory()
    shell.username = config.telnet_user
    shell.password = config.telnet_pass
    shell.port = config.telnet_port

# application to be started by twistd
application = service.Application("apt-proxy", uid, gid)
print service.IProcess(application).processName
service.IProcess(application).processName = 'apt-proxy'

for address in config.address:
    if config.telnet_port:
        internet.TCPServer(config.telnet_port, shell, interface=address).setServiceParent(application)
    internet.TCPServer(config.port, factory, interface=address).setServiceParent(application)

if __name__ == '__main__':
    # Run on command line
    log.startLogging(sys.stdout, setStdout=0)
    service.IServiceCollection(application).privilegedStartService()
    service.IServiceCollection(application).startService()
    reactor.run()
