#!/bin/bash

do_help()
{
	echo "`basename $0` usage:
  -?/--help          print this message
  -V/--verbose       write verbose output to stdout
  --step-trace       run trace in single step mode (default)
  --branch-trace     run trace in branch mode
  --buffer-size=num  per-cpu buffer size in MB (default: 50MB)
" >&2
}

getOptions()
{
	BUF_SIZE=50
	BRANCH_TRACE=0
	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
				;;
			--buffer-size)
				if test -z "$val"; then
					echo "No value given for option $arg. "\
						"See `basename $0` --help" >&2
					exit 1
				fi
				BUF_SIZE=$val
				;;
			--step-trace)
				BRANCH_TRACE=0
				;;
			--branch-trace)
				BRANCH_TRACE=1
				;;
			-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
}

getOptions $@

runCommand swtrace init -s $BUF_SIZE
runCommand swtrace disable

if test $BRANCH_TRACE = 0; then
	runCommand swtrace enable 4 17 25 49 50
else
	runCommand swtrace enable 4 17 25
fi

runCommand swtrace on

if test $BRANCH_TRACE = 0; then
	runCommand swtrace it_install -ss
else
	runCommand swtrace it_install
fi
