#!/bin/ksh
#
# pragma ident "@(#)runtest.hds	1.7      01/07/30 SMI"
# Copyright (c) 2001 by Sun Microsystems, Inc.  All rights reserved.

prgdir=../../prgs 	# program directory
starttimes_file=/tmp/start_times.hds
b_time=			# gives m2 it's initial value for OLD_BUSY_TIME	
w_time=			# gives m2 it's initial value for OLD_WAIT_TIME
busycount=0
firsttime=0
HDS_BIN=$1
sleepid=$2

# test level
tlevel=$(cat /tmp/level.dat)

 # get list of disks.
dls=$(cat /etc/mnttab | grep -v ":boot" | grep -w "/dev/dsk" | \
grep "rw," | tr ":" "-" | sort -k 1.1)


# access method
am=
[ "$tlevel" = L1 ] && am="method=AsyncIO"

#check dls
if [ -z "$dls" ]
then
	echo "No Harddrives found."
	exit 1
fi

while [ -d /proc/$sleepid ]
do
  
     # Reset variable 
     ldev=
     # get device list 
     echo "$dls" | while read inline
     do
	if [ -f "$starttimes_file" ]
	then
		# check if listed tests are finished
		cat $starttimes_file | while read inline2
		do
			test_id=`echo $inline2 | cut -f1 -d:`
			if [ ! -d /proc/$test_id ]
			then
				# if so, output LOOPTIME and remove test entry
				started=`echo $inline2 | cut -f2 -d:`
				endtime=`../../prgs/time_sec`
				l_time=`expr $endtime - $started`
				echo LOOPTIME: $l_time
				cat $starttimes_file | grep -v $test_id > ${starttimes_file}.tmp
				mv ${starttimes_file}.tmp $starttimes_file
				T_COUNT=`head -1 /tmp/mdisk | cut -f2 -d=`
				# decrement test counter
				T_COUNT=`expr $T_COUNT - 1`
				sed -e "s/T_COUNT=[0-9]*/T_COUNT=$T_COUNT/" /tmp/mdisk > /tmp/mdisk.tmp
				mv /tmp/mdisk.tmp /tmp/mdisk
			fi
		done
	fi

	dev=$(echo $inline | awk -F"/" '{print $4}' | cut -f1 -d's')

	if [ "$dev" != "$ldev" ]
	then
		#echo "DEV=$dev"

		b_time="90"
		w_time="0"
		exit_val=""
		while [ "$exit_val" -ne 200 ]
		do
			# monitor disk usage
			$prgdir/m2 -x disk -d $dev $b_time $w_time
			exit_val=$?	
			#echo "EXIT_VAL=$exit_val"

			# if exit value is 100, kick off another test.
			if [ "$exit_val" -eq 100 ]
			then
			       	busycount=`expr $busycount + 1`
				if [ $busycount -gt 2 -o $firsttime -eq 0 ]
				then
					testcount=`ps -ef|grep disktest|grep -v grep|wc -l`
					if [ $testcount -lt 3 ]
					then		
						hds/bin/$HDS_BIN/disktest -v -o dev=$dev,$am &
						jobid=$!
						sleep 1
						if [ ! -d /proc/$jobid ]; then
							echo "!ERROR Starting $dev"
							exit 1
						fi
						starttime=`../../prgs/time_sec`
						# keep track of starttime
						echo "$jobid:$starttime" >> $starttimes_file

						# increment the test counter in mdisk file
						T_COUNT=`head -1 /tmp/mdisk | cut -f2 -d=`
						T_COUNT=`expr $T_COUNT + 1`
						sed -e "s/T_COUNT=[0-9]*/T_COUNT=$T_COUNT/" /tmp/mdisk > /tmp/mdisk.tmp
						mv /tmp/mdisk.tmp /tmp/mdisk
						firsttime=1
						busycount=0
					fi
				fi
			fi
			b_time=
			w_time=
		done
	fi
	ldev=$dev
     done
done
