#!/bin/bash

do_help()
{
	echo "`basename $0` usage:
  -?/--help            print this message
  -V/--verbose         write verbose output to stdout
  --trace-outupt=file  trace output filename (default: trace.nrm2)
" >&2
}

getOptions()
{
	TRACE_OUTPUT="trace.nrm2"
	VERBOSE=0

	while [ "$#" -ne 0 ]; do
		arg=`printf %s $1 | awk -F= '{print $1}'`
		val=`printf %s $1 | awk -F= '{print $2}'`
		shift
		case "$arg" in
			-"?"|--help)
				do_help
				exit 0
				;;
			--trace-output)
				if test -z "$val"; then
					echo "No value given for option $arg. "\
						"See `basename $0` --help" >&2
					exit 1
				fi
				TRACE_OUTPUT=$val
				;;
			-V|--verbose)
				VERBOSE=1
				;;
			*)
				echo "Unknown option \"$arg\". "\
					"See `basename $0` --help" >&2
				exit 1
				;;
		esac
	done
}

runCommand()
{
	if test $VERBOSE = 1; then
		echo
		echo ---Output of command \"$@\" -------------------------
		$@
	else
		$@ &> /dev/null
	fi
	if test "$?" -ne 0; then
		echo "Error running command \"$@\".  Aborting." >&2
		exit 1
	fi
}

runSwtraceOff()
{
	if test $VERBOSE = 1; then
		echo
		echo ---Output of command \"$@\" -------------------------
		swtrace off
	else
		swtrace off &> /dev/null
	fi
	if test "$?" -ne 0; then
		echo "Warning: swtrace off reports possible buffer overflow." >&2
	fi
}


getOptions $@

runSwtraceOff
runCommand swtrace it_remove
runCommand swtrace disable
runCommand swtrace get $TRACE_OUTPUT
runCommand swtrace free
