#!/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
firstsector=$(fdisk -lu ${DISK}|grep "${DEVICE} "|sed 's/\*//'|awk '{print $2}')
lastsector=$(fdisk -lu ${DISK}|grep "${DEVICE} "|sed 's/\*//'|awk '{print $3}')
fsid=$(fdisk -lu ${DISK}|grep "${DEVICE} "|sed 's/\*//'|awk '{print $5}')
if [ "${fsid}" != "7" ]; then
echo "Error, ${DEVICE}: Id is not 07"
exit 1
fi
echo "firstsector :${firstsector}"
echo "lastsector :${lastsector}"
sectors=$((${lastsector} - ${firstsector} +1))
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") || \
   (strings ${outputfile}|grep -iq "BOOTMGR is compressed") 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
