#! /bin/sh

step="${1:-1}"
disk="${2:-ad0}"

dmesg=/var/run/dmesg.boot
dname=`sed -n -E "/^${disk}:.*<.*>/p" $dmesg | sed 's/.*\(<.*>\).*/\1/'`
bytes=`diskinfo -B /dev/r$disk`
cap=`diskinfo -p /dev/r$disk`

# 消去のパラメータ
bytes=`diskinfo -b /dev/r$disk`
# 10Mバイトずつ確認
ibs=`expr 1024 '*' 1024`
icnt=10
# ブロックサイズ単位でのディスクサイズ
max=`expr '(' $bytes + $ibs - 1 ')' / $ibs`

# 結果
zero=0
one=0
maybe=0
unerased=0
checked=0

#
echo ''

echo ''; echo ''; echo ''; echo ''; echo '';
echo ''; echo ''; echo ''; echo ''; echo '';
echo -n '[10A'
echo -n '7'

startsec=`tinydate '+%s'`
rems='??? [min]'

skip=0
while [ $skip -lt $max ]; do
	# カーソル位置
	echo -n '8'
	echo -n '7'
	# 計時
	cursec=`tinydate '+%s'`
	# バーグラフ
	p=`expr 100 '*' $skip / $max`
	m=`expr 1000 '*' $skip / $max`
	q=`expr $p / 2`
	i=0
	bar=''
	while [ $i -lt $q ]; do
		bar="$bar"'#'
		i=`expr $i + 1`
	done
	while [ $i -lt 50 ]; do
		bar="$bar"'_'
		i=`expr $i + 1`
	done
	#
	# 残り時間
	elapsed=`expr $cursec - $startsec`
	if [ $m -gt 0 ]; then
		remain=`expr '(' 1000 - $m ')' '*' $elapsed / $m + 1`
		if [ $remain -gt 120 ]; then
			rems=`expr '(' $remain + 59 ')' / 60`
			rems="${rems} [min]"
		else
			rems="${remain} [sec]"
		fi
	fi
	if [ $elapsed -gt 120 ]; then
		elas=`expr '(' $elapsed + 30 ')' / 60`
		elas="${elas} [min]"
	else
		elas="${elapsed} [sec]"
	fi
	#
	echo "verifying data on disk: ${disk}.  ${p}% done"
	echo "${elas} elapsed, ${rems} remains (approx.)   "
	echo ''
	echo "    0%|${bar}|100%"
	echo ''
	case x$DEBUG in
		x[Yy]*)
			echo 'now in debug mode...'
			sleep 1
			;;
		*)
			dd if=/dev/r$disk ibs=$ibs skip=$skip count=$icnt | check -s
			case $? in
				0) zero=`expr $zero + $icnt` ;;
				1) one=`expr $one + $icnt` ;;
				2) maybe=`expr $maybe + $icnt` ;;
				*) unerased=`expr $unerased + $icnt` ;;
			esac
			;;
	esac
	# 次ループ
	checked=`expr $checked + $icnt`
	skip=`expr $skip + $icnt + $step`
done

echo ''; echo ''; echo ''; echo ''; echo ''

cursec=`tinydate '+%s'`
elapsed=`expr $cursec - $startsec`
if [ $elapsed -gt 120 ]; then
	min=`expr $elapsed / 60`
	sec=`expr $elapsed - $min '*' 60`
	elas="${min} [min] ${sec} [sec]"
else
	elas="${elapsed} [sec]"
fi

unerased=`expr $unerased + $maybe`
zp=`expr $zero '*' 100 / $checked`
op=`expr $one '*' 100 / $checked`
np=`expr $unerased '*' 100 / $checked`

echo "completed ($elas)"
echo ''
echo "$checked blocks verified (total $max blocks)"
echo " erased with '0': $zero blocks ($zp %)"
echo " erased with '1': $one blocks ($op %)"
echo "        unerased: $unerased blocks ($np %)"
echo ''
echo -n 'Press ENTER to return menu...'
read x

exit 0

# EOF
