# -*- coding: UTF-8 -*-

# Copyright (c) 2007 Daniele Favara <nomed@dsslive.org>.
#
# This is free software you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# This software is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software; see the file COPYING.  If not, write to the Free
# Software Foundation, Inc., 51 Franilin St, Fifth Floor, Boston, MA

"""This module contains functions called from console script entry points."""

import os
import sys

from os.path import dirname, exists, join

import pkg_resources
pkg_resources.require("TurboGears")

import turbogears
import cherrypy

cherrypy.lowercase_api = True

class ConfigurationError(Exception):
    pass

def _get_configfile():
    setupdir = dirname(dirname(dirname(__file__)))
    curdir = os.getcwd()

    # First look on the command line for a desired config file,
    # if it's not on the command line, then look for 'setup.py'
    # in the current directory. If there, load configuration
    # from a file called 'dev.cfg'. If it's not there, the project
    # is probably installed and we'll look first for a file called
    # 'prod.cfg' in the current directory and then for a default
    # config file called 'default.cfg' packaged in the egg.
    #if len(sys.argv) > 1:
    #    configfile = sys.argv[1]
    if exists(join(setupdir, "setup.py")):
        configfile = join(setupdir, "dev.cfg")
    elif exists(join(curdir, "prod.cfg")):
        configfile = join(curdir, "prod.cfg")
    else:
        try:
            configfile = pkg_resources.resource_filename(
              pkg_resources.Requirement.parse("tginvoice"),
                "config/default.cfg")
        except pkg_resources.DistributionNotFound:
            raise ConfigurationError("Could not find default configuration.")
    return configfile

def start():
    """Start the CherryPy application server."""
    configfile = _get_configfile()

    turbogears.update_config(configfile=configfile,
        modulename="tginvoice.config")
    turbogears.config.update(dict(package="tginvoice"))
    from tginvoice import loader
    from tginvoice.controllers.root import Root
    root = Root()
    turbogears.start_server(root)

def admin():
    configfile = _get_configfile()

    turbogears.update_config(configfile=configfile,
        modulename="tginvoice.config")
    turbogears.config.update(dict(package="tginvoice"))
    from tginvoice import loader
    loader = loader.Loader(turbogears.config)
    usage = "%s COMMAND [...]"%(loader.APPNAME+"-admin")
    description = "Available commands:\n"
    for cmd in loader.COMMANDS:
        description += " %-23s %s\n"%(cmd,
            loader.COMMANDS[cmd].__summary__)


    if len(sys.argv)>1:
        cmd = sys.argv[1]
        if cmd == '-h' or cmd == '--help':
            print usage
            print
            print description
            sys.exit()
    else:
        print usage
        print
        print description
        sys.exit()
    if not cmd in loader.COMMANDS:
        sys.stderr.write("unknown command '%s'\n" % (cmd))
        print usage
        print
        print description
        sys.exit()
    else:
        loader.COMMANDS[cmd].main(loader)
