#!/usr/bin/python
#
# File: check-compliance.py
# Wrapper script around a policy
#
# Workflow:
# 0. User calls "check-compliance POLICY NEW_QUERY QUERY_HISTORY" wrapper script.
#    POLICY is an AIR policy; NEW_QUERY is a query in n3, perhaps the output
#    of the sparql2n3 script, and QUERY_HISTORY is a file with the query history.
# 1. Wrapper script appends NEW_QUERY to the history file in QUERY_HISTORY,
#    say, history.n3. This accomplishes three things:
#    a. We only need to look at QUERY_HISTORY when reasoning, making it much
#       easier to automatically generate policies that only grow linearly with
#       the number of terms.
#    b. AIR will explicitly know which query is the current (new) query.
#    c. This guarantees that the QUERY_HISTORY is never empty, eliminating a
#       tricky edge case.
# 2. Wrapper script writes NEW_QUERY to a file, say, query.n3. This is redundant
#    since, for now, NEW_QUERY is a file!
# 3a.Wrapper generates QUERY_DESCRIPTOR with the new_query and query_history.
# 3. Wrapper script calls policyrunner.py, and returns the output of
#    policyrunner.py for viewing.
# 4. (Optional) If policy is non compliant, we can remove it from the history
#    file.
#
# I'm exhibiting poor practice in making this UNIX-specific. Oh well.

import sys
import os

def main():
    # First, a whole bunch of code just to handle command line options.
    from optparse import OptionParser
    usage = "usage: %prog [options] policy new_query query_descriptor"
    version = "%prog version 0.1, 2009-07-08"
    description = """POLICY is an AIR policy; NEW_QUERY is a query in n3, perhaps the output of the sparql2n3 script, and QUERY_DESCRIPTOR is a file like query-req.n3 that defines the location of the query and history files.
    """
    parser = OptionParser(usage=usage, version=version, description=description)
    parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Prints additional debugging output.")
    (options, args) = parser.parse_args()
    if len(args) != 3:
        print "Not enough (or too many) arguments! See -h for usage. Exiting..."
        sys.exit()
    # We now have our three files. Let's get their absolute paths.
    args[0] = os.path.abspath(args[0])
    args[1] = os.path.abspath(args[1])
    args[2] = os.path.abspath(args[2])
    if options.verbose:
        print "Chatty mode! Running with verbosity enabled."
        print "POLICY file: " + args[0]
        print "QUERY input: " + args[1]
        print "DESCRIPTION: " + args[2]
    # Append the new query to the query history.
    command = "cat " + args[1] + " >> " + args[2]
    os.system(command)
    # Generate a query descriptor
    descriptor = """# query descriptor auto-generated by check-compliance.py
@prefix s: <http://dig.csail.mit.edu/2009/IARPA-PIR/sparql#> .
@prefix : <http://dig.csail.mit.edu/2009/IARPA-PIR/query1#> .
[] a s:ComplianceQuery;
   s:Query <file://""" + args[1] + """>;
   s:History <file://""" + args[2] + """>.
"""
#   s:query <file://""" + args[1] + """>;
#   s:query :Query-1;
    # Write the query descriptor to a temporary file.
    fname = '/tmp/query_req_%s.n3' % os.getpid()
    f = open(fname, 'w+b')
    f.write(descriptor)
    f.close()
    # Get the full path of the temp file and print it.
    if options.verbose:
        print "Created the temporary file" + fname
        command = "cat " + fname
        os.system(command)
    # Generate and run the policyrunner command.
    command = "policyrunner test file://" + args[0] + " file://" + args[2] + " file://" + fname
#command = "policyrunner test file://" + args[0] +" file://" + fname
    if options.verbose:
        print command
    os.system(command)
    # Clean our garbage.
    os.remove(fname)


 
if __name__ == "__main__":
    main()

