#!/bin/sh


# grub-MR ------ a rudimentary replacement for grub-install
#
#
#
#
# 2003/08/24
# - fixed line 26 (Christian)
#
# 2002/11/18
# - first incarnation



Die() {
    echo "$1" >> /dev/stderr
    exit 1
}


FindBootPart() {
    for sz in /boot / ; do
	bootpart=`cat $2 | grep " $sz " | cut -d' ' -f1 | head -n1`
	[ "$bootpart" ] && [ "/mnt/RESTORING/$bootpart" ] && break
    done
    [ ! "$bootpart" ] && Die "Cannot find boot partition in mountlist"
    echo "$bootpart"
}

FindPathOfRESTExe() {
    local path
    for path in /usr/sbin /usr/bin /usr/local/sbin /usr/local/bin \
/bin /sbin ; do
        if [ -f "/mnt/RESTORING/$path/$1" ] ; then 
            echo "/mnt/RESTORING/$path/$1"
        fi
    done
}


# ---------------------------------- main -----------------------------------

if [ "$#" -ne "2" ] ; then
    Die "grub-MR <MBR drive> <mountlist filename>; e.g. grub-MR /dev/hda /tmp/mountlist.txt"
fi
[ ! -f "$2" ] && Die "mountlist file not found"
bootpart=`FindBootPart $1 $2`
mbrpart=$1
partno=`basename $bootpart | sed s/[a-z]*//`
if [ ! "$partno" ] ; then
    partno=0
else
    partno=$(($partno-1))
fi
grub=`FindPathOfRESTExe grub`
echo "grub = $grub"
echo -en "device (hd0) $mbrpart\nroot (hd0,$partno)\nsetup (hd0)\nquit\n" | $grub --batch --device-map=/dev/null
exit $?
