#!/bin/bash
#
# $1 is name of profile which must exist in the $AUTODIR/sources/ffsb directory
# $2 ... are any key=value pairs of valid profile entries or numdevs=n wher n is
#	the number of devices to rn on
# Other key assumption is that FS(s) to benchmark are already mounted on /mnt/tmp1 ../mnt/tmpn

. /etc/autobench.conf || . functions

# Process the arguments ######################################################
if [ $# -lt 1 ]; then
  echo "You must specify the profile to run "
  exit 1
fi

# Install support files ######################################################
if [ ! \( -d $AUTODIR/sources/ffsb -a -x $AUTODIR/sources/ffsb/ffsb \) ];
then
  $AUTODIR/scripts/benchmarks/install/ffsb || exit 2
fi

getcommand doprofilers
doprofilers install

pushd $AUTODIR/sources/ffsb

i=0
for arg in $@
do
	#let i=i+1
   	#echo "arg $i is $arg"
	equal=$(expr index $arg "=")
	if [ "$equal" != "0" ]; then #if there is an "=" in the arg
		key=${arg%%=*}              #strip off everything after the =
		#echo debug key is $key
		if [ $key == "numdevs" ]; then 
	  		numdevs=${arg##*=}
			#echo numdevs is $numdevs
			for ((j=i+1;j< ((i+$numdevs));j++))
			do	
	 			profiles="$profiles profile${j}"
				sed -e "s/location=.*/location=\/mnt\/tmp${j}/" $base > $LOGDIR/benchmark/profile${j}
			done
			let i=j-1
			continue
		fi
		for profile in $profiles 
		do
			#echo debug sed args $key $arg $profile
			sed -e "s/${key}.*/${arg}/" $LOGDIR/benchmark/$profile >tmpfile
			cp tmpfile $LOGDIR/benchmark/$profile
		done
	else
#		if [ ! -e "$arg" ]; then
#			log "Profile ($arg) for ffsb does not exist, exiting"
#			popd
#			exit
#		fi
		# go try and get the profile
		wget -O $arg http://ausgsa.austin.ibm.com/projects/l/ltcperformance/benchmarks/ffsb/resources/profiles/$arg
		numdevs=1
		let i=i+1
		base=$arg
		profiles=profile${i}
		sed -e "s/location=.*/location=\/mnt\/tmp${i}/" $base > $LOGDIR/benchmark/profile${i}
	fi
done 
rm tmpfile

for ((j=1; j<=i; j++))
do
	mp="/mnt/tmp${j}"
	fst=`mount | grep $mp`
	fst=${fst##*type}
	echo $fst
	fst=${fst%%(*}
	echo fstype is $fst
	echo "fstype for /mnt/tmp${j} is $fst" >> $LOGDIR/benchmark/fstype.$RUN_NUMBER
	if [ "$fst" == "" ]; then
		log "No filesystem mounted to run test on, aborting!"
		exit
	fi
done

# only run the first instance through streamfilter for starting and stopping of
# sar and profile since they are system global.
watchfor "Starting Actual Benchmark" startprofilers
watchfor "Results" 'stopprofilers; doprofilers report ; doprofilers postprocess'

$AUTODIR/sources/ffsb/ffsb $LOGDIR/benchmark/profile1 $LOGDIR/benchmark/ffsbout.$RUN_NUMBER-1 &
#collect the pids so we can wait for all work to complete.
ids="$!"
for ((j=2; j<=i; j++))
do
	$AUTODIR/sources/ffsb/ffsb $LOGDIR/benchmark/profile${j} $LOGDIR/benchmark/ffsbout.$RUN_NUMBER-${j} &
	#collect the pids so we can wait for all work to complete.
	ids="$ids $!"
done

for id in $ids
do
	#echo "wait for $id"
	wait $id
done

popd
