#! /bin/sh

PREREQ="disks"

prereqs()
{
	echo "$PREREQ"
}

case $1 in
prereqs)
	prereqs
	exit 0
	;;
esac

. /scripts/functions
. /scripts/functions-uniklu

GRUB="no"
HOMES=""
for x in $(cat /proc/cmdline); do
        case $x in
        afshomes=yes)
          HOMES="afshomes=yes"
          ;;
        cifshomes=yes)
          HOMES="cifshomes=yes"
          ;;
        grub=yes)
          GRUB="yes"
          ;;
       esac
done


if [ "$BOOT" = "installimage" -a "$GRUB" = "yes" ]; then
  TARGET=/target
  GRUBSRC=/target 
else
  exit 0
fi

[ "$quiet" != "y" ] && log_begin_msg "Installing GRUB ..."

# find partition where grub will be installed:
rm -f ${TARGET}/boot/__uniklu__.${BOOT}
touch ${TARGET}/boot/__uniklu__.${BOOT}
grub --no-curses >/tmp/hd0 <<EOT
find /boot/__uniklu__.${BOOT}
quit
EOT
rm -f ${TARGET}/boot/__uniklu__.${BOOT}
# extract id from (hd0,X):
LINUXID=$(cat /tmp/hd0 | tr '(,)' ' ' | gawk '/hd0/ {print $2}')


mkdir -p ${TARGET}/boot/grub/
rm -f ${TARGET}/boot/grub/*stage*
cp -rp ${GRUBSRC}/usr/lib/grub/i386-pc/* ${TARGET}/boot/grub/

if [ -z "$LINUXID" ]; then
  panic "could not find partition for GRUB!"
else 

  sed -e "s/%HD0_UNIKLU%/$LINUXID/g" -e "s/%HOMES%/$HOMES/g" ${GRUBSRC}/boot/grub/menu.lst.template > ${TARGET}/boot/grub/menu.lst
  [ "$quiet" != "y" ] && _log_msg "now Installing GRUB"
  grub --no-curses --batch <<__EOTG__ > /dev/null 2>&1
root  (hd0,$LINUXID)
setup (hd0)
__EOTG__
    
  if [ $? -ne 0 ]; then
  panic " -- GRUB failed ???"
  else
    [ "$quiet" != "y" ] && _log_msg "GRUB installed"
  fi
fi

[ "$quiet" != "y" ] && log_end_msg
