#!/usr/bin/python

# Copyright (C) 2007-2010 AG Projects.
#

"""OpenXCAP"""


if __name__ == '__main__':
    import sys
    from optparse import OptionParser
    from application.process import process, ProcessError
    from application import log
    import xcap

    name = 'openxcap'
    description = 'An open source XCAP Server'
    version = xcap.__version__
    fullname = 'OpenXCAP %s' % version

    config_directory = '/etc/openxcap'
    runtime_directory = '/var/run/openxcap'
    default_pid = "%s/%s.pid" % (runtime_directory, name)

    parser = OptionParser(version="%%prog %s" % version)
    parser.add_option("--no-fork", action="store_false", dest="fork", default=1,
                      help="run the process in the foreground (for debugging)")
    parser.add_option("--pid", dest="pidFile", default=default_pid,
                      help="pid file (%s)" % default_pid,
                      metavar="File")

    (options, args) = parser.parse_args()

    try:
        xcap.dependencies.check()
    except xcap.DependencyError, e:
        log.fatal(str(e))
        sys.exit(1)

    pidFile = options.pidFile

    process.system_config_directory = config_directory
    try:
        process.runtime_directory = runtime_directory
    except ProcessError, e:
        log.msg("Fatal error: %s" % e)
        sys.exit(1)

    from xcap.logutil import start_log
    if options.fork:
        try:
            process.daemonize(pidFile)
        except ProcessError, e:
            log.fatal(str(e))
            sys.exit(1)
        start_log()
    else:
        pass
        #from application.debug.memory import *

    log.msg("Starting %s" % fullname)

    try:
        from xcap.server import XCAPServer
        server = XCAPServer()
        server.start()
    except Exception, e:
        log.fatal("failed to create %s: %s" % (fullname, e))
        if e.__class__ is not RuntimeError:
            log.err()
        sys.exit(1)

