#!/bin/sh

# This script runs the regression tests in src/regression.
# It also compiles the tests in benchmark/tests

set -e

name=`basename $0`

usage () {
	echo >&2 "usage: $name [-cross host] [-run-only] [mlton flags ...]"
	exit 1
}

cross='no'
runOnly='no'
flags=''
while [ "$#" -gt 0 ]; do
	case "$1" in
	-cross)
		cross='yes'
		shift
		if [ "$#" = 0 ]; then
			usage
		fi
		crossHost="$1"
		shift
		;;
	-run-only)
		runOnly='yes'
		shift
		;;
	*)
		flags="$@"
		break
		;;
	esac
done

dir=`dirname $0`
src=`cd $dir/.. && pwd`
bin="$src/build/bin"
mlton="$bin/mlton"
if [ $cross = 'yes' ]; then
	flags="$flags -host $crossHost"
fi
cont='callcc.sml callcc2.sml callcc3.sml'
intinf='int-inf.0.sml int-inf.1.sml int-inf.2.sml int-inf.3.sml int-inf.4.sml int-inf.5.sml conv.sml conv2.sml harmonic.sml slow.sml slower.sml smith-normal-form.sml'
signal='signals.sml suspend.sml'
thread='thread0.sml thread1.sml thread2.sml mutex.sml prodcons.sml same-fringe.sml timeout.sml'
world='world1.sml world2.sml world3.sml world4.sml world5.sml world6.sml'
tmp=/tmp/z.regression.$$
PATH=$bin:.:$PATH

compFail () {
	echo "compilation of $f failed with $flags"
}

$mlton -v
echo "flags = $flags"

cd $src/regression
for f in `ls *.sml`; do
	f=`basename $f .sml`
	case "$f" in
	serialize)
		echo "skipping $f"
	;;
	*)
		echo "testing $f"
		case "$f" in
		exnHistory*)
			extraFlags="-exn-history true"
		;;
		*)
			extraFlags=""
		;;
		esac
		if [ $runOnly = 'no' ]; then
			$mlton $flags $extraFlags $f.sml
			if [ $? -ne 0 -o ! -x $f ]; then
				compFail $f
#				exit 1
			fi
		fi
		if [ ! -r $f.nonterm -a $cross = 'no' -a -x $f ]; then
			( ./$f || echo 'Nonzero exit status.' ) >$tmp 2>&1 
			if [ -r $f.ok ] && ! diff $f.ok $tmp ; then
				echo "difference with $flags"
			fi
		fi
	;;
	esac
done 
if [ $cross = 'yes' -o $runOnly = 'yes' ]; then
	exit 0
fi
make clean >/dev/null
cd $src/benchmark/tests
for f in `ls *.sml`; do
	f=`basename $f .sml`
	tmpf=/tmp/$f.$$
	case "$f" in
	fxp)
		echo "skipping $f"
	;;
	*)
			echo "testing $f"
		echo "val _ = Main.doit ()" | cat $f.sml - > $tmpf.sml
		$mlton -o $tmpf $flags $tmpf.sml
		if [ $? -ne 0 ]; then
			compFail $f
		fi
		rm -f $tmpf $tmpf.sml
	;;
	esac
done 
make clean > /dev/null
cd $src
for f in mllex mlyacc mlprof; do
    tmpf=/tmp/$f.$$
    cd $src/$f
    case "$f" in
    foobar)
	    echo "skipping $f"
    ;;
    *)
	    echo "testing $f"
	    gmake -W $f >/dev/null
	    $mlton $flags -o $tmpf $f.cm
	    if [ $? -ne 0 ]; then
			compFail $f
	    fi
	    rm -f $tmpf
    ;;
    esac
done

rm -f $tmp
