#!/bin/bash
P=wptlbflush-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

# 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
		;;
	--min-processes)
		WPTLBFLUSH_MIN_PROCESSES=$2
		shift 2
		;;
	--max-processes)
		WPTLBFLUSH_MAX_PROCESSES=$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/wptlbflush
fi
if [ ! -d $SHELLPACK_SOURCES/wptlbflush-installed ]; then
	mmtests_activity source-install
	$SHELLPACK_INCLUDE/shellpack-install-wptlbflush -v ${VERSION}  || die wptlbflush install script returned error
	mmtests_activity source-installed
fi
cd $SHELLPACK_SOURCES/wptlbflush-${VERSION}-installed || die Failed to cd to wptlbflush install directory
if [ "$INSTALL_ONLY" = "yes" ]; then
	echo wptlbflush installed only as requested.
	exit $SHELLPACK_SUCCESS
fi

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

# Run the benchmark
THREADS=
START_THREAD=$WPTLBFLUSH_MIN_PROCESSES
END_THREAD=$WPTLBFLUSH_MAX_PROCESSES
if [ $END_THREAD -gt 32 ]; then
	THREADS=`seq $START_THREAD 3 8`
	THREADS="$THREADS `seq 12 9 32`"
	THREADS="$THREADS `seq 48 31 $END_THREAD`"
elif [ $END_THREAD -gt 8 ]; then
	THREADS=`seq $START_THREAD 2 8`
	THREADS="$THREADS `seq 12 6 $END_THREAD`"
else
	THREADS=`seq $START_THREAD 2 $END_THREAD`
fi
if [ `echo $THREADS | awk '{print $NF}'` -ne $END_THREAD ]; then
	THREADS="$THREADS $END_THREAD"
fi

for NR_THREADS in $THREADS; do
	if [ $NR_THREADS -lt $WPTLBFLUSH_MIN_PROCESSES ]; then
		continue
	fi
	mmtests_activity process $NR_THREADS/$END_THREAD
	echo Running for $NR_THREADS processes of $WPTLBFLUSH_MAX_PROCESSES
	sed -i -e "s/define NUM_PROCESS.*/define NUM_PROCESS $NR_THREADS/" $SHELLPACK_SOURCES/wptlbflush-${VERSION}-installed/wp-tlbflush.c
	gcc -Wall -lpthread $SHELLPACK_SOURCES/wptlbflush-${VERSION}-installed/wp-tlbflush.c -o $SHELLPACK_SOURCES/wptlbflush-${VERSION}-installed/wp-tlbflush || die Failed to build

	monitor_pre_hook $NR_THREADS
	$TIME_CMD -o $LOGDIR_RESULTS/time-$NR_THREADS \
		$SHELLPACK_SOURCES/wptlbflush-${VERSION}-installed/wp-tlbflush > $LOGDIR_RESULTS/wp-tlbflush-$NR_THREADS.log || \
		die wp-flush aborted due to possible corruption
	monitor_post_hook $NR_THREADS
done

exit $SHELLPACK_SUCCESS
#### Description wptlbflush
#### Details wptlbflush-bench 19
