#! /bin/ksh

#
# Name        : ${HOME}/bin/MBR.ksh
#
# Version     : 1.0
#
# Author      : Gerard van Wageningen
#
# Description : Master Boot Record structure
#
# 1.0   First Version
#

\whence set_debug 1>/dev/null 2>&1 && eval $( set_debug ${0##*/} )

# Read Master Boot Record from first sector of disk /dev/hda to 0000:7C00
# 0x000 - 0x1b7: 440 bytes Code Area (i386 real mode machine 
#		 language instructions)
# 0x1b8 - 0x1bb: 4 bytes Optional Disk signature
# 0x1bc - 0x1bd: 2 bytes, Usually Nulls
# 0x1be - 0x1cd: 16 bytes entry Partition 1
# 0x1ce - 0x1dd: 16 bytes entry Partition 2
# 0x1de - 0x1ed: 16 bytes entry Partition 3
# 0x1ee - 0x1fd: 16 bytes entry Partition 4
# 0x1fe: 0x55, boot signature lowest byte (little-endian)
# 0x1ff: 0xAA, boot signature highest byte (little-endian)
#2 bytes 	bootsignatuur (0xAA55)
#
# 16 Byte IBM Partition Table scheme
# 0x0 	Status flag 	0x80 = bootable; 0x00 = non-bootable
# 0x1 	Start head 	
# 0x2 	Start sector 	
# 0x3 	Start cylinder 	
# 0x4 	Partition type 	0x0F = extended Partition
# 0x5 	End head 	
# 0x6 	End sector 	
# 0x7 	End cylinder 	
# 0x8-0xb 	Logical block address
# 0xc-0xf	Length of the partition, in sectors

# dd if=/dev/hda of=mbr.bin bs=512 count=1
# dd if=mbr.bin of=/dev/hda bs=446 count=1 # Do not overwrite partition table

typeset BYTE=''
typeset b=''
typeset -i i=0

set -A BYTE $( sudo dd if=/dev/hda bs=512 count=1 2>/dev/null \
               | od -t x1 \
               | sed -e 's/^........//g; $d' \
               | tr 'a-z' 'A-Z'
             )

if [[ "${BYTE[ 16#1fe ]}" != '55' || "${BYTE[ 16#1ff ]}" != 'AA' ]]
then
  print -u2 "Sector does not contain valid boot signature."
  exit 1
fi

for b in "${BYTE[16#1be]}" "${BYTE[16#1ce]}" "${BYTE[16#1de]}" "${BYTE[16#1ee]}"
do
 i=i+1
 case "${b}" in
    00) print "Partition ${i} is non-bootable." ;;
    80) print "Partition ${i} is bootable." ;;
    *)  print -u2 "Partition ${i} is invalid." ; exit 1 ;; 
 esac
done


exit 0

################### EOF ###################
