#!/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())
    narg = len(sys.argv)
    # moke
    if narg == 1:
        if os.path.exists("mokefile.py"):
            mokefile = "mokefile.py"
        else:
            sys.exit("moke: *** No mokefile.py found. Try 'moke new'. Stop.")
    # moke --new
    if narg >= 2 and sys.argv[1] == "--new":
        sys.argv.pop(1) # remove --new
        src = os.path.join(os.path.dirname(moke.__file__), "data", "mokefile.py")
        if narg == 3:
            mokefile = sys.argv.pop(1) # remove new mokefile name
        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)        
    # moke arg1 ...
    if narg >= 2:
        if os.path.isfile(sys.argv[1]):
            mokefile = sys.argv.pop(1)
        elif os.path.exists("mokefile.py"):
            mokefile = "mokefile.py"
        else:
            sys.exit("moke: *** No mokefile.py found. Try 'moke new'. 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)
