#! /bin/sh
#
#   verify.sh -- データが消えているか確認する
#
#	0.0: Jul.  9, 2005 by Dai ISHIJIMA
#	0.1: Feb. 17, 2007 (for wpout08)
#

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=$(( 1024 * 1024 ))
icnt=10
# ブロックサイズ単位でのディスクサイズ
max=$(( ( $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 -e '\e[10A\c'
echo -e '\e7\c'

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

skip=0
while [ $skip -lt $max ]; do
	# カーソル位置
	echo -e '\e8\c'
	echo -e '\e7\c'
	# 計時
	cursec=`tinydate '+%s'`
	# バーグラフ
	p=$(( 100 * $skip / $max ))
	m=$(( 1000 * $skip / $max ))
	q=$(( $p / 2 ))
	i=0
	bar=''
	while [ $i -lt $q ]; do
		bar="$bar"'#'
		i=$(( $i + 1 ))
	done
	while [ $i -lt 50 ]; do
		bar="$bar"'_'
		i=$(( $i + 1 ))
	done
	#
	# 残り時間
	elapsed=$(( $cursec - $startsec ))
	if [ $m -gt 0 ]; then
		remain=$(( ( 1000 - $m ) * $elapsed / $m + 1 ))
		if [ $remain -gt 120 ]; then
			rems=$(( ( $remain + 59 ) / 60 ))
			rems="${rems} [min]"
		else
			rems="${remain} [sec]"
		fi
	fi
	if [ $elapsed -gt 120 ]; then
		elas=$(( ( $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=$(( $zero + $icnt )) ;;
				1) one=$(( $one + $icnt )) ;;
				2) maybe=$(( $maybe + $icnt )) ;;
				*) unerased=$(( $unerased + $icnt )) ;;
			esac
			;;
	esac
	# 次ループ
	checked=$(( $checked + $icnt ))
	skip=$(( $skip + $icnt + $step ))
done

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

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

unerased=$(( $unerased + $maybe ))
zp=$(( $zero * 100 / $checked ))
op=$(( $one * 100 / $checked ))
np=$(( $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 "Verified $checked blocks" > /tmp/verify-log.$disk
echo -n " erased with 0:${zp}%, 1:${op}%, " >> /tmp/verify-log.$disk
echo "unerased:${np}%" >> /tmp/verify-log.$disk
echo " epoch: $startsec -> $cursec" >> /tmp/verify-log.$disk

echo -n 'Press ENTER to return menu...'
read x

exit 0

# EOF
