#!/bin/bash -e

exitproc()
{ umount $TMPDIR;rmdir $TMPDIR; }
trap '
exitproc
exit 1
' 2 15

getrawhs()
{
set +e
hdinfo="$(hdparm -i $DEVICE 2>/dev/null)"
if test $? -ne 0; then
USERHSMAND=true
else
set -e
for info in $hdinfo; do
case "$info" in *RawCHS=*) RawCHS="${info#RawCHS=}"; ;; esac
done
RawH=$(echo $RawCHS|cut -d"/" -f2)
RawS=$(echo $RawCHS|cut -d"/" -f3|sed 's/\,//')
fi
set -e
echo "RawHS=$RawH/$RawS"
}

analize_sector()
{
local cylinder=${1}
local offset=${2}
local start=$((cylinder + 1))
if (file $TMPDIR/$image|grep -iq "x86 boot sector") then
if (strings $TMPDIR/$image|grep -q NTFS) then
	type="NTFS Boot Sector"
elif (strings $TMPDIR/$image|grep -q MSWIN) then
	type="FAT Boot Sector"
elif (strings $TMPDIR/$image|grep -q GRUB) then
	type="GRUB Boot Sector"
else
	type=
fi
if [ $offset -eq -1 -a "$type" == "NTFS Boot Sector" ]; then
echo "   Cylinder $(($start - 1)) is NTFS End Cylinder"
$DEBUG && echo
else
echo -n "Start-Cylinder $start"
echo -en "\toffset $offset"
echo -e "\t$type"
$DEBUG && echo -n "SectorImage: "
$DEBUG && strings $TMPDIR/$image|tr -d '\012'
$DEBUG && (echo;echo)
fi
fi
return 0
}


DEVICE=$1
if [ $# -lt 2 ]; then
if [ $# -gt 0 ]; then
getrawhs
fi
echo "eg. $0 /dev/sda -HS=255/63"
echo "eg. $0 /dev/sda -HS=64/32"
echo "eg. $0 /dev/sda -HS=16/32"
echo "eg. $0 /dev/sda -HS=32/16"
echo "eg. $0 /dev/sda -HS=32/32"
echo "eg. $0 /dev/sda -HS=16/16"
exit 1
fi

DEBUG=false
USERHSMAND=false
HS=$2
devname=${DEVICE##*/}
LANG=C

# User specified HS 
for x in $2; do
case "$x" in *-HS=*) hs="${x#-HS=}"; ;; esac
done
H=$(echo $hs|cut -d"/" -f1)
S=$(echo $hs|cut -d"/" -f2)
#H=${H:-$RawH}
#S=${S:-$RawS}

test "$S" = "" && exit

cylindersize=$(($H * $S))
wholesize=$(cat /sys/block/$devname/size)
cylinders=$(($wholesize / $cylindersize))
TMPDIR=`mktemp -d`

mount -t tmpfs -o "size=100k" tmpfs $TMPDIR

echo "Target Device: $DEVICE"
echo "Total Cylinders: $cylinders"
echo "H/S=$H/$S"
echo

for ((i=0;i<$cylinders;i++))
do
skipsectors=$(($i * $cylindersize ))

if [ $i -eq 0 ]; then
skipsectors=$(($skipsectors + $S))
fi

skipsectors=$(($skipsectors - 1))
dd if=$DEVICE count=1 of=$TMPDIR/1.img skip=$skipsectors 2>/dev/null
skipsectors=$(($skipsectors + 1))
dd if=$DEVICE count=1 of=$TMPDIR/2.img skip=$skipsectors 2>/dev/null
skipsectors=$(($skipsectors + $S))
dd if=$DEVICE count=1 of=$TMPDIR/3.img skip=$skipsectors 2>/dev/null

image=1.img
analize_sector $i -1
image=2.img
analize_sector $i 0
image=3.img
analize_sector $i $S

done

exitproc
exit 0
