#!/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

from apt_proxy.apt_proxy_conf import factoryConfig
from apt_proxy.apt_proxy import Factory
from twisted.manhole.telnet import ShellFactory

username = "aptproxy"

factory = Factory()
shell = ShellFactory()

pwent = pwd.getpwnam(username)
uid = pwent[2]
gid = pwent[3]

# application to be started by twistd
application = service.Application("AptProxy", uid, gid)

factoryConfig(factory, shell)

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

if __name__ == '__main__':
    #Sorry moshez, but I don't jet feel confortable with twistd
    application.run(0)
