#!/bin/sh

seconds=$1   # how many seconds per run
shift
opre=$1      # store for current test position
shift
num=$1       # chunk size for reading
shift

for disk in "$@"; do

# skip a busy disk
drive=`echo "$disk" | sed -e 's/[a-z]*$//'`

if out=`iostat 2>/dev/null -w 1 -c 2 -d "$drive"`; then
	tps=`echo "$out" | awk 'NR==4{print $2+0}'`
	echo "drive $drive executes $tps tps"
else
	echo "skipping unknown disk $disk"
	continue
fi

if [ "$tps" -gt 1 ]; then
	echo "skipping busy disk $disk"
	continue
fi

ofile=$opre.$disk

off=0
[ -f $ofile ] && off=`cat $ofile`

bdev=/dev/$disk
rdev=/dev/r$disk

size=`stat -f "%z" $bdev`
size=`expr $size / 1048576`

if [ $size -gt 0 ]; then
	:
else
	part=`echo "$bdev" | sed -e 's/.*[^a-z]\([a-z]\)$/\1/'`
	size=`disklabel $disk | sed -ne 's/^ *'"$part"': *\([0-9][0-9]*\).*/\1/p'`
	echo "size of $bdev for part $part is $size"
	size=`expr $size / 2048`
fi

if [ $size -gt 0 ]; then
	echo "size of $bdev is $size"
else
	echo "size of $bdev is not positive"
	continue
fi

echo "Start $off"
startoff=$off

now=`date +%s`
then=`expr $now + $seconds`
while [ $now -le $then ]; do
	n=$num
	m=`expr $size - $off`
	echo "Remaining $size - $off = $m"
	[ $n -gt $m ] && n=$m
	echo "Reading chunk at $off size $n"
	if dd if=$rdev of=/dev/null bs=1024k skip=$off count=$n 2>/dev/null; then
		off=`expr $off + $n`
		if [ $off -ge $size ]; then
			off=0
			echo rewind to $off of $size
		else
			echo advance to $off of $size
		fi
		now=`date +%s`
	else
		echo "Failure"
		echo "$0: Reading chunk at $off size $n from $rdev failed" 1>&2

		bigoff=`echo $off '* 2048' | bc -l 2>/dev/null`
		bign=`echo $n '* 2048' | bc -l 2>/dev/null`

		echo "$0: Scanning from block $bigoff + $bign" 1>&2
		goodn=`
		dd if=$rdev of=/dev/null bs=512 skip=$bigoff count=$bign 2>&1 \
		| awk -F+ '/records in/{print $1}'
		`

		badoff=`echo $bigoff + $goodn | bc -l 2>/dev/null`
		echo "$0: Stopped at $badoff" 1>&2

		if dd if=$rdev of=/dev/null bs=512 skip=$badoff count=1 2>/dev/null; then
			echo "$0: Looks ok again ?" 1>&2
		else
			echo "$0: Bad block found at $badoff" 1>&2
		fi


		break
	fi
done

echo "Stop $off"

if [ $startoff = $off ]; then
	echo "No progress"
else
	echo $off > $ofile
fi

done
