#!/usr/bin/env python
import sys
import os


try:
    import sjq
except:
    sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'sjq'))
    try:
        import sjq
        assert sjq
    except:
        pass


try:
    import mvpipe
except:
    sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))
    import mvpipe


from mvpipe.support import autotype

def usage(msg=None):
    if msg:
        sys.stderr.write('%s\n' % msg)

    s="""\
MVpipe - HPC/HTC analysis pipelines

Usage: mvpipe {options} {args} filename {target1 target2...}

Arguments:
    filename       The filename of the pipeline to run
    target         The output file you want to build
                   (default: the first target in the pipeline)

Options:
    -l logfile     Log debug output to this file (default: none)
    -v             Verbose logging
    -dr            Dry run - don't actually submit jobs

    Additional pipeline-specific arguments can be set by using the format:
        --foo bar --arg one --arg two

    This will set the variable "foo" to be "bar", and "arg" to be a list:
    ["one", "two"]. These variables can then be used by the Pipeline script.

"""

    sys.stderr.write(s)
    sys.exit(1)

if __name__ == '__main__':
    fname = None
    logfile = None
    args = {}
    target = []
    verbose = False
    dryrun = False

    last = None
    for i, arg in enumerate(sys.argv[1:]):
        if i == 0 and os.path.exists(arg):
            fname = arg
        elif last:
            if last == '-l':
                logfile = arg
                last = None
            elif last[:2] == '--':
                var = last[2:]
                if arg[:2] == '--':
                    args[var] = True
                    last = arg
                else:
                    if var in args:
                        if type(args[var]) == list:
                            args[var].append(autotype(arg))
                        else:
                            args[var] = [args[var], autotype(arg)]
                    else:
                        args[var] = autotype(arg)
                    last = None
        elif arg == '-v':
            verbose = True
        elif arg == '-dr':
            dryrun = True
        elif arg in ['-h', '-help', '--help']:
            usage()
        elif arg[0] == '-':
            last = arg
        elif not fname and os.path.exists(os.path.expanduser(arg)):
            fname = arg
        else:
            target.append(arg)
        # else:
        #     sys.stderr.write("Don't know how to deal with argument: %s\n" % arg)
        #     sys.exit(1)

    pipe = None

    if not fname:
        usage()

    try:
        pipe = mvpipe.parse(fname, args, logfile=logfile, dryrun=dryrun, verbose=verbose)
        if target:
            for t in target:
                pipe.build(t)
        else:
            pipe.build(None)
        pipe.close()
    except mvpipe.ParseError, e:
        if pipe:
            pipe.abort()
        sys.stderr.write('%s\n' % e)
