#!/bin/sh

AWK=../lmawk
TROOT_DIR=../../../../vendor/3rd_tests

if test -f ./Test.conf
then
	. ./Test.conf
fi

if test -z "$TEST_FILES"
then
	TEST_FILES=g.*.sh
fi

if test -z "$TEST_GAWK_DEFAULT" -a -f gawk_default.list
then
	TEST_GAWK_DEFAULT=`grep -v "^#" gawk_default.list`
fi


if test -z "$TEST_GAWK_ERROR" -a -f gawk_error.list
then
	TEST_GAWK_ERROR=`grep -v "^#" gawk_error.list`
fi

GAWK_DIR=$TROOT_DIR/gawk-4.1.1/test
BWK_DIR=$TROOT_DIR/bwk/test

pass_cnt=0
fail_cnt=0
unkn_cnt=0

implementation=`basename $AWK`

announce()
{
	announced=1
	if test "$1" = 0
	then
		echo -n "pass"
		pass_cnt=$(($pass_cnt + 1))
	else
		echo -n "FAIL"
		fail_cnt=$(($fail_cnt + 1))
		fail_list="$fail_list $2"
		echo "$3" > "$2.diff"
		if test ! -z "$STOP_WHEN_TEST_FAILS"
		then
			echo ""
			echo "First failure, have to stop because STOP_WHEN_TEST_FAILS sais so."
			exit 1
		fi
	fi
	if test ! -z "$4" -a "$1" = 0
	then
		rm "$4"
	fi
}

pre_ann()
{
	announced=0
	echo -n "$n: "
}

post_ann()
{
	if test "$announced" -gt 0
	then
		echo ""
	else
		echo "???"
		unkn_cnt=$(($unkn_cnt+1))
	fi
}

gen_testname()
{
	testname=${n%%.sh}
	testname=${testname##g.}
	testname=${testname##t.}
}

gawk_run_()
{
	if test -f "$GAWK_DIR/$1.in"
	then
		$AWK -v "SRCDIR=$GAWK_DIR" -v "srcdir=$GAWK_DIR" -f "$GAWK_DIR/$1.awk" <"$GAWK_DIR/$1.in" >"$1.out" 2>&1
	else
		echo "" | $AWK -v "SRCDIR=$GAWK_DIR" -v "srcdir=$GAWK_DIR" -f "$GAWK_DIR/$1.awk" >"$1.out" 2>&1
	fi
}

gawk_default_test()
{
	local okfile
	gawk_run_ "$1"
	if test -f "local.$implementation/$1.ok"
	then
		okfile="local.$implementation/$1.ok"
	else
		okfile="$GAWK_DIR/$1.ok"
	fi
	dif=`diff -u "$okfile" "$1.out"`
	announce "$?" "$1" "$dif" "$1.out"
}

gawk_error_test()
{
	local res err
	gawk_run_ "$1"
	if test "$?" == 0
	then
		# should have returned false but it's true!
		res=1
		echo ""
		echo "*** exit status 0 ***" >> "$1.out"
	else
		case $AWK in
			*mawk*)
				# it's false, but check for a compile-time error
				err=`grep ": line [0-9]\+:" "$1.out"; grep ": run time error:" "$1.out"`
				if test -z "$err"
				then
					res=1
					echo "*** doesn't look like a compile time or run time error ***" >> "$1.out"
				else
					res=0
				fi
				;;
			*) res=0 ;;
			esac
	fi
	announce "$res" "$1" "$dif" "$1.out"
}

if test ! -z "$TEST_FILES"
then
	for n in $TEST_FILES
	do
		gen_testname $n
		pre_ann $n
		. ./$n
		post_ann
	done
fi

if test ! -z "$TEST_GAWK_DEFAULT"
then
	for n_ in $TEST_GAWK_DEFAULT
	do
		n=g.$n_
		testname=$n_
		pre_ann
		gawk_default_test $testname
		post_ann
	done
fi

if test ! -z "$TEST_GAWK_ERROR"
then
	for n_ in $TEST_GAWK_ERROR
	do
		n=g.$n_
		testname=$n_
		pre_ann
		gawk_error_test $testname
		post_ann
	done
fi

echo "================"
echo "All: $(($pass_cnt + $fail_cnt + $unkn_cnt))   pass: $pass_cnt    ???: $unkn_cnt    fail: $fail_cnt"
if test ! -z "$fail_list"
then
	echo "Tests failed:$fail_list"
fi
