#!/bin/sh
# Obligatory functions to process before every test.

if [ -z "$PLANNER" ]; then
	# Running in free state; need to get all variable for test
	. /etc/inquisitor/global
	. $SHARE_DIR/functions
	. $SHARE_DIR/communication

	show_usage()
	{
		echo -n 'Inquisitor test: '
		sed -ne '/^# *DESCRIPTION=/ s/# *DESCRIPTION=//p' <$0
		cat <<__EOF__
A part of Inquisitor platform, version ${INQ_VERSION}

Usage: [variables] $0 [options]

Options:
  -h, --help            display this help and exit
  -V, --version         output version information and exit

Variables:
__EOF__
		# Parse all the variables from test script
		sed -ne '/^# *VAR=/ s/^# *VAR=//p' <$0 | while read L; do
			printf '  %-20s  %s (%s)\n' "`echo $L | cut -f1 -d:`" "`echo $L | cut -f4 -d:`" "`echo $L | cut -f3 -d:`"
		done
		echo
		grep -q "^# *DESTROYS_HDD=true" $0 && echo 'WARNING! This test would destroy the contents of all your hard drives!'
		grep -q "^# *POWEROFF_DURING_TEST=true" $0 && echo 'WARNING! This test would end in a poweroff of system under test!'
		exit 0
	}

	show_version()
	{
		echo -n 'Inquisitor test: '
		sed -ne '/^# *DESCRIPTION=/ s/# *DESCRIPTION=//p' <$0
		cat <<__EOF__
A part of Inquisitor platform, version ${INQ_VERSION}

Copyright (C) 2004-2008 by Inquisitor team
This is free software.  You may redistribute copies of it under the terms of
the GNU General Public License <http://www.gnu.org/licenses/gpl.html>.
There is NO WARRANTY, to the extent permitted by law.
__EOF__
		exit 0
	}

	# Parse command-line options
	TEMP=`getopt -n ${0##*/} -o h,V -l help,version -- "$@"` || show_usage
	eval set -- "$TEMP"

	while :; do
		case "$1" in
		-h|--help) show_usage
			;;
		-V|--version) show_version
			;;
		--) shift; break
			;;
		*) show_usage
			;;
		esac
		shift
	done

	if [ -z "$TEST_NAME" ]; then
		TEST_NAME=`basename $0`
		TEST_FILENAME="$SHARE_DIR/test/"`basename $0`
		eval `sed -ne '/^# *VAR=/ s/^# *VAR=\(.*\):\(.*\):\(.*\):\(.*\)$/\1=\3/p' <$TEST_FILENAME`
	fi

	# Override communications functions with empty ones
	test_promise_time() { return 0; }
	test_stage_progress() { return 0; }
	benchmark_submit_float()
	{
		printf "BENCHMARK: %-40s%s" "$1" "$2"
	}
	benchmark_submit_string()
	{
		printf "BENCHMARK: %-40s%s" "$1" "$2"
	}
	test_succeeded()
	{
		echo "$@" >&2
		exit 0
	}
	test_failed()
	{
		echo "$@" >&2
		exit 1
	}
else
	. /etc/inquisitor/global
	. $SHARE_DIR/functions
	. $SHARE_DIR/communication

	test_succeeded()
	{
		if [ -n "$@" ]; then
			echo "$@" >&4 || echo "$@" >&2
		fi
		exit 0
	}

	test_failed()
	{
		if [ -n "$@" ]; then
			echo "$@" >&4 || echo "$@" >&2
		fi
		exit 1
	}
fi

_exit_handler()
{
	local rc=$?
	trap - EXIT
	type exit_handler >$DEBUG_TTY 2>&1 && exit_handler || true
	exit $rc
}
trap _exit_handler HUP PIPE INT QUIT TERM EXIT
