#! python
import argparse
from importlib import import_module
import shutil
import os
import sys
import jeev

parser = argparse.ArgumentParser(prog='jeev', description='Jeev')

subparsers = parser.add_subparsers(dest='command')
init_parser = subparsers.add_parser('init', help="Initializes an instance of jeev")
init_parser.add_argument('directory')
run_parser = subparsers.add_parser('run', help="Initializes an instance of jeev")
run_parser.add_argument('--config', default='config.py')

class Error(Exception):
    pass


def init(ns):
    import shutil
    try:
        import_module(ns.directory)
    except ImportError:
        pass
    else:
        raise Error("%r conflicts with the name of an existing "
                    "Python module and cannot be used as the name "
                    "of the jeev directory." % ns.directory)

    if os.path.exists(ns.directory):
        raise Error("Directory %r already exists." % ns.directory)

    starter_template_path = os.path.join(jeev.__path__[0], 'starter_template')
    shutil.copytree(starter_template_path, ns.directory, ignore=shutil.ignore_patterns("*.pyc"))
    print "Initialized jeev in", ns.directory
    print "You should now be able to change directory to it and then run 'jeev run'"


def run(ns):
    if os.getcwd() not in sys.path:
        sys.path.insert(0, os.getcwd())

    import imp
    try:
        config = imp.load_source('config', ns.config)
    except IOError:
        config = object()

    jeev.run(config)

try:
    ns = parser.parse_args(sys.argv[1:])
    globals()[ns.command](ns)

except Error, e:
    sys.stderr.write("ERROR: %s\n" % e.message)