#!/usr/libexec/platform-python

import sys
import classad2 as classad
import htcondor2 as htcondor


def makeClassAd(adString, from_file=False):
    # If we're looking at the output from `condor_[q|status] -long:new`,
    # make it parseable by throwing away the opening '{\n'.  The ClassAd
    # constructor already ignores any ad past the first.
    if from_file and adString.startswith('{\n') and adString.endswith('\n}\n'):
        adString = adString[2:]

    try: return classad.ClassAd(adString)
    except classad.ClassAdException:
        modifiedAdString = "[" + adString + "]"
        return classad.ClassAd(modifiedAdString)


def usage(path):
    print("Usage: {0} [options] <expr|assignment>[ <expr|assignment>]*".format(path))
    print("");
    print("Evaluate ClassAd expressions.")
    print("Assignments modify the ClassAd context.");
    print("")
    print("Where [options] is one of")
    print("\t-[my-]file   <file>\tA file containing the initial ClassAd context");
    print("\t-target-file <file>\tA file containing the target ClassAd");
    print("\t-debug             \tEnable debug mode" );
    print("\t-help              \tPrint this screen and exit");
    print("")
    print("Flags may replace expressions or assignments:")
    print("\t-quiet             \tDon't print the ClassAd context after this flag");


def evaluateAndPrint(argv):
    i = 1
    quiet = False
    updated = True
    targetAd = None
    myAd = classad.ClassAd()
    while i < len(argv):
        arg = argv[i]

        if arg == '-quiet':
            quiet = True
        elif arg == "-file" or arg == "-my-file":
            i += 1
            if i >= len(argv):
                print("{0}: {1} requires an argument".format(argv[0], arg), file=sys.stderr)
                return -1
            adStringFileName = argv[i]
            adString = open(adStringFileName).read()
            try:
                myAd = makeClassAd(adString, from_file=True)
            except classad.ClassAdException:
                sys.exit("Unable to turn file '" + adStringFileName + "' into a ClassAd.")
        elif arg == '-target-file':
            i += 1
            if i >= len(argv):
                print("{0}: {1} requires an argument".format(argv[0], arg), file=sys.stderr)
                return -1
            adStringFileName = argv[i]
            adString = open(adStringFileName).read()
            try:
                targetAd = makeClassAd(adString, from_file=True)
            except classad.ClassAdException:
                sys.exit("Unable to turn file '" + adStringFileName + "' into a ClassAd.")
        elif arg == "-debug":
            htcondor.enable_debug()
        elif arg == "-help":
            usage(argv[0])
            return -1
        else:
            try:
                newAd = makeClassAd(arg)
                myAd.update(newAd)
                updated = True
            except classad.ClassAdException:
                try:
                    if updated:
                        updated = False
                        if not quiet:
                            print(repr(myAd))
                    expr = classad.ExprTree(arg)
                except classad.ClassAdException:
                    sys.exit("Unable to turn '" + arg + "' into a ClassAd or an expression.")

                result = expr.simplify(myAd, targetAd)
                print(repr(result))
        i += 1

    return 0


def main():
    return evaluateAndPrint(sys.argv)

if __name__ == "__main__":
    exit(main())
