#!/usr/bin/python2

""" ircLoad
    This is the Main file of ircLoad. In here the command
    line handling and configuration managment are handlet. """

import sys
#import daemon
import logging as log
from xml.dom import minidom
import getopt
import random

from twisted.internet import reactor

from xdccLoad import XdccBotFactory
from querryHandler import querryHandler

factories = []
querry_handler = []
tmp_dir = '.'
global debug_
debug_ = 0
global unpack_
unpack_ = 0
global testrun_
testrun_ = 0

#-----------------------------------------------------------------------
def main(argv=None):
    _daemon = False
    _logfile = '/tmp/ircLoad.log'
    _log_level = log.INFO
    config_file="config.xml"
    global debug_
    global unpack_
    global testrun_
    try:
        opts, args = getopt.getopt(argv, "hc:dDl:tu", ["help", "config=", "daemon", "debug",
            "logfile=","testrun","unpack"])
    except getopt.GetoptError:
        usage()
        sys.exit(2)
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage()
            sys.exit()
        elif opt in ('-c', '--config='):
            config_file = arg
        elif opt in ('-d', '--daemon'):
            _daemon = True
        elif opt in ('-D', '--debug'):
            debug_ = 1
            _log_level = log.DEBUG
        elif opt in ('-l', '--logfile'):
            _logfile = arg
        elif opt in ('-t', '--testrun'):
            testrun_ = 1
        elif opt in ('-u', '--unpack'):
            unpack_ = 1
    log.basicConfig(
        filename = _logfile,
        level = _log_level,
        filemode = "w", # a for append to logfile
        format = '%(asctime)s %(levelname)s:%(message)s')
    try:
        log.info("cf=%s" % config_file)
        fsock = open(config_file)
        xmldoc = minidom.parse(fsock)
        fsock.close()
    except IOError:
        log.error( 'cannot open config')
        exit
    tmp_dir = xmldoc.getElementsByTagName("tmpdir")[0].attributes["dir"].value
    log.info( "Donload dir = %s" % tmp_dir)


    #geting list of databases from config file
    querry_handler = querryHandler()
    for db in xmldoc.getElementsByTagName("database"):
        log.info( "%s %s" % (db.attributes["db"].value, db.attributes["type"].value))
        _types = []
        for _type in db.getElementsByTagName("datatype"):
            _types.append( _type.attributes["type"].value)
        querry_handler.addDatabase(db.attributes["db"].value,
                                   db.attributes["type"].value,
                                   db.attributes["datadir"].value,
                                   db.attributes["min_filesize"].value,
                                   db.attributes["max_filesize"].value,
                                   _types)
    querry_handler.update()


    #Geting list of servers from config file
    for serv in xmldoc.getElementsByTagName("server"):
        _uname = ('%s_%04x' % ( serv.attributes["user"].value, random.randrange(16**4))).encode('ascii', 'ignore')
        _addr  = (str(serv.attributes["addr"].value)).encode('ascii', 'ignore')
        _port  = int(serv.attributes["port"].value)
        _channels = []
        for chan in serv.getElementsByTagName("channel"):
            _channels.append([str(chan.attributes["name"].value), chan.attributes["scan"].value])
        log.info( " SERVER: %s:%d %s %s %s" % ( _addr, _port, _uname, _channels, tmp_dir))
        factories.append( XdccBotFactory( str(serv.attributes["addr"].value), int(serv.attributes["port"].value), _channels, _uname, querry_handler, tmp_dir))
    for _factory in factories:
        reactor.connectTCP( _factory.getServer(), _factory.getPort(), _factory )
    if _daemon:
        with daemon.DaemonContext():
            reactor.run()
    else:
        reactor.run()

#-----------------------------------------------------------------------
if __name__ == "__main__":
    main(sys.argv[1:])
