# vim:filetype=sh
#
# This hook extracts the output from the filebench:- total operations, ops/sec
# and the energy readings from the wattmeter. 
# In this hook, we assume that there are two wattmeters, one connected to the 
# machine while the other to the external disk and we can download the readings
# from the wattmeter through the USB interface. 
#
# To enable, set MEASURE_FILEBENCH.

ME=filebench
TYPE=measure
STDOUT="/tmp/logs/stdout-$APEPOCH"

if [ ! -z "AP_MEASURE_HOOK" ] ; then
	eval `echo "AP_SAVED_"$TYPE"_HOOK_"$ME"=""$AP_MEASURE_HOOK"`
fi
if [ ! -z "$MEASURE_FILEBENCH" ] ; then
	AP_MEASURE_HOOK=ap_hook_measure_filebench
fi

# Parse the FileBench output
function ap_filebench {
	PATTERN="IO Summary: "
	summary=`cat $STDOUT | grep -ir -A 1 "$PATTERN"`;
	ops=`echo $summary | awk '{ print ''$3'' }'`
	ops_s=`echo $summary | awk '{ print ''$5'' }'`
	r_w=`echo $summary | awk '{ print ''$7'' }' | cut -d '(' -f 2`
	mb_s=`echo $summary | awk '{ print ''$9'' }' | cut -d ''m'' -f 1`
	cpu_op=`echo $summary | awk '{ print ''$10'' }' | cut -d ''u'' -f 1`
	latency=`echo $summary | awk '{ print ''$12'' }' | cut -d ''m'' -f 1`

	echo "t_ops = $ops"
	echo "ops_s = $ops_s"
	echo "t_mb_s = $mb_s"
	echo "t_cpu_op = $cpu_op"
	echo "t_latency = $latency"
	echo "test_runtime = $TEST_RUNTIME"

	return 0;
}

# Function to log the energy stats.
function ap_energy_stats_download() {
	# USB0 --> m/c USB 1 --> disk
	ENERGY_INTO_TEN_MC=`wattsup /dev/ttyUSB0  "#D,R,0;" r | tail -n 2 | head -n 1| cut -d ',' -f 8`
	if [ "$?" -gt "0" ]; then
		echo "Fetching reading from wattmeter failed"
		return 1
	fi
	
	ENERGY_MC=`echo "scale=2; $ENERGY_INTO_TEN_MC / 10" | bc`

	# Extract disk readings	
	ENERGY_INTO_TEN_DISK=`wattsup /dev/ttyUSB1  "#D,R,0;" r | tail -n 2 | head -n 1| cut -d ',' -f 8`
	if [ "$?" -gt "0" ]; then
		echo "Fetching reading from wattmeter failed"
		return 1
	fi
	
	ENERGY_DISK=`echo "scale=2; $ENERGY_INTO_TEN_DISK / 10" | bc`

}


function ap_hook_measure_filebench {
	local ME=filebench
	local TYPE=measure
	if [ "$1" = "premeasure" ] ; then
		true
	elif [ "$1" = "start" ] ; then
		echo "start"
	elif [ "$1" = "end" ] ; then
		echo "Unmounting $TESTDEV "
		umount $TESTDEV
		ap_energy_stats_download
		if [ "$?" -eq "1" ]; then
			return 1	
		fi
        	ap_log "energy_mc = " ${ENERGY_MC}
        	ap_log "energy_disk = " ${ENERGY_DISK}
		ap_logexec ap_filebench || return $?
	elif [ "$1" = "final" ] ; then
		true
	else
		echo "Measurement hook failed " 1>&2
		exit 1
	fi

	local HOOK=`eval "echo $""AP_SAVED_"$TYPE"_HOOK_"$ME`
	if [ ! -z "$HOOK" ] ; then
		"$HOOK" $*
		return $?
	fi

	return 0
}

unset ME
