#! /bin/bash
# bash is important because for echo -e

# edit the magic number of boot sector (the last two bytes)
# (c) 2001, Thomas Lange, lange@informatik.uni-koeln.de

seek=510

usage() {

cat <<EOF
    bootsector [-edlvh] device

Read or write the magic number (the last two bytes) of a boot
sector. Writing 0x0000 to it disables booting from this boot sector.
The value 0xAA55 enables booting from this boot sector.

    -e    enable the boot sector
    -d    disable the boot sector
    -l    list the magic number hexadecimal
    -v    list the magic number in a verbose way
    -h    print this help

Examples:

# bootsector -e /dev/hda
# bootsector -l /dev/hda
0000000 aa55
# bootsector -d /dev/hda
# bootsector -l /dev/hda
0000000 0000
# bootsector -v /dev/hda
Boot sector /dev/hda disabled.

bootsector is written by Thomas Lange, lange@informatik.uni-koeln.de, 2001.

EOF
exit 0
}

readbb() { # read last two bytes from boot block

    dd bs=1c skip=$seek count=2 if=$1 2>/dev/null|od -x|grep -v 0000002
}

writebb() { # write last two bytes of boot block

    dd bs=1c seek=$seek of=$1 2>/dev/null || echo "Can't write to boot block $1"
}

arch=`dpkg --print-installation-architecture`
[ "$arch" = "i386" ] || {
    Currently, only i386 architecure is supported.
    exit 1
}

getopts e:d:l:v:h opt
case $opt in
    h) usage ;;
    e) echo -ne "\x55\xaa" | writebb $OPTARG ;;
    d) echo -ne "\x0\x0"   | writebb $OPTARG ;;
    l) readbb $OPTARG ;;
    v) bs=`readbb $OPTARG`
       case $bs in
	    "0000000 0000") echo "Boot sector $OPTARG is disabled." ;;
	    "0000000 aa55") echo "Boot sector $OPTARG is enabled." ;;
	    *) echo "Unknown boot sector $bs" ;;
       esac
       ;;
    *) usage; exit 1 ;;
esac
