#!/usr/bin/python
"""Main FastCGI entry point for web interface"""

import cherrypy
import os
import sys

import main

dev = False
base_dir = os.path.dirname(__file__)

def usage():
    print >>sys.stderr, """%s [config]

Run server as FastCGI, with CherryPy config from "main.conf".

With `config`, run standalone with CherryPy config from `config`.

Run this script as either 'auth.fcgi' or 'unauth.fcgi', to get
the authenticated or unauthenticated site respectively.
""" % sys.argv[0]
    sys.exit(2)

if __name__ == "__main__":
    if len(sys.argv) > 2:
        usage()
    if len(sys.argv) > 1:
        if sys.argv[1] in ('-h', '--help'):
            usage()
        conf_file = sys.argv[1]
        dev = True
    else:
        conf_file = os.path.join(base_dir, 'main.conf')

    app_config = {
        '/': {
            'tools.invirtwebstate.on': True,
            },
        }

    if os.path.basename(sys.argv[0]).startswith('auth'):
        root = main.InvirtWeb()
    elif os.path.basename(sys.argv[0]).startswith('unauth'):
        root = main.InvirtUnauthWeb()
    else:
        usage()

    app = cherrypy.tree.mount(root, '/', app_config)
    app.merge(conf_file)
    cherrypy.config.update(conf_file)

    if dev:
        cherrypy.server.quickstart()
        cherrypy.engine.start()
        cherrypy.engine.block()
    else:
        cherrypy.engine.start(blocking=False)
        from flup.server.fcgi import WSGIServer
        server = WSGIServer(cherrypy.tree)
        server.run()
