#!/bin/sh

# check to see if disk 80 is also hd0 for grub; if yes, exit; if no, fix problem

#fixes: 1. change device.map, 2. fix menu.lst, 3. write grub to correct disk

#set -x
touch /tmp/grubinst-log
tail -f /tmp/grubinst-log &
exec > /tmp/grubinst-log 2>&1
echo "Fixing grub for SAS[56]/ir"

flag=0
grub_device_map="/boot/grub/device.map"
menu_list="/boot/grub/menu.lst"
a=0

#get grub --> sd mapping
declare -a grub_disk
num_grub_disks=`grep -c "hd" $grub_device_map`
count=0
while [ "$count" -lt "$num_grub_disks" ]
do
    grub_disk[$count]=`grep "hd$count" $grub_device_map | cut -f2` 
    let count+=1
done

#get edd --> sd mapping
declare -a edd_disk
for device in ${grub_disk[*]}
do
    temp_output=`/sbin/edd_id $device`
    if [ $? -ne 0 ]; then
       #ignore if edd_id returns error code.
       echo "Ignoring disk device $device"
       continue
    fi
    grub_disk_id=`echo $temp_output | cut -d'8' -f2`
    echo "The Grub disk id is $grub_disk_id"
    edd_disk[$grub_disk_id]="$device"
done

echo "GRUB map: ${grub_disk[*]}"
echo "EDD map: ${edd_disk[*]}"
echo "The boot disk is ${edd_disk[0]}"
fdisk -l ${edd_disk[0]} | grep -i "Dell Utility"
if [ $? -eq 0 ]; then
	boot_partno=2
else
	boot_partno=1
fi

#See if GRUB and EDD mappings match, if not, fix device.map and menu.lst, and write grub again
if [ "${grub_disk[0]}" != "${edd_disk[0]}" ]; then
    #fix device map
    cp -p $grub_device_map $grub_device_map.orig
    sed "/hd/d" $grub_device_map > $grub_device_map.new
    mv -f $grub_device_map.new $grub_device_map
    j=0
    while [ $j -lt ${#edd_disk[*]} ]
    do
	echo "The disk is ${edd_disk[$j]}something"
        if [ -n "${edd_disk[$j]}" ]; then
           echo -e "(hd$j)\t${edd_disk[$j]}" >> $grub_device_map
        fi
        let j+=1
    done
    
    #fix menu.lst and write grub 
    cp -f $menu_list $menu_list.orig
    sed "s|hd[1-9]|hd0|g" $menu_list >> $menu_list.new
    mv -f $menu_list.new $menu_list
    #grub-install ${edd_disk[0]}
    flag=1
fi
[ $flag == "1" ] && grub --batch << EOF
root (hd0,$boot_partno)
install --stage2=/boot/grub/stage2 /grub/stage1 (hd0,$boot_partno) /grub/stage2 0x8000 (hd0,$boot_partno)/grub/menu.lst
quit
EOF

