#!/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():
    argv0_dir = os.path.dirname(sys.argv[0])
    print >>sys.stderr, """%s <unauth|auth> [config]

Or via the provided wrapper scripts:
%s/auth.fcgi [config]
%s/unauth.fcgi [config]

Run server as FastCGI, with CherryPy config from "main.conf".
With `config`, run standalone with CherryPy config from `config`.

Serve the authenticated site with 'auth' or under 'auth.fcgi',
and the unauthenticated site with 'unauth' or under 'unauth.fcgi'.
""" % (sys.argv[0], argv0_dir, argv0_dir)
    sys.exit(2)

if __name__ == "__main__":
    if '-h' in sys.argv or '--help' in sys.argv:
        usage()
    if not (2 <= len(sys.argv) <= 3):
        usage()

    mode = sys.argv[1]
    if len(sys.argv) == 3:
        conf_file = sys.argv[2]
        dev = True
    else:
        conf_file = os.path.join(base_dir, 'main.conf')

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

    if mode.startswith('auth'):
        root = main.InvirtWeb()
        app_config['/']['tools.mako.module_directory'] = "/tmp/invirt-auth-web-templatecache"
    elif mode.startswith('unauth'):
        root = main.InvirtUnauthWeb()
        app_config['/']['tools.mako.module_directory'] = "/tmp/invirt-unauth-web-templatecache"
    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()
