#!python
from __future__ import print_function

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

import argparse
import sys

################################################################################
#               help functions
################################################################################
def listTests():
	list = [f.rstrip('.c') for f in listdir('.')
		if not f.startswith('.') and (
			not isfile(f) or f.endswith('.c')
		)]

	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

################################################################################
#               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 > %s 2>&1" % (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
	if not generate :
		# touch expected files so empty output are supported by default
		sh("touch .expect/%s.txt" % test, dry_run)

		# 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: ", end="" )
		print( ", ".join( tests ) )

	failed = False;
	for t in tests:
		if not generate :
			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")

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

	if generate :
		print( "Done" )

	return 0 if failed else 1

################################################################################
#               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('--all', help='Run all test available', action='store_true')
parser.add_argument('--generate-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 :
	print('ERROR: must have option \'--all\' or non-empty test list', file=sys.stderr)
	parser.print_help()
	sys.exit(1)

tests = listTests() if options.all else options.tests

sys.exit( run_tests(tests, options.generate_expected, options.dry_run) )
