#!/usr/bin/env python2.7
import runpy
import os
import shutil
import sys

try:
    import moke
except ImportError:
    sys.exit("moke: *** Not properly installed.  Stop.")

if __name__ == "__main__":
    sys.path.insert(0, os.getcwd())
    if len(sys.argv) > 1 and sys.argv[1] != "--help":
        arg1 = sys.argv.pop(1)
        if os.path.isfile(arg1):
            mokefile = arg1
        elif arg1 == "new":
            src = os.path.join(os.path.dirname(moke.__file__), "data", "mokefile.py")
            if len(sys.argv) > 1:
                mokefile = sys.argv.pop(1)
            else:
                mokefile = "mokefile.py"
            dst = os.path.join(os.getcwd(), mokefile)
            if not os.path.exists(dst):
                shutil.copy(src, dst)
                sys.stderr.write("moke: *** Created %s\n" % dst)
                sys.stderr.write("moke: *** Running 'moke%s--help'\n" % \
                                 (" %s " % mokefile if mokefile != "mokefile.py" else " "))
                sys.argv.append("--help")
            else:
                sys.exit("moke: *** File %s already exists. Stop." % dst)
    elif len(sys.argv) > 1 and sys.argv[1] == "--help":
        sys.exit("moke: run 'moke new'")
    else: 
        if os.path.exists("mokefile.py"):
            mokefile = "mokefile.py"
        else:
            sys.exit("moke: *** No mokefile.py found.  Stop.")
    # run mokefile and make it thing it is executed
    ret =  runpy.run_path(mokefile, run_name="__main__")
    gottask = any([isinstance(obj, moke.core.task) for obj in ret.itervalues()])
    if not gottask:
        sys.exit("moke: *** No task specified in %s.  Stop." % mokefile)
