import socket
import sys

from qommon.scgi_server import run

import publisher

def start(args):
    port = 3007
    script_name = ''

    i = 0
    while i < len(args):
        if args[i] == '--port':
            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':
            script_name = args[i+1]
            i += 1
        i += 1

    try:
        run(publisher.LarpePublisher.create_publisher, port=port, script_name=script_name)
    except socket.error, err:
        if err[0] == 98:
            print >> sys.stderr, 'address already in use'
            sys.exit(1)
        raise
    except KeyboardInterrupt:
        sys.exit(1)

