#!/bin/bash
# This is the script for running the hackbench benchmark
#
# Usage $P <pipes|sockets> <number-of-groups> -i iterations
P=hackbench-bench
DEFAULT_VERSION=0
. $SHELLPACK_INCLUDE/common.sh
iterations=1
conn_name=
conn_type=
num_groups=

# Basic argument parser
while [ "$1" != "" ]; do
	case "$1" in
	-v)
		VERSION=$2
		shift 2
		;;
	--install-only)
		INSTALL_ONLY=yes
		shift
		;;
	--install-force)
		INSTALL_FORCE=yes
		shift
		;;
	pipes)
		conn_type="-pipe"
		conn_name=pipes
		num_groups=$2
		shift 2
		;;
	sockets)
		num_groups=$2
		conn_name=sockets
		shift 2
		;;
	-i)
		iterations=$2
		shift 2
		;;
	*)
		echo Unrecognised option: $1
		shift
	esac
done
if [ -z "$VERSION" ]; then
	VERSION=$DEFAULT_VERSION
fi

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

# Include monitor hooks
. $SHELLPACK_INCLUDE/include-monitor.sh

# Ensure pipes or sockets were specified
if [ "$num_groups" = "" ]; then
	die Failed to specify pipes or sockets
fi

pushd $SHELLPACK_SOURCES/hackbench-${VERSION}-installed > /dev/null
RESULTSLOG=$LOGDIR_RESULTS/hackbench
TIFS=$IFS
RETVAL=0
IFS=,
echo -n > $RESULTSLOG
for group in $num_groups; do
	IFS=$TIFS
	echo -n > $RESULTSLOG.$group
	monitor_pre_hook $LOGDIR_RESULTS $group
	if [ $RETVAL -eq 0 ]; then
		echo "Connection type: $conn_name" | tee -a $RESULTSLOG $RESULTSLOG.$group
		echo "Number of groups: $group" | tee -a $RESULTSLOG $RESULTSLOG.$group

		# Run a number of iterations.
		iter=$iterations
		while [ $iter -gt 0 ]; do
			save_rc ./hackbench $conn_type $group process 1000 | tee -a $RESULTSLOG $RESULTSLOG.$group
			recover_rc
			RETVAL=$?
			if [ $RETVAL -ne 0 ]; then
				echo Error encountered in hackbench
				iter=0
			fi
			iter=$(($iter-1))
		done
	fi
	monitor_post_hook $LOGDIR_RESULTS $group
	IFS=,
done

exit $RETVAL
#### Description Run the HackBench benchmark
#### Details hackbench-bench 19
