#! /bin/sh

stuff="${1:--z}"
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`

echo ''; echo ''; echo ''
echo "*** erase data on ${disk} ${dname}, ${bytes} bytes"
echo -n "    with "
case x"$stuff" in
	x-z)	echo "writing '0' onto the disk" ;;
	x-f)	echo "writing '1' onto the disk" ;;
	x-r)	echo "writing  random data onto the disk" ;;
esac

echo -n "Ok? [y/n]: "
read ans
case x"$ans" in
	xy)	;;
	*)	echo 'canceled'; exit 1;;
esac

echo -n "Really? [yes/no]: "
read ans
case x"$ans" in
	xyes)	;;
	*)	echo 'canceled'; exit 1;;
esac


# 消去のパラメータ
bytes=`diskinfo -b /dev/r$disk`
obs=`expr 1024 '*' 1024`
ibs=1024
icnt=32768
ocnt=32
max=`expr '(' $bytes + $obs - 1 ')' / $obs`

#
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 -le $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 "erasing 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
			;;
		*)
			stuff $stuff | dd ibs=$ibs obs=$obs seek=$skip count=$icnt of=/dev/r$disk
			;;
	esac
	# 次ループ
	skip=`expr $skip + $ocnt`
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

echo "completed ($elas)"
echo ''
echo -n 'Press ENTER to return menu...'
read x

exit 0

# EOF
