#!/usr/bin/env python

import sys, optparse, stellaris, logging, os

from benri.utils import daemonize
from benri.log import initLogger
from benri.config import Config
from stellaris.service import Serve
from stellaris.env import Environment

def start(env_path):
    # read in the config file

    try:
        env = Environment(env_path)
        server = Serve(env)        
    except Exception, e:
        sys.exit(str(e))

    try:
        server.start()
    except KeyboardInterrupt, e:
        env.log.debug("Received a keyboard interrupt, stopping server.")
        server.stop()
    except SystemExit, e:
        env.log.debug("Received system exit, stopping server.")
        server.stop()

if __name__ == "__main__":
    p = optparse.OptionParser(version='stellaris'.title() + ' ' + stellaris.__VERSION__, usage="%prog [options] <environment path>")
    p.add_option("-d", "--daemon", action="store_const", const=True, dest="daemon", default=False, help="Runs the service in the background.")
    p.add_option("-c", "--create-environment", action="store", type="string", dest="setup",
                 help="Create the files necessary to run a stellaris instance. The given name is used to create a directory with the files in the current working directory.")
    

    (opts, args) = p.parse_args()

    if opts.setup:
        import shutil
        from pkg_resources import Requirement, resource_filename
        
        name = opts.setup
        path = os.path.join(os.getcwd(), name)
        try:
            env = Environment(path, create=True)
        except Exception, e:
            import traceback
            traceback.print_exc()
            sys.exit("Could not create the environment %s\n" % name)
            
        print "Created the files necessary to run Stellaris in %s." % path
        print "Start Stellaris with `stellaris %s`" % path
        sys.exit('\n')

    if len(args) < 1:
        p.print_version()
        p.print_help()
        sys.exit(-1)
    
    env_path = os.path.abspath(args[0])
    
    # this must be done before daemonize
    curdir = os.getcwd()
                
    if opts.daemon:
        daemonize()
    
    start(env_path)
