#!/bin/sh

LogIt "mbr-me --- starting"
if [ "$#" -ne "1" ] ; then
    echo "mbr-me <bytes>  ... e.g. mbr-me 446"
    exit 1
fi

count=$1

> /tmp/maybe-bootable.txt
for i in `find /mnt/cdrom/archives | grep \.mbr` ; do
    stub=`echo $i | cut -d'.' -f1 | cut -d'/' -f5`
    device=/dev/$stub
    LogIt "(mbr-me) i=$i; stub=$stub; device=$device"
    res=`fdisk -l $device 2> /dev/null`
    if [ "$res" = "" ] ; then
        LogIt "$device ignored (drive not found)." 1
        continue
    fi
    dd if=$device of=/tmp/$stub.mbr.original bs=1 count=512 &> /dev/null
    dd if=$i of=$device bs=1 count=$1 &> /tmp/dd.log
    if [ "$?" -ne "0" ] ; then
        cat /tmp/dd.log
        LogIt "Failed to restore $device's MBR." 1
    else 
        LogIt "$device's MBR was restored ok." 2
        echo "$device" >> /tmp/maybe-bootable.txt
    fi
#    dd if=/tmp/$stub.mbr.original bs=1 count=64 skip=446 seek=446 \
#&> /dev/null
#    if [ "$?" -ne "0" ] ; then
#        echo "Unable to restore MBR's original partition list."
#    fi
done

if [ "`cat /proc/cmdline | grep "cuckoo"`" != "" ] ; then
    echo "calling make-me-bootable"
    make-me-bootable /tmp/maybe-bootable.txt
fi

LogIt "mbr-me --- leaving"
exit 0
