#!/bin/sh

trap 'rm -f $TESTFILE $RUNLOG $LOGFILE; exit 1' 2 3

TESTFILE=/tmp/test$$
RUNLOG=/tmp/run$$
LOGFILE=/tmp/log$$
PASSED=1

rm -f $LOGFILE;
echo "Some tests failed. Report follows" >$LOGFILE

if [ "$1" = "" ]; then
	files="lib/*.l src/*.l"
else
	files="$*"
fi

for file in $files; do

	if [ ! -e $file ]; then
		echo "examine: $file: no such file" >&2
		exit 1
	fi

	if [ `dirname $file` = lib ]; then
		SK=./sketchy
	else
		SK=./dist/sk.sh
	fi
	echo ":l $file" >$TESTFILE
	sed -ne '/---example---/,/^$/p' $file \
		| sed -e '1d' -e 's/^;//' -e 's/=>.*//' >>$TESTFILE
	EXAMPLE=`sed -ne '/---example---/,/^$/p' $file \
		| sed -ne '/=>/p'`
	SOURCE=`echo "$EXAMPLE" | sed -e 's/; \(.*\) =>.*/\1/'`
	RESULT=`echo "$EXAMPLE" | sed -e 's/.*=> \(.*\)/\1/'`
	if [ "$RESULT" != "" ]; then echo -n "$SOURCE" '=> '; fi
	$SK -B <$TESTFILE | tail -n 1 > $RUNLOG 2>&1
	if [ "$RESULT" != "" ]; then cat $RUNLOG; fi
	if [ "$RESULT" != "" -a "`cat $RUNLOG`" != "$RESULT" ]; then
		echo "--- $file:" >>$LOGFILE
		echo "Result should have been: $RESULT" >>$LOGFILE
		echo "Output follows:" >>$LOGFILE
		./sketchy -B <$TESTFILE >>$LOGFILE 2>&1
		PASSED=0
	fi
done

if [ $PASSED = 0 ]; then
	more $LOGFILE
else
	echo "Everything fine."
fi

rm -f $TESTFILE $RUNLOG $LOGFILE
