#! /bin/sh
#
#   erase.sh -- データを上書きして情報を消す
#
#	0.0: Oct. 30, 2001 by Dai ISHIJIMA (e.sh, for v00)
#	0.1: Oct. 22, 2002 (for v01, variable disk size)
#	0.2: May   1, 2004 (for v02, 0, 1, random)
#	0.3: Jun. 20, 2004 (for v03, menu/floppy)
#	0.4: Feb. 17, 2007 (for v08, 乱数パターンと補数)
#	0.5: Feb.  7, 2010 (for ubuntu-gpxe)
#	0.6: Feb. 16, 2010 (check ubuntu, puppy, slax)
#

stuff='-z'
disk="${2:-sda}"

escapechar="${ESCAPECHAR:-'\033'}"

dkinfo=`fdisk -l "/dev/$disk" 2>/dev/null | grep "^Disk /dev/"`

case x"$dkinfo" in
    x)
	echo "can't get disk information: $disk"
	exit 1
	;;
esac

echo ''; echo ''; echo ''
echo "*** erase data on ${dkinfo}"
echo -n "    with "
case x"$stuff" in
	x-z)	method='write 0'
		echo "writing '0' onto the disk" ;;
esac

echo -n "Ok? [y]: "
#sh dummyread.sh
read ans
case x"$ans" in
	x[!yY]*) echo 'canceled'; exit 1;;
esac

echo -n "Really? [yes]: "
#sh dummyread.sh
read ans
case x"$ans" in
	x[!yY]*) echo 'canceled'; exit 1;;
esac


# 消去のパラメータ
bytes=`fdisk -l /dev/$disk 2>/dev/null | grep "^Disk /dev/" | awk '{print $5}'`
unitlen=$(( 32 * 1024 * 1024 ))
ibs=1024
icnt=$(( $unitlen / $ibs ))
obs=$(( 1024 * 1024 ))
ocnt=$(( $unitlen / $obs ))
max=$(( ( $bytes + $obs - 1 ) / $obs ))

#
echo ''

echo ''; echo ''; echo ''; echo ''; echo '';
echo ''; echo ''; echo ''; echo ''; echo '';
echo -n "$escapechar"; echo -n '[10A'
echo -n "$escapechar"; echo -n '7'

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

skip=0
while [ $skip -le $max ]; do
	# カーソル位置
	echo -n "$escapechar"; echo -n '8'
	echo -n "$escapechar"; echo -n '7'
	# 計時
	cursec=`date '+%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 "erasing data on disk: ${disk}.  ${p}% ($skip/$max) 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/zero ibs=$ibs obs=$obs seek=$skip count=$icnt of=/dev/$disk
			;;
	esac
	# 次ループ
	skip=$(( $skip + $ocnt ))
done

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

cursec=`date '+%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

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

exit 0

# EOF
