# This program runs ksh regression tests
# shtests [ name=value ... ] [ --all | --compile ] [ --time ] [ a.sh b.sh ... ]

timesensitive='*@(options|sigchld|subshell).sh'

unset DISPLAY ENV FIGNORE HISTFILE
LANG=C
LC_ALL=C
compile=1
script=1
time=1
vmdebug=a
while	:
do	case $1 in
	-a|--a*)compile=2
		script=2
		;;
	-c|--c*)compile=2
		script=
		;;
	-s|--s*)compile=
		script=2
		;;
	-t|--not*)time=
		;;
	-v|--nov*)vmdebug=
		;;
	-*)	echo $0: $1: invalid option >&2
		exit 2
		;;
	*=*)	n=${1%%=*}
		v=${1#*=}
		eval $n=\'$v\'
		export $n
		;;
	*)	break
		;;
	esac
	shift
done
if	[[ ! $vmdebug ]]
then	unset VMDEBUG
elif	[[ $VMDEBUG ]]
then	vmdebug=$VMDEBUG
else	export VMDEBUG=$vmdebug
fi
[[ $VMDEBUG ]] || timesensitive=.
export LANG LC_ALL PATH PWD SHELL
PWD=`pwd`
SHELL=${SHELL-ksh}
case $0 in
/*)	d=`dirname $0`;;
*/*)	d=$PWD/`dirname $0`;;
*)	d=$PWD;;
esac
case $SHELL in
/*)	;;
*/*)	SHELL=$d/$SHELL;;
*)	SHELL=$(whence $SHELL);;
esac
PATH=/bin:/usr/bin
if	[[ -d /usr/ucb ]]
then	PATH=$PATH:/usr/ucb
fi
PATH=$PATH:$d
if	[[ $INSTALLROOT && -r $INSTALLROOT/bin/.paths ]]
then	PATH=$INSTALLROOT/bin:$PATH
fi
if	[[ $compile ]]
then	SHCOMP=${SHCOMP:-shcomp}
	if	whence $SHCOMP > /dev/null
	then	tmp=$(mktemp -dt) || { echo mktemp -dt failed >&2; exit 1; }
		trap "cd /; rm -rf $tmp" EXIT
	elif	[[ $compile != 1 ]]
	then	echo $0: --compile: $SHCOMP not found >&2
		exit 1
	else	compile=
	fi
fi
typeset -A tests
for i in ${*-*.sh}
do	t=$(grep -c err_exit $i)
	if	(( $t > 2 ))
	then	(( t = $t - 2 ))
	fi
	tests[$i]=$t
	T=test
	if	(( $t != 1 ))
	then	T=${T}s
	fi
	E=error
	if	[[ $script ]]
	then	echo test $i begins ${time:+"at $(date +%Y-%m-%d+%H:%M:%S)"}
		if	[[ $i == $timesensitive ]]
		then	unset VMDEBUG
		fi
		if	$SHELL $i
		then	echo test $i passed ${time:+"at $(date +%Y-%m-%d+%H:%M:%S)"} "[ $t $T 0 ${E}s ]"
		else	e=$?
			if	(( e > 256 ))
			then	e=1
				E=signal
			fi
			if	(( $e != 1 ))
			then	E=${E}s
			fi
			echo test $i failed ${time:+"at $(date +%Y-%m-%d+%H:%M:%S)"} with exit code $e "[ $t $T $e $E ]"
		fi
		if	[[ $i == $timesensitive ]]
		then	export VMDEBUG=$vmdebug
		fi
	fi
done
if	[[ $compile ]]
then	for i in ${*-*.sh}
	do	t=${tests[$i]}
		T=test
		if	(( $t != 1 ))
		then	T=${T}s
		fi
		o=${i##*/}
		o=shcomp-${o%.sh}.ksh
		echo test $o begins ${time:+"at $(date +%Y-%m-%d+%H:%M:%S)"}
		E=error
		if	$SHCOMP $i > $tmp/$o
		then	if	[[ $i == $timesensitive ]]
			then	unset VMDEBUG
			fi
			if	$SHELL $tmp/$o
			then	echo test $o passed ${time:+"at $(date +%Y-%m-%d+%H:%M:%S)"} "[ $t $T 0 ${E}s ]"
			else	e=$?
				if	(( e > 256 ))
				then	e=1
					E=signal
				fi
				if	(( $e != 1 ))
				then	E=${E}s
				fi
				echo test $o failed ${time:+"at $(date +%Y-%m-%d+%H:%M:%S)"} with exit code $e "[ $t $T $e $E ]"
			fi
			if	[[ $i == $timesensitive ]]
			then	export VMDEBUG=$vmdebug
			fi
		else	e=$?
			t=1
			T=test
			echo test $o failed to compile ${time:+"at $(date +%Y-%m-%d+%H:%M:%S)"} with exit code $e "[ $t $T 1 $E ]"
		fi
	done
fi
