#!/usr/bin/python3

from pybin.tools import *
from pybin.test_run import *
from pybin import settings

import argparse
import re
import sys
import tempfile
import time

################################################################################
#               help functions
################################################################################

def find_tests():
	expected = []

	def match_test(path):
		match = re.search("^%s\/([\w\/\-_]*).expect\/([\w\-_]+)(\.[\w\-_]+)?\.txt$" % settings.SRCDIR, path)
		if match :
			test = Test()
			test.name = match.group(2)
			test.path = match.group(1)
			test.arch = match.group(3)[1:] if match.group(3) else None
			if settings.arch.match(test.arch):
				expected.append(test)

	path_walk( match_test )

	return expected

# reads the directory ./.expect and indentifies the tests
def list_tests( includes, excludes ):
	# tests directly in the .expect folder will always be processed
	test_list = find_tests()

	# if we have a limited number of includes, filter by them
	if includes:
		test_list = [x for x in test_list if
			x.target().startswith( tuple(includes) )
		]

	# # if we have a folders to excludes, filter by them
	if excludes:
		test_list = [x for x in test_list if not
			x.target().startswith( tuple(excludes) )
		]

	return test_list

# from the found tests, filter all the valid tests/desired tests
def valid_tests( options ):
	tests = []

	# if we are regenerating the tests we need to find the information of the
	# already existing tests and create new info for the new tests
	if options.regenerate_expected :
		for testname in options.tests :
			testname = canonical_path( testname )
			if Test.valid_name(testname):
				found = [test for test in all_tests if canonical_path( test.target() ) == testname]
				tests.append( found[0] if len(found) == 1 else Test.from_target(testname) )
			else :
				print('ERROR: "%s", tests are not allowed to end with a C/C++/CFA extension, ignoring it' % testname, file=sys.stderr)

	else :
		# otherwise we only need to validate that all tests are present in the complete list
		for testname in options.tests:
			test = [t for t in all_tests if path_cmp( t.target(), testname )]

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

	return tests

# parses the option
def parse_args():
	# create a parser with the arguments for the tests script
	parser = argparse.ArgumentParser(description='Script which runs cforall tests')
	parser.add_argument('--debug', help='Run all tests in debug or release', type=yes_no, default='yes')
	parser.add_argument('--install', help='Run all tests based on installed binaries or tree binaries', type=yes_no, default='no')
	parser.add_argument('--arch', help='Test for specific architecture', type=str, default='')
	parser.add_argument('--timeout', help='Maximum duration in seconds after a single test is considered to have timed out', type=int, default=60)
	parser.add_argument('--global-timeout', help='Maximum cumulative duration in seconds after the ALL tests are considered to have timed out', type=int, default=7200)
	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('-j', '--jobs', help='Number of tests to run simultaneously', type=int)
	parser.add_argument('--list-comp', help='List all valide arguments', action='store_true')
	parser.add_argument('-I','--include', help='Directory of test to include, can be used multiple time, All  if omitted', action='append')
	parser.add_argument('-E','--exclude', help='Directory of test to exclude, can be used multiple time, None if omitted', action='append')
	parser.add_argument('tests', metavar='test', type=str, nargs='*', help='a list of tests to run')

	try:
		options =  parser.parse_args()
	except:
		print('ERROR: invalid arguments', file=sys.stderr)
		parser.print_help(sys.stderr)
		sys.exit(1)

	# script must have at least some tests to run or be listing
	listing    = options.list or options.list_comp
	all_tests  = options.all
	some_tests = len(options.tests) > 0
	some_dirs  = len(options.include) > 0 if options.include else 0

	# check that exactly one of the booleans is set to true
	if not sum( (listing, all_tests, some_tests, some_dirs) ) > 0 :
		print('''ERROR: must have option '--all', '--list', '--include', '-I' or non-empty test list''', file=sys.stderr)
		parser.print_help()
		sys.exit(1)

	return options

################################################################################
#               running test functions
################################################################################
def success(val):
	return val == 0 or settings.dry_run

def no_rule(file, target):
	return not settings.dry_run and file_contains_only(file, "make: *** No rule to make target `%s'.  Stop." % target)

# logic to run a single test and return the result (No handling of printing or other test framework logic)
def run_single_test(test):

	# find the output file based on the test name and options flag
	exe_file = test.target_executable();
	out_file = test.target_output()
	err_file = test.error_log()
	cmp_file = test.expect()
	in_file  = test.input()

	# prepare the proper directories
	test.prepare()

	# build, skipping to next test on error
	with Timed() as comp_dur:
		make_ret, _ = make( test.target(), output=subprocess.DEVNULL, error=out_file, error_file = err_file )

	run_dur = None
	# run everything in a temp directory to make sure core file are handled properly
	with tempdir():
		# if the make command succeds continue otherwise skip to diff
		if success(make_ret):
			with Timed() as run_dur:
				if settings.dry_run or is_exe(exe_file):
					# run test
					retcode, _ = sh(exe_file, output=out_file, input=in_file, timeout=True)
				else :
					# simply cat the result into the output
					retcode = cat(exe_file, out_file)
		else:
			retcode = mv(err_file, out_file)

		if success(retcode):
			if settings.generating :
				# if we are ounly generating the output we still need to check that the test actually exists
				if no_rule(out_file, test.target()) :
					retcode = 1
					error = "\t\tNo make target for test %s!" % test.target()
					rm(out_file)
				else:
					error = None
			else :
				# fetch return code and error from the diff command
				retcode, error = diff(cmp_file, out_file)

		else:
			with open (out_file, "r") as myfile:
				error = myfile.read()

			ret, info = core_info(exe_file)
			error = error + info if error else info



	# clean the executable
	rm(exe_file)

	return retcode, error, [comp_dur.duration, run_dur.duration if run_dur else None]

# run a single test and handle the errors, outputs, printing, exception handling, etc.
def run_test_worker(t) :
	try :
		# print formated name
		name_txt = '{0:{width}}  '.format(t.target(), width=settings.output_width)

		retcode, error, duration = run_single_test(t)

		# update output based on current action
		result_txt = TestResult.toString( retcode, duration )

		#print result with error if needed
		text = '\t' + name_txt + result_txt
		out = sys.stdout
		if error :
			text = text + '\n' + error

		return retcode == TestResult.SUCCESS, text
	except KeyboardInterrupt:
		return False, ""
	except:
		print("Unexpected error in worker thread", file=sys.stderr)
		sys.stderr.flush()
		return False, ""


# run the given list of tests with the given parameters
def run_tests(tests, jobs) :
	# clean the sandbox from previous commands
	make('clean', output=subprocess.DEVNULL, error=subprocess.DEVNULL)

	# create the executor for our jobs and handle the signal properly
	pool = multiprocessing.Pool(jobs)

	failed = False

	# for each test to run
	try :
		num = len(tests)
		fancy = sys.stdout.isatty()
		results = pool.imap_unordered(
			run_test_worker,
			tests,
			chunksize = 1
		)

		for i, (succ, txt) in enumerate(timed(results, timeout = settings.timeout.total), 1) :
			if not succ :
				failed = True

			print("       " + txt)

			if(fancy and i != num):
				print("%d/%d" % (i, num), end='\r')
				sys.stdout.flush()

	except KeyboardInterrupt:
		print("Tests interrupted by user", file=sys.stderr)
		pool.terminate()
		pool.join()
		failed = True
	except multiprocessing.TimeoutError:
		print("ERROR: Test suite timed out", file=sys.stderr)
		pool.terminate()
		pool.join()
		failed = True
		killgroup() # needed to cleanly kill all children


	# clean the workspace
	make('clean', output=subprocess.DEVNULL, error=subprocess.DEVNULL)

	return 1 if failed else 0


################################################################################
#               main loop
################################################################################
if __name__ == "__main__":

	# parse the command line arguments
	options = parse_args()

	# init global settings
	settings.init( options )

	# fetch the liest of all valid tests
	all_tests = list_tests( options.include, options.exclude )


	# if user wants all tests than no other treatement of the test list is required
	if options.all or options.list or options.list_comp or options.include :
		tests = all_tests

	#otherwise we need to validate that the test list that was entered is valid
	else :
		tests = valid_tests( options )

	# make sure we have at least some test to run
	if not tests :
		print('ERROR: No valid test to run', file=sys.stderr)
		sys.exit(1)


	# sort the test alphabetically for convenience
	tests.sort(key=lambda t: (t.arch if t.arch else '') + t.target())

	# users may want to simply list the tests
	if options.list_comp :
		print("-h --help --debug --dry-run --list --arch --all --regenerate-expected --install --timeout --global-timeout -j --jobs ", end='')
		print(" ".join(map(lambda t: "%s" % (t.target()), tests)))

	elif options.list :
		print("Listing for %s:%s"% (settings.arch.string, settings.debug.string))
		fancy_print("\n".join(map(lambda t: t.toString(), tests)))

	else :
		# check the build configuration works
		settings.prep_output(tests)
		settings.validate()

		options.jobs, forceJobs = job_count( options, tests )
		settings.update_make_cmd(forceJobs, options.jobs)

		print('%s %i tests on %i cores (%s:%s)' % (
			'Regenerating' if settings.generating else 'Running',
			len(tests),
			options.jobs,
			settings.arch.string,
			settings.debug.string
		))

		# otherwise run all tests and make sure to return the correct error code
		sys.exit( run_tests(tests, options.jobs) )
