#!/usr/bin/python

import optparse, os, string
from subprocess import call

parser = optparse.OptionParser()

parser.add_option('-d', '--debug',
    action='store_true', dest='debug',
    help='Build Debug Version', default=False)

parser.add_option('-e', '--execute', 
	action='store_true', dest='execute',
	help='Execute after build', default=False)

parser.add_option('-c', '--clean',
	action='store_true', dest='clean',
	help='Clean before build')

parser.add_option('-n', '--namespace',
    dest='namespace',
    help='Which debug file should be included', default='All')

parser.add_option('-m', '--memory',
    action='store_true', dest='memory',
    help='Run valgrind', default=False)

parser.add_option('-s', '--debug-syntax',
    action='store_true', dest='syntax',
    help='Debug Syntax Analysis', default=False)

parser.add_option('-t', '--test',
    action='store_true', dest='test',
    help='Run Tests', default=False)

parser.add_option('-r', '--track',
    action='store_true', dest='track',
    help='Track each function call', default=False)

parser.add_option('-a', '--expand-ast',
    action='store_true', dest='ast',
    help='Expand the ast', default=False)

options, args = parser.parse_args()

def runBuild():

    if options.clean: 
        call(['rm', '-rf', './CMakeCache.txt'])

    cmakeOptions = ['cmake']

    cmakeOptions.append('.')

    if options.debug:
        cmakeOptions.append('-DCMAKE_BUILD_TYPE=Debug')
    else:
        cmakeOptions.append('-DCMAKE_BUILD_TYPE=Release')

    cmakeOptions.append('-DDEBUG_NAMESPACE=' + options.namespace)

    if options.track:
        cmakeOptions.append('-DDEBUG_TRACK=1')

    if options.syntax:
        cmakeOptions.append('-DDEBUG_SYNTAX=1')

    if options.test:
        cmakeOptions.append('-DRUN_TESTS=1')

    if options.ast:
        cmakeOptions.append('-DEXPAND_AST=1')

    call(cmakeOptions)

    if options.clean:
    	call(['make', 'clean'])

    call(['make'])

    if options.execute:
    	call(['./build/condor'])

    if options.memory:
        call(['valgrind', '--leak-check=full', '--show-leak-kinds=all', '--track-origins=yes', '--log-file=mem.dump', './build/condor'])

if __name__ == "__main__":
    runBuild()