#!/bin/sh

if ! [ -f ai/regression/regression.nut ]; then
	echo "Make sure you are in the root of OpenTTD before starting this script."
	exit 1
fi

cp ai/regression/regression.nut ai/regression/main.nut

params=""
gdb=""
if [ "$1" != "-r" ]; then
	params="-snull -mnull -vnull:ticks=2000"
fi
if [ "$1" = "-g" ]; then
	gdb="gdb --ex run --args "
fi
if [ -n "$gdb" ]; then
	$gdb ./openttd -a regression -x -c ai/regression/regression.cfg $params -g ai/regression/regression.sav
else
	./openttd -a regression -x -c ai/regression/regression.cfg $params -g ai/regression/regression.sav 2>tmp.stderr | awk '{ gsub("0x\\(nil\\)", "0x00000000", $0); print $0; }' > tmp.regression
fi

if [ -z "$gdb" ]; then
	res="`diff -u ai/regression/regression.txt tmp.regression`"
	if [ -z "$res" ]; then
		echo "Regression test passed!"
	else
		echo "Regression test failed! Difference:"
		echo "$res"
	fi
	echo ""
	stderr="`cat tmp.stderr`"
	if [ -n "$stderr" ]; then
		echo "OpenTTD gave this on stderr:"
		echo "$stderr"
	fi
	echo ""
	echo "Regression test done"
fi

rm -f ai/regression/main.nut tmp.stderr

if [ "$1" != "-k" ]; then
	rm -f tmp.regression
fi
