import socket
import sys
import quixote.server.simple_server

from qommon.scgi_server import run

import publisher

def start(args):
    run_function = run
    run_kwargs = {
        'port': 3007,
        'script_name': ''
    }
    http = 0

    i = 0
    while i < len(args):
        if args[i] == '--port':
            run_kwargs['port'] = int(args[i+1])
            i += 1
        elif args[i] == '--silent':
            sys.stdout = open('/dev/null', 'w')
            sys.stderr = open('/dev/null', 'w')
        elif args[i] == '--script-name':
            run_kwargs['script_name'] = args[i+1]
            i += 1
        elif args[i] == '--app-dir':
            publisher.LarpePublisher.APP_DIR = args[i+1]
            i += 1
        elif args[i] == '--data-dir':
            publisher.LarpePublisher.DATA_DIR = args[i+1]
            i += 1
        elif args[i] == '--http':
            http = 1
        i += 1

    if http == 1:
        run_function = quixote.server.simple_server.run
        if run_kwargs['script_name']:
            print "--http option is incompatible with --script-name"
        del run_kwargs['script_name']
    try:
        run_function(publisher.LarpePublisher.create_publisher, **run_kwargs)
    except socket.error, err:
        if err[0] == 98:
            print >> sys.stderr, 'address already in use'
            sys.exit(1)
        raise
    except KeyboardInterrupt:
        sys.exit(1)

