#! /bin/sh
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

: ${TMPDIR:=/tmp}
export TMPDIR

# basic /bin/sh syntax
SUFFIX=$( ${THIS_SH} -c 'echo $(( $RANDOM + $BASHPID ))' )

BASH_TSTOUT=${TMPDIR}/bashtst-$SUFFIX	# for now
export BASH_TSTOUT

trap 'rm -f $BASH_TSTOUT ; exit' 1 2 3 15
trap 'rm -f $BASH_TSTOUT' 0

PATH=.:$PATH	# just to get recho/zecho/printenv if not run via `make tests'
export PATH

# unset BASH_ENV only if it is set
[ "${BASH_ENV+set}" = "set" ] && unset BASH_ENV
# can't reliably do it for SHELLOPTS; SHELLOPTS is readonly in bash
if [ "${BASH_VERSION+set}" = "set" ]; then
	export -n SHELLOPTS	# just make sure its not exported
	set +o posix
	typeset -p SHELLOPTS
else
	[ "${SHELLOPTS+set}" = "set" ] && unset SHELLOPTS 2>/dev/null
fi
# ditto for BASHOPTS, which is also readonly in bash
if [ "${BASH_VERSION+set}" = "set" ]; then
	export -n BASHOPTS	# just make sure its not exported
else
	[ "${BASHOPTS+set}" = "set" ] && unset BASHOPTS 2>/dev/null
fi

: ${THIS_SH:=../bash}
export THIS_SH

: ${BUILD_DIR:=..}
export BUILD_DIR

${THIS_SH} ./version

rm -f ${BASH_TSTOUT}

export TAB='	'

echo Any output from any test, unless otherwise noted, indicates a possible anomaly

# keep track of passed and failed tests and report them
if [ -t 1 ]; then
	# can't rely on having $'...' or printf understanding \e
	# bright red background, white foreground text
	CSTART=$(printf '\033[01;101;37m') CEND=$(printf '\033[0m')
else
	CSTART= CEND=
fi

passed=0
total=0
failed=0

if [ -n "$BASH_TSTOUT_SAVEDIR" ] && [ -d "$BASH_TSTOUT_SAVEDIR" ]; then
	echo "Using $BASH_TSTOUT_SAVEDIR to save output from failed tests"
else
	unset BASH_TSTOUT_SAVEDIR
fi

for x in run-*
do
	case $x in
	$0|run-minimal|run-gprof)	;;
	*.orig|*.save|*~) ;;
	*)	echo $x
		total=$(( $total + 1 ))
		if sh $x; then
			passed=$(( $passed + 1 ))
		else
			failed=$(( $failed + 1 ))
			echo "${CSTART}${x}: NON-ZERO exit status $?${CEND}"
			if [ -n "$BASH_TSTOUT_SAVEDIR" ]; then
				mv ${BASH_TSTOUT} ${BASH_TSTOUT_SAVEDIR}/${x}-${SUFFIX}
				echo "${CSTART}output saved to ${BASH_TSTOUT_SAVEDIR}/${x}-${SUFFIX}${CEND}"
			elif [ $failed -eq 1 ]; then
				echo "${CSTART}Set environment variable BASH_TSTOUT_SAVEDIR to a directory to save failed test output${CEND}"
			fi
		fi
		rm -f ${BASH_TSTOUT}
		;;
	esac
done

echo "${CSTART}${passed}/${total} tests succeeded${CEND}"
exit $failed
