#! /bin/sh

# runtest - run an xmlformat test

# Test scripts are located in ./tests, and are run by naming the basename
# of the input XML file. For example, to run the test for tests/abc.xml,
# invoke "runtest abc".

# The test name "all" runs all tests.

# -p = use ./xmlformat.pl rather than xmlformat.rb
# -r = use ./xmlformat.rb (which is the default anyway)
# -u = update the expected-result file from the actual output file
# -v = verbose

VERBOSE=0
UPDATE=0
CMD=./xmlformat.rb

while [ $# -gt 0 ]; do
	case $1 in
		-p)
			CMD=./xmlformat.pl
			shift
			;;
		-r)
			CMD=./xmlformat.rb
			shift
			;;
		-u)
			UPDATE=1
			shift
			;;
		-v)
			VERBOSE=1
			shift
			;;
		-*)
			echo "Unknown option: $1" 1>&2
			exit 1
			;;
		*)
			break
			;;
	esac
done

if [ $# -eq 0 ]; then
	echo "$0 [-p] [-r] [-u] [-v] test-name" 1>&2
	exit 1
fi

if [ $# -eq 1 -a "x$1" = "xall" ]; then
	if [ $VERBOSE -ne 0 ]; then
		echo "run all tests..." 1>&2
	fi
	TESTS=`(cd tests;ls *.xml|sed -e 's/\.xml//')`
else
	TESTS="$@"
fi

for testname in $TESTS; do
	BASE=tests/$testname
	if [ ! -f $BASE.xml ]; then
		echo "No file $BASE.xml found" 1>&2
		exit 1
	fi
	# use test-specific config file if one exists (else use default)
	# (reset file for each test)
	CONFIG_FILE=
	if [ -f $BASE.conf ]; then
		CONFIG_FILE="--config-file $BASE.conf"
	fi
	# generate output
	if [ $VERBOSE -ne 0 ]; then
		echo "$CMD $CONFIG_FILE $BASE.xml > $BASE.out" 1>&2
	fi
	$CMD $CONFIG_FILE $BASE.xml > $BASE.out
	# if in update mode, update .res file with .out file
	# else compare output to expected result
	if [ $UPDATE -eq 1 ]; then
		echo "Updating $BASE.res from $BASE.out" 1>&2
		cp $BASE.out $BASE.res
	else
		diff -u $BASE.res $BASE.out
	fi
done
