#!/usr/bin/env python

#
# Copyright (C) 2002 Manuel Estrada Sainz <ranty@debian.org>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import twisted
import apt_proxy
from twisted.python import usage
import sys, pwd, os

class MyOptions(usage.Options):
    optFlags = [
        ['version', 'V', 'print version and quit'],
        ['verbose', 'v', 'give verbose output'],
        ['quiet', 'q', "try not to write messages to stdout"],
        ['recursive', 'r', 'recurse into subdirectories'],
        ['help', 'h'],
        ]
    optParameters = [
        ['import-dir', 'i', None, "Directory to import .deb's from"],
        ['user', 'u', 'aptproxy', "Change to this username."],
        ['debug', 'd', 0, "debug level"],
        ]
    longdesc="apt-proxy-import imports .deb files into the apt-proxy cache."

    def __init__(self):
        usage.Options.__init__(self)

    def opt_version(self):
        print "apt-proxy-import 1.9.x"
        sys.exit(0)

try:
    config = MyOptions()
    config.parseOptions()
except usage.UsageError, ue:
    print '%s: %s' % (sys.argv[0], ue)

should_be_uid = pwd.getpwnam(config.opts['user'])[2]
if os.getuid() != should_be_uid:
    try:
        os.setuid(should_be_uid)
    except OSError:
        print "Error, couldn't change to user %s."%config.opts['user']
        sys.exit(1)

from apt_proxy.apt_proxy_conf import factoryConfig
from apt_proxy import packages

class DummyFactory:
    "This is just to get the configuration data somewhere."
    def __init__ (self):
        self.backends = []
    def debug(self, msg):
        print msg
    def addBackend(self, backend):
        self.backends.append(backend)
        
        
factory = DummyFactory()
factoryConfig(factory)

twisted.python.log.startLogging(sys.stdout)

if config.opts['debug']:
    print 'debug'
    factory.do_debug=1
    apt_proxy.misc.log.addDomains(factory.debug)
    apt_proxy.misc.log.addDomains( {'all': config.opts['debug']} )
elif config.opts['verbose']:
    print "verbose"
    apt_proxy.misc.log.addDomains( {'all': 10} )
elif not config.opts['quiet']:
    # default behaviour
    apt_proxy.misc.log.addDomains( {'all': 4} )

if config.opts['recursive']:
    recurse = 1
else:
    recurse = 0

import_dir = config.opts['import-dir']

if not import_dir:
    import_dir = factory.import_dir
packages.import_directory(factory, import_dir, recurse)
