#!/bin/bash

#time bash $(dirname $0)/timed "$@"

timed()
{
	# Default to all .d direcories.
	DIRS=$(find . -type d -name '*.d' | sort)

	if [ -f /proc/cpuinfo ]; then
		CORES=$(awk '/cpu cores/ { print $4; exit }' /proc/cpuinfo)
	else
		CORES=$(sysctl -n hw.physicalcpu)
	fi


	if ! echo $CORES | grep -q '^[1-9][0-9]\?$'; then
		echo "warning: could not determine number of cores, using 2"
		CORES=2
	fi

	HERE=$(basename $(pwd))
	if [ "${HERE%.d}" != "$HERE" ]; then
		# In a test directory. Set DIR to . and pass any arguments to the local
		# gentests.
		DIRS=.
		ARGS="$@"
	elif [ $# != 0 ]; then
		# Args on the command line, but not in .d. Assume they are test cases.
		DIRS=$(find "$@" -type d -name '*.d')
	fi

	GENTEST_LOG=`mktemp /tmp/gentest.XXXXXX`

	for D in $DIRS; do
		cd $D
		echo ---- in $D
		./gentests $ARGS 2>> $GENTEST_LOG | xargs -n1 -P$CORES bash
		WORKING="$WORKING $D/working"
		cd $OLDPWD
	done

	CASES=`find $WORKING -name '*.sh' -not -size 0 | wc -l`
	FAILURES=`find $WORKING -name '*.diff' -not -size 0 | wc -l`

	find $WORKING -name '*.diff' -not -size 0

	echo ---- cases
	echo $CASES
	echo ---- failures
	echo $FAILURES

	INTERNAL_ERRORS=""

	if [ -s $GENTEST_LOG ]; then
		echo ---- internal errors
		cat $GENTEST_LOG
	fi

	if test -s $GENTEST_LOG; then
		INTERNAL_ERRORS="yes"
	fi

	rm -f $GENTEST_LOG

	#
	# Exit with 1 if runtests experienced some internal error. Exit with 2 if a
	# test failed. Otherwise 0.
	#

	if [ "$INTERNAL_ERRORS" = yes ]; then
		exit 1;
	elif [ "$FAILURES" != "0" ]; then
		exit 2
	fi

}

if [ "$0" = 'timed' ]; then
	timed "$@"
else
	time bash -c ". $0" timed "$@"
fi
