#!/bin/bash

P=schbench-bench
DEFAULT_VERSION=0
. $SHELLPACK_INCLUDE/common.sh
TIME_CMD=`which time`
if [ "$TIME_CMD" = "" ]; then
        TIMEFORMAT="%2Uuser %2Ssystem %Relapsed %P%%CPU"
        TIME_CMD="time"
fi

SCHBENCH_ITERATIONS=1

# Basic argument parser
TASKSET_SERVER=
TASKSET_CLIENT=
SERVERSIDE_COMMAND=none
SERVERSIDE_NAME=`date +%Y%m%d-%H%M-%S`

while [ "$1" != "" ]; do
	case "$1" in
	-v)
		VERSION=$2
		shift 2
		;;
	--serverside-command)
		SERVERSIDE_COMMAND=$2
		shift 2
		;;
	--serverside-name)
		SERVERSIDE_NAME=$2
		shift 2
		;;
	--install-only)
		INSTALL_ONLY=yes
		shift
		;;
	--install-force)
		INSTALL_FORCE=yes
		shift
		;;
	--message-threads)
		SCHBENCH_MESSAGE_THREADS=$2
		shift 2
		;;
	--threads)
		SCHBENCH_THREADS=$2
		shift 2
		;;
	--runtime)
		SCHBENCH_RUNTIME=$2
		shift 2
		;;
	--sleeptime)
		SCHBENCH_SLEEPTIME=$2
		shift 2
		;;
	--cputime)
		SCHBENCH_CPUTIME=$2
		shift 2
		;;
	--auto)
		SCHBENCH_AUTO=yes
		shift
		;;
	--pipe)
		SCHBENCH_PIPE_SIZE=$2
		shift 2
		;;
	--rps)
		SCHBENCH_REQS_PER_SECOND=$2
		shift 2
		;;
	*)
		echo Unrecognised option: $1
		shift
	esac
done
if [ "$TASKSET_SERVER" != "" ]; then
	echo TASKSET_SERVER: $TASKSET_SERVER
	echo TASKSET_CLIENT: $TASKSET_CLIENT
fi
if [ -z "$VERSION" ]; then
	VERSION=$DEFAULT_VERSION
fi

if [ "$INSTALL_FORCE" = "yes" ]; then
	rm -rf $SHELLPACK_SOURCES/schbench-${VERSION}
fi
if [ ! -d $SHELLPACK_SOURCES/schbench-${VERSION}-installed ]; then
	mmtests_activity source-install
	$SHELLPACK_INCLUDE/shellpack-install-schbench -v ${VERSION}  || die schbench install script returned error
	mmtests_activity source-installed
fi
cd $SHELLPACK_SOURCES/schbench-${VERSION}-installed || die Failed to cd to schbench install directory
if [ "$INSTALL_ONLY" = "yes" ]; then
	echo schbench installed only as requested.
	exit $SHELLPACK_SUCCESS
fi
# Include monitor hooks
. $SHELLPACK_INCLUDE/include-monitor.sh

NR_THREADS=1
if [ "$NR_THREADS" = "" ]; then
	NR_THREADS=1
fi
THREADS=$NR_THREADS
NR_THREADS=$((NR_THREADS*2))
while [ $NR_THREADS -le $SCHBENCH_THREADS ]; do
	THREADS="$THREADS $NR_THREADS"
	NR_THREADS=$((NR_THREADS*2))
done
if [ `echo $THREADS | awk '{print $NF}'` -ne $SCHBENCH_THREADS ]; then
	THREADS="$THREADS $SCHBENCH_THREADS"
fi
for NR_THREADS in $THREADS; do
	if [ $NR_THREADS -gt $SCHBENCH_THREADS ]; then
		NR_THREADS=$SCHBENCH_THREADS
	fi
	mmtests_activity process $NR_THREADS/$SCHBENCH_THREADS
	mmtests_activity $NR_THREADS
	monitor_pre_hook $LOGDIR_RESULTS $NR_THREADS

for ITERATION in `seq 1 $SCHBENCH_ITERATIONS`; do
	mmtests_activity iteration $ITERATION
		echo Running $NR_THREADS schbench
		$TIME_CMD -o $LOGDIR_RESULTS/time-$NR_THREADS \
			./schbench -r $SCHBENCH_RUNTIME -m $SCHBENCH_MESSAGE_THREADS \
				-t $NR_THREADS 2>&1 | \
				tee $LOGDIR_RESULTS/schbench-$NR_THREADS.log
done

	monitor_post_hook $LOGDIR_RESULTS $NR_THREADS
done

exit $SHELLPACK_SUCCESS
#### Description A small-ish program to benchmark wakeup latencies.
#### Details schbench-bench 5
