#!/bin/sh

[ -z "$3" ] && {
	echo "Syntax: $0 test-database admin-user test-user [misc]" >&2
	echo
	echo "Where misc is:"
	echo "       --no-create	don't create the DB"
	echo "       --run-name name	run tests matching '*name*'"
	echo
	exit 1
}

test_db="$1"
admin_user="$2"
test_user="$3"

create_db=1
run_name=""
while ! [ -z "$4" ]; do
	if [ "x$4" = "x--no-create" ]; then
		create_db=0
	elif [ "x$4" = "x--run-name" ]; then
		shift
		run_name="$4"
	fi

	shift
done

scriptdir="`dirname $0`"
tempdir="`mktemp -d`"
cp -Rap $scriptdir/../../legacyworlds-server-data/db-structure/* $tempdir/
cat > $tempdir/db-config.txt <<EOF
admin=$admin_user
db=$test_db
user=$test_user
password=$test_user
EOF

(
	cd $tempdir

	if [ $create_db -eq 1 ]; then
		echo "Creating DB..."
		psql -vQUIET=1 -vON_ERROR_STOP=1 --file database.sql || exit 1
		psql -vQUIET=1 -f tests/pgtap.sql $test_db || exit 1
	fi

	cd tests
	if [ "x$run_name" = "x" ]; then
		run_name='*.sql'
	else
		run_name='*'"$run_name"'*.sql'
	fi
	if ! [ -z "`find admin/ -type f -name "$run_name"`" ]; then
		pg_prove -d $test_db `find admin/ -type f -name "$run_name" | sort` || exit 1
	fi
	if ! [ -z "`find user/ -type f -name "$run_name"`" ]; then
		pg_prove -U $test_user -d $test_db `find user/ -type f -name "$run_name" | sort` || exit 1
	fi
)
result=$?

rm -rf $tempdir
exit $result