import socket
import sys
import os

import qommon.scgi_server
import quixote.server.simple_server

import authentic.publisher as publisher

def start(args):
    extra_dirs = []
    run_function = qommon.scgi_server.run
    run_kwargs = {}
    run_kwargs['port'] = 3002

    i = 0
    while i < len(args):
        if args[i] == '--port':
            run_kwargs['port'] = int(args[i+1])
            i += 1
        elif args[i] == '--extra':
            publisher.AuthenticPublisher.register_extra_dir(args[i+1])
            extra_dirs.append(args[i+1])
            i += 1
        elif args[i] == '--app-dir':
            publisher.AuthenticPublisher.APP_DIR = args[i+1]
            i += 1
        elif args[i] == '--data-dir':
            publisher.AuthenticPublisher.DATA_DIR = args[i+1]
            i += 1
        elif args[i] == '--http':
            run_function = qommon.scgi_server.http_run
        elif args[i] == '--host':
            run_kwargs['host'] = args[i+1]
            i += 1
        elif args[i] == '--webroot-dir':
            publisher.AuthenticPublisher.WEBROOT_DIR = args[i+1]
            i += 1
        elif args[i] == '--silent':
            sys.stdout = file('/dev/null', 'w')
            sys.stderr = file('/dev/null', 'w')
        elif args[i] == '--script-name':
            run_kwargs['script_name'] = args[i+1]
            i += 1
        elif args[i] == '--spawn-cron':
            run_kwargs['spawn_cron'] = True
        elif args[i] == '--max-children':
            try:
                run_kwargs['max_children'] = int(args[i+1])
            except:
                raise SystemExit('--max-children needs an integer parameter')
            i += 1
        elif args[i] == '--max-requests':
            try:
                run_kwargs['handler_connection_limit'] = int(args[i+1])
            except:
                raise SystemExit('--max-requests needs an integer parameter')

        i += 1

    try:
        run_function(publisher.AuthenticPublisher.create_publisher, **run_kwargs)
    except socket.error, e:
        if e[0] == 98:
            print >> sys.stderr, 'address already in use'
            sys.exit(1)
        raise
    except KeyboardInterrupt:
        sys.exit(1)

