#!python
from __future__ import print_function

from os import listdir, environ
from os.path import isfile, join, splitext
from subprocess import Popen, PIPE, STDOUT

import argparse
import os
import re
import sys

################################################################################
#               help functions
################################################################################
def listTests():
	list = [splitext(f)[0] for f in listdir('./.expect')
		if not f.startswith('.') and f.endswith('.txt')
		]

	return list

def sh(cmd, dry_run):
	if dry_run :
		print("cmd: %s" % cmd)
		return 0
	else :
		proc = Popen(cmd, stderr=STDOUT, shell=True)
		proc.communicate()
		return proc.returncode

def file_replace(fname, pat, s_after):
    # first, see if the pattern is even in the file.
    with open(fname) as f:
        if not any(re.search(pat, line) for line in f):
            return # pattern does not occur in file so we are done.

    # pattern is in the file, so perform replace operation.
    with open(fname) as f:
        out_fname = fname + ".tmp"
        out = open(out_fname, "w")
        for line in f:
            out.write(re.sub(pat, s_after, line))
        out.close()
        os.rename(out_fname, fname)

def fix_MakeLevel(file) :
	if environ.get('MAKELEVEL') :
		file_replace(file, "make\[%i\]" % int(environ.get('MAKELEVEL')), 'make' )


################################################################################
#               running test functions
################################################################################
def run_test_instance(test, generate, dry_run):

	out_file = (".out/%s.log" % test) if not generate else (".expect/%s.txt" % test)

	sh("rm -f %s" % out_file, dry_run)
	sh("rm -f %s > /dev/null 2>&1" % test, dry_run)

	# build, skipping to next test on error
	make_ret = sh("make -j 8 %s 2> %s 1> /dev/null" % (test, out_file), dry_run)

	if make_ret == 0 :
		# fetch optional input
		stdinput = "< .in/%s.txt" % test if isfile(".in/%s.txt" % test) else ""

		# run test
		sh("./%s %s > %s 2>&1" % (test, stdinput, out_file), dry_run)

	retcode = 0

	fix_MakeLevel(out_file)

	if not generate :
		# diff the output of the files
		retcode = sh("diff .expect/%s.txt .out/%s.log" % (test, test), dry_run)

	# clean the executable
	sh("rm -f %s > /dev/null 2>&1" % test, dry_run)

	return retcode

def run_tests(tests, generate, dry_run) :
	sh('make clean > /dev/null 2>&1', dry_run)
	sh('mkdir -p .out .expect', dry_run)

	if generate :
		print( "Regenerate tests for: " )

	failed = False;
	for t in tests:
		print("%20s  " % t, end="")
		sys.stdout.flush()
		test_failed = run_test_instance(t, generate, dry_run)
		failed = test_failed or failed

		if not generate :
			print("FAILED" if test_failed else "PASSED")
		else :
			print( "Done" )

	sh('make clean > /dev/null 2>&1', dry_run)

	return 1 if failed else 0

################################################################################
#               main loop
################################################################################
parser = argparse.ArgumentParser(description='Script which runs cforall tests')
parser.add_argument('--dry-run', help='Don\'t run the tests, only output the commands', action='store_true')
parser.add_argument('--list', help='List all test available', action='store_true')
parser.add_argument('--all', help='Run all test available', action='store_true')
parser.add_argument('--regenerate-expected', help='Regenerate the .expect by running the specified tets, can be used with --all option', action='store_true')
parser.add_argument('tests', metavar='test', type=str, nargs='*', help='a list of tests to run')

options = parser.parse_args()

if (len(options.tests) > 0  and     options.all and not options.list) \
or (len(options.tests) == 0 and not options.all and not options.list) :
	print('ERROR: must have option \'--all\' or non-empty test list', file=sys.stderr)
	parser.print_help()
	sys.exit(1)

allTests = listTests()

if options.all or options.list :
	tests = allTests

else :
	tests = []
	for test in options.tests:
		if test in allTests :
			tests.append(test)
		else :
			print('ERROR: No expected file for test %s, ignoring it' % test, file=sys.stderr)

	if len(tests) == 0 :
		print('ERROR: No valid test to run', file=sys.stderr)
		sys.exit(1)

if options.list :
	print("\n".join(tests))

else :
	sys.exit( run_tests(tests, options.regenerate_expected, options.dry_run) )
