#!/bin/bash
export RED='\e[0;31m'
export GRN='\e[0;32m'
export YLW='\e[0;33m'
export NC='\e[0m' # No Colour

TOP_LEVEL=`dirname $0`/..
SYSFS_TEST_DIR=$TOP_LEVEL/opal_errd/sysfs-test/
ALL_TESTS=$TOP_LEVEL/opal_errd/tests/*
TEST_RESULTS=$TOP_LEVEL/opal_errd/tests-results
PLAT_PREFIX=

export OPAL_ERRD_DIR=$TOP_LEVEL/opal_errd
export SYSFS=`mktemp -d --tmpdir ppc64-diag-run_tests.sysfs.XXXXXXXXXX`
export OUT=`mktemp -d --tmpdir ppc64-diag-run_tests.out.XXXXXXXXXX`
export LOG=`mktemp --tmpdir ppc64-diag-run_tests.log.XXXXXXXXXX`
export OUTSTDERR=`mktemp --tmpdir ppc64-diag-run_tests.stderr.XXXXXXXXXX`
export OUTSTDOUT=`mktemp --tmpdir ppc64-diag-run_tests.stdout.XXXXXXXXXX`

function check_suite {
	#Do some basic checks that the user isn't trying to run this directly
	if [[ -z "${SYSFS:+x}" ]] ; then
		echo "Fatal error, you do not appear to be running this script in
		the ppc64-diag test suite";
		exit 1;
	fi
}

function copy_sysfs {
	cp -pr ${SYSFS_TEST_DIR}/* $SYSFS/
}

function run_binary {
	if [[ -x $OPAL_ERRD_DIR/$1 ]] ; then
		$VALGRIND $OPAL_ERRD_DIR/$1 $2 2>> $OUTSTDERR 1>> $OUTSTDOUT
	else
		echo "Fatal error, cannot execute binary '$1'. Did you make?";
		exit 1;
	fi
}

function diff_with_result {
	# Explicitly diff a file with an arbitrary result file
	if [[ $# -eq 1 ]] ; then
		if ! diff -u $RESULT $1 ; then
			register_fail;
		fi
	# Otherwise just diff result.out with stdout and result.err with stderr
	else
		if ! diff -u ${RESULT}.out $OUTSTDOUT ; then
			register_fail;
		fi
		if ! diff -u ${RESULT}.err $OUTSTDERR ; then
			register_fail;
		fi
	fi
	register_success;

}

function register_success {
	/bin/true
}

function register_fail {
	echo "FAIL $CUR_TEST with RC ${1:-undef}";
	exit ${1:-1};
}

Q=0
all_tests=$ALL_TESTS

while getopts ":qt:" opt; do
	case "$opt" in
		q)
			q=1
			;;
		t)
			all_tests=$OPTARG
	esac
done

grep -q pSeries /proc/cpuinfo && PLAT_PREFIX=".pseries"

for the_test in $all_tests; do
	export CUR_TEST=$(basename $the_test)
	export RESULT="$TEST_RESULTS/$CUR_TEST.result$PLAT_PREFIX"
	if [[ ! -f $RESULT.err ]] && [[ ! -f $RESULT.out ]] ; then
		export RESULT="$TEST_RESULTS/$CUR_TEST.result"
	fi
	if [[ $q -eq 1 ]] ; then
		source "$the_test"
	else
		source "$the_test"
	fi
	R=$?
	if [[ $R -ne 0 ]] ; then
		echo -e "${RED}$the_test FAILED with RC $R${NC}"
		exit $R
	fi
	#reset for next test
	rm -rf $SYSFS/*
	rm -rf $OUT/*
	> $LOG
	> $OUTSTDERR
	> $OUTSTDOUT
done

rm -rf $SYSFS $OUT $LOG $OUTSTDERR $OUTSTDOUT
echo PASS
exit 0
