#!/usr/bin/env python
# this implements the daemon side of things
# 1.) lissen for connections
# 2.) handle them
# 3.) goto 1.)
#
import sys, re, threading, etdc_fd, etd_server

version   = "$Id: $"
partition = lambda p, l: reduce(lambda a, i: (a[0]+[i], a[1]) if p(i) else (a[0], a[1]+[i]), l, ([], []))


# we are a main program, not loadable as module
# Our command line options either start with '-' (minus) or have the form key=value
rxOpt                = re.compile(r"^(-.+|[^=]+=.+)$")
(options, arguments) = partition(rxOpt.match, sys.argv[1:])

print "{0}: options = {1}, arguments = {2}".format(sys.argv[0], options, arguments)


def usage(name, longhelp, exitval):
    print """{name} [options]
    start an e-transfer server with the given [options]""".format( name=name )
    if longhelp:
        print """
currently recognized options:
    -h          print this message and exit succesfully
    -v          print version and exit succesfully
    -d          daemonize
"""
    sys.exit( exitval )


if '-h' in options:
    # help exists sucessfully
    usage(sys.argv[0], True, 0)

if '-v' in options:
    print version
    sys.exit( 0 )

#if not arguments:
#    usage(sys.argv[0], False, 1)
event     = threading.Event()
clients   = []
# Create a listener to accept incoming commands on
lissensok = etdc_fd.mk_server('tcp', (None, 4004))
# the data channel
transfers = {}
dataAddr  = ('tcp', (None, 4005))
dataServ  = etd_server.ETDDataServer( dataAddr, transfers )
try:
    while True:
        (newfd, remote_addr) = lissensok.accept()
        print "Incoming connection from {0}".format( remote_addr )
        if newfd is None:
            print "accept() returned None?"
            continue
        clients.append( (newfd, etd_server.ETDServerWrapper(newfd, event, remote_addr, data=dataServ, xfers=transfers)) )
except KeyboardInterrupt:
    print "ETDaemon shutting down. Stop incoming connections ..."
    lissensok.close()
    print "Joining threads ..."
    map(lambda clnt: clnt[0].close(), clients)
    dataServ.close()
    print "Done."
