#! /usr/bin/env python
# -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license. 
# See the NOTICE for more information.


import os
import pkg_resources
import re
import sys
from paste.deploy import loadapp, loadwsgi
from gunicorn.main import main

__usage__ = "%prog [OPTIONS] APP_MODULE"

_scheme_re = re.compile(r'^[a-z][a-z]+:', re.I)


def get_app(parser, opts, args):
    if len(args) != 1:
        parser.error("No applicantion name specified.")
        
    config_file = os.path.abspath(os.path.normpath(
                        os.path.join(os.getcwd(), args[0])))
                        
    if not os.path.exists(config_file):
        parser.error("Config file not found.")
    
    config_url = 'config:%s' % config_file
    relative_to = os.path.dirname(config_file)
    
    # load module in sys path
    sys.path.insert(0, relative_to)

    # add to eggs
    pkg_resources.working_set.add_entry(relative_to)
    ctx = loadwsgi.loadcontext(loadwsgi.SERVER, config_url,
                            relative_to=relative_to)

    if opts.workers:
        workers = opts.workers
    else:
        workers = int(ctx.local_conf.get('workers', 1))
        
    opts.host = opts.host or ctx.local_conf.get('host', '127.0.0.1')
    opts.port = opts.port or int(ctx.local_conf.get('port', 8000))
        
    debug = ctx.global_conf.get('debug') == "true"
    if debug:
        # we force to one worker in debug mode.
        workers = 1

    opts.workers=workers
    
    app = loadapp(config_url, relative_to=relative_to)
    return app
    
main(__usage__, get_app)
