#!/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
        # determine destinations for script and ini
        if narg >= 4:
            inidst = sys.argv.pop(2) # remove new
        else:
            inidst = "mokefile.ini"
        if narg >= 3:
            scrdst = sys.argv.pop(1) # remove new mokefile name
        else:
            scrdst = "mokefile.py"
        # sources
        scr = os.path.join(os.path.dirname(moke.__file__), "data", "mokefile.py")
        ini = os.path.join(os.path.dirname(moke.__file__), "data", "mokefile.ini")
        # destinations
        scrdst = os.path.join(os.getcwd(), scrdst)
        inidst = os.path.join(os.getcwd(), inidst)
        # copy or fail
        if not os.path.exists(scrdst) and not os.path.exists(inidst):
            shutil.copy(scr, scrdst)
            shutil.copy(ini, inidst)
        else:
            sys.exit("moke: *** File %s or %s already exists. Stop." % (scrdst, inidst))
        # run with new
        sys.stderr.write("moke: *** Created %s and %s\n" % (scrdst, inidst))
        sys.stderr.write("moke: *** Running 'moke%s--help'\n" % \
                             (" %s " % scrdst if scrdst != "mokefile.py" else " "))
        sys.argv.append("--help")
        
    # moke arg1 options ...
    if narg >= 2:
        mokefile = "mokefile.py"
        for argidx in xrange(1, len(sys.argv), 2):
            if sys.argv[argidx] == "-f":
                # remove fmokefileile
                mokefile = sys.argv[argidx + 1]
                sys.argv.pop(argidx)
                sys.argv.pop(argidx)
                break
        print mokefile
        if not os.path.isfile(mokefile):
            sys.exit("moke: *** No %s found. Try 'moke new'. Stop." % mokefile)            
    
    # 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)
