#!/bin/bash
# -*- mode: shell-script; indent-tabs-mode: t; sh-basic-offset: 8; sh-indentation: 8; sh-indent-for-case-alt: + -*-

script_path=`dirname $0`
script_name=`basename $0`
pbench_bin="`cd ${script_path}/..; /bin/pwd`"

# source the base script
. "$pbench_bin"/base

# The sole purpose of this script is to ensure a tool
# of your choosing is used during the execution of a benchmark.
# For a list of performance tools, look at the
# $pbench_bin/tool-scripts directory.

# Defaults
group=default
start_trigger=""
stop_trigger=""

function usage() {
	printf "usage:\n"
	printf "$script_name [--group=<tool group>] --start-trigger=<string to match> --stop-trigger=<string to match>\n"
}

if [[ "${#}" == 0 ]] ;then
        usage >&2
        exit 1
fi

# Process options and arguments
opts=$(getopt -q -o h --longoptions "help,group:,start-trigger:,stop-trigger:" -n "getopt.sh" -- "$@");
if [ $? -ne 0 ]; then
	printf "\n%s\n%s: you specified an invalid option\n\n" "${*}" "${script_name}" >&2
	usage >&2
	exit 1
fi
eval set -- "$opts";
while true; do
	case "$1" in
		--start-trigger)
		shift;
		if [ -n "$1" ]; then
			start_trigger="$1"
			shift;
		fi
		;;
		--stop-trigger)
		shift;
		if [ -n "$1" ]; then
			stop_trigger="$1"
			shift;
		fi
		;;
		--group)
		shift;
		if [ -n "$1" ]; then
			group="$1"
			shift;
		fi
		;;
                -h|--help)
                usage;
                exit 0
                ;;
		--)
		shift;
		break;
		;;
		*)
		shift;
		;;
	esac
done

if [[ -z "$start_trigger" || -z "$stop_trigger" ]] ;then
	printf "Both --start-trigger and --stop-trigger must be specified and must be non-empty.\n" >&2
	usage >&2
	exit 1
fi
if [[ "$start_trigger" != "${start_trigger%%:*}" ]]; then
	printf "$script_name: the start trigger cannot have a colon in it: \"${start_trigger}\"\n" >&2
	exit 1
fi
if [ "$stop_trigger" != "${stop_trigger%%:*}" ]; then
	printf "$script_name: the stop trigger cannot have a colon in it: \"${stop_trigger}\"\n" >&2
	exit 1
fi

if [ ! -f "$pbench_run/tool-triggers" ]; then
	mkdir -p "$pbench_run"
	echo "#group:start-trigger:stop-trigger" > "$pbench_run/tool-triggers"
fi
# remove any previous trigger for the given group
sed -i /^$group.*/d "$pbench_run/tool-triggers"
# remember this trigger
printf "%s:%s:%s\n" "$group" "$start_trigger" "$stop_trigger" >> "$pbench_run/tool-triggers"
printf "tool trigger strings for start: \"$start_trigger\" and for stop: \"$stop_trigger\" are now registered for tool group: $group\n"
