#!/bin/bash
# This script installs memtester
P=memtester-bench
DEFAULT_VERSION=4.3.0
. $SHELLPACK_INCLUDE/common.sh

# 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
		;;
	--instances)
		MEMTESTER_INSTANCES=$2
		shift 2
		;;
	--mb-usage)
		MEMTESTER_MEMORY_MB=$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/memtester-${VERSION}
fi
if [ ! -d $SHELLPACK_SOURCES/memtester-${VERSION}-installed ]; then
	$SHELLPACK_INCLUDE/shellpack-install-memtester -v ${VERSION}  || die memtester install script returned error
fi
cd $SHELLPACK_SOURCES/memtester-${VERSION}-installed || die Failed to cd to memtester install directory
if [ "$INSTALL_ONLY" = "yes" ]; then
	echo memtester installed only as requested.
	exit $SHELLPACK_SUCCESS
fi

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

cd $SHELLPACK_SOURCES/memtester-${VERSION}-installed || exit $SHELLPACK_ERROR
USAGE=$((MEMTESTER_MEMORY_MB/MEMTESTER_INSTANCES))
for INSTANCE in `seq 1 $MEMTESTER_INSTANCES`; do
	
	echo Starting instance $INSTANCE usage $USAGE mb
	./memtester $((MEMTESTER_MEMORY_MB/MEMTESTER_INSTANCES))M 1 > $LOGDIR_RESULTS/memtester-$INSTANCE.log &
	echo $! > $SHELLPACK_TEMP/memtester-$INSTANCE.pid
done

EXIT_CODE=$SHELLPACK_SUCCESS
for INSTANCE in `seq 1 $MEMTESTER_INSTANCES`; do
	INSTANCE_PID=`cat $SHELLPACK_TEMP/memtester-$INSTANCE.pid`
	echo Waiting on instance $INSTANCE pid $INSTANCE_PID
	wait $INSTANCE_PID
	RET=$?
	if [ $RET -ne 0 ]; then
		warn Instance $INSTANCE failed with exit code $RET
		EXIT_CODE=$SHELLPACK_ERROR
	fi
done

exit $EXIT_CODE
#### Description Userspace memory integrity tester
#### Details memtester-bench 4
