#!/bin/sh -e
# Regression test framework (modeled on perl's if you can't tell).

# Call this function to test something.
ok () {
	local name=$1 expected_return=$2 expected_output=$3
	shift 3
	
	testcount=$(($testcount + 1))
	echo -n "compare '$name' '$testcount' '$expected_output' '$expected_return' '"
	set +e
	"$@"
	echo "' $?"
	set -e
}

# Call this function last say how many tests you should have run.
tests () {
	echo expected=$1
	echo testcount=$testcount
}

# This is uber-disgusing. Our IFS is messed up, so this gets the full output
# of the test program. It then parses it.
testfailures=0
compare () {
	while :; do
		local name=$1 count=$2 expected_output=$3 expected_return=$4 output=$5 return=$6 id
		shift 6
		if [ "$name" ]; then
			id="$name($count)"
		else
			id=$count
		fi
		if [ "$expected_return" != "$return" ]; then

			say "test $id FAILED: expected return code $expected_return, but got $return"
			testfailures=$(($testfailures + 1))
		elif [ "$expected_output" = "$output" ]; then
			if [ "$VERBOSE" ]; then
				say "test $id succeeded"
			fi
		else
			say "test $id FAILED: expected \`$expected_output', but got \`$output'"
			testfailures=$(($testfailures + 1))
		fi
		
		if [ "$1" != compare ]; then
			break
		fi
		shift
	done
	eval $@
}

say () {
	if [ -z "$spoke" ]; then
		spoke=1
		echo
	fi
	echo "	$*"
}

totaltestcount=0
totalfailures=0

if [ "$1" ]; then
	for script in "$@"; do
		# This part runs a regression test script (which uses the code above),
		# and parses the output to print a human-readable summary.
			
		spoke=""
		echo -n Beginning test of $script ..
		testcount=0
		eval `. $script || echo woah`
		if [ "$expected" -a "$expected" != "$testcount" ]; then
			say "($expected tests were expected, but $testcount were run)"
		fi
		if [ "$testfailures" != 0 ]; then
			echo ".. $testfailures test(s) FAILED."
		else
			if [ "$spoke" ]; then
				echo -n ".."
			fi		
			echo " all test(s) successful."
		fi

		totalfailures=$(($totalfailures + $testfailures)) || true
		totaltestcount=$(($totaltestcount + $testcount)) || true
	done
	echo
	echo "Regression test summary:"
	echo "	A total of $totaltestcount individual tests were ran,"
	echo -n "	from $(($#)) regression test scripts. "
	if [ "$totalfailures" != 0 ]; then
		echo "Of those, $totalfailures tests FAILED."
		exit 1
	else
		echo "All succeeded."
	fi
fi
