#!/bin/bash -e
if [ $# -lt 1 ]; then
echo "eg. $0 /dev/sda1"
exit 1
fi
LANG=C
DEVICE=$1
common=${DEVICE%/*}
devname=${DEVICE##*/}
left3char=$(echo ${devname}|cut -b1-3)
devicenumber=$(echo ${devname}|cut -b4-)
DISK=${common}/${left3char}
echo "Target Disk :${DISK}"
echo "Target Partition :${DEVICE}"
outputfile=backuped-${devname}-pbr.img
firstcylinder=$(fdisk -l ${DISK}|grep "${DEVICE} "|sed 's/\*//'|awk '{print $2}')
lastcylinder=$(fdisk -l ${DISK}|grep "${DEVICE} "|sed 's/\*//'|awk '{print $3}')
fsid=$(fdisk -l ${DISK}|grep "${DEVICE} "|sed 's/\*//'|awk '{print $5}')
if [ "${fsid}" != "7" ]; then
echo "Error, ${DEVICE}: Id is not 07"
exit 1
fi
echo "firstcylinder :${firstcylinder}"
echo "lastcylinder :${lastcylinder}"
cylinders=$((${lastcylinder} - ${firstcylinder} + 1))
echo "cylinders :${cylinders}"
st=$(fdisk -l ${DISK}|grep "sectors/track"|awk '{print $3}')
echo "sectors / track :${st}"
sc=$(fdisk -l ${DISK}|grep "cylinders of"|awk '{print $5}')
echo "sectors / cylinder :${sc}"
if [ ${devicenumber} -le 4 ]; then
sectors=$((${cylinders} * ${sc}))
else
sectors=$((${cylinders} * ${sc} - ${st}))
fi
if [ ${firstcylinder} -eq 1 ]; then
sectors=$((${sectors} - ${st}))
fi
echo "total sectors :${sectors}"
skipsectors=$((${sectors} -1))
echo "skipsectors :${skipsectors}"
echo
echo "Extracting backuped PBR..."
dd if=${DEVICE} of=${outputfile} bs=512 skip=${skipsectors} >/dev/null 2>&1
filesize=$(stat -c %s ${outputfile})
echo
if [ ${filesize} -eq 512 ]; then
if (file ${outputfile}|grep -q "NTFS") then
echo "Finished, ${outputfile} is here."
echo "You may execute \"dd if=${outputfile} of=${DEVICE}\""
elif (file ${outputfile}|grep -iq "x86 boot sector") then
if (strings ${outputfile}|grep -iq "NTLDR is missing") then
echo "Finished, ${outputfile} is here."
echo "You may execute \"dd if=${outputfile} of=${DEVICE}\""
fi
else
echo "Error, Not a NTFS boot sector"
exit 1
fi
else
echo "Error, filesize :${filesize}"
fi
