#!/bin/bash
#
P=ku_latency-bench
DEFAULT_VERSION=0
. $SHELLPACK_INCLUDE/common.sh

TASKSET_SEND=""
TASKSET_RECV=""

# 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
		;;
	--run-seconds)
		KU_LATENCY_RUN_SECONDS=$2
		shift 2
		;;
	--start-send-first)
		KU_LATENCY_START_SEND_FIRST=$2
		shift 2
		;;
	--bind-same)
		TASKSET_SEND="taskset -c 0"
		TASKSET_RECV="taskset -c 0"
		shift
		;;
	--bind-firstsecond)
		TASKSET_SEND="taskset -c 0"
		TASKSET_RECV="taskset -c 1"
		shift
		;;
	--bind-firstlast)
		TASKSET_SEND="taskset -c 0"
		TASKSET_RECV="taskset -c $(($NUMCPUS-1))"
		shift
		;;
	*)
		echo Unrecognised option: $1
		shift
	esac
done
if [ -z "$VERSION" ]; then
	VERSION=$DEFAULT_VERSION
fi

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

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

RUN_SECONDS="${KU_LATENCY_RUN_SECONDS:-10}"
START_SEND_FIRST="${KU_LATENCY_START_SEND_FIRST:-no}"

pushd $SHELLPACK_SOURCES/ku_latency-$VERSION-installed > /dev/null

if [[ ${START_SEND_FIRST} == "yes" ]]; then
    echo "Starting send-data via $TASKSET_SEND"
    $TASKSET_SEND ./send-data -d localhost > $LOGDIR_RESULTS/send-data.log &
    SENDDATA_PID=$!

    echo "Starting ku-latency via $TASKSET_RECV"
    $TASKSET_RECV ./ku-latency -e localhost | tee $LOGDIR_RESULTS/ku-latency.log > /dev/null &
    KULATENCY_PID=`jobs -p | tail -n 1`
else
    echo "Starting ku-latency via $TASKSET_RECV"
    $TASKSET_SEND ./ku-latency -e localhost | tee $LOGDIR_RESULTS/ku-latency.log > /dev/null &
    KULATENCY_PID=`jobs -p`

    echo "Starting send-data via $TASKSET_SEND"
    $TASKSET_RECV ./send-data -d localhost > $LOGDIR_RESULTS/send-data.log &
    SENDDATA_PID=$!
fi

jobs -l

echo "Sleeping $RUN_SECONDS seconds"
sleep $RUN_SECONDS

echo "Killing send-data PID $SENDDATA_PID"
kill -SIGINT $SENDDATA_PID

echo "killing ku-latency PID $KULATENCY_PID"
kill $KULATENCY_PID

exit $SHELLPACK_SUCCESS
#### Description Kernel network packet receive latency
#### Details ku_latency-bench 32
