import sys
import os
import urllib2
import subprocess

def do_compile(address, filename, username, modulename, mode, optionals=[], grammar="grammars/actionlanguage.g"):
    filename = os.path.realpath(filename)
    try:
        urllib2.urlopen(urllib2.Request(address, 'op=set_input&username=user_manager&value="%s"' % username)).read()
        subprocess.check_call([sys.executable, "hutn_compiler/compiler.py", filename, grammar, mode, username, modulename, filename, address] + optionals, cwd="interface/HUTN")
    except urllib2.URLError:
        return 2
    except:
        urllib2.urlopen(urllib2.Request(address, 'op=set_input&username=user_manager&value="__%s"' % username)).read()
        return 1
    urllib2.urlopen(urllib2.Request(address, 'op=set_input&username=user_manager&value="__%s"' % username)).read()
    return 0

if __name__ == "__main__":
    if len(sys.argv) != 6:
        sys.stderr.write("Expected different parameters!\n")
        sys.stderr.write("    %s address filename username modulename mode\n" % sys.argv[0])
        sys.exit(1)
    else:
        address = sys.argv[1]
        filename = sys.argv[2]
        username = sys.argv[3]
        modulename = sys.argv[4]
        mode = sys.argv[5]
        
        sys.exit(do_compile(address, filename, username, modulename, mode))
