#! /bin/bash

# (c) Michael Goetze, 2011, mgoetze@mgoetze.net

error=0; trap 'error=$(($?>$error?$?:$error))' ERR # save maximum error code

if [ -r $LOGDIR/disk_var.sh ] ; then
	. $LOGDIR/disk_var.sh
else
	echo "disk_var.sh not found!"
	exit 1
fi

bootdev=`device2grub $BOOT_DEVICE`
bootpart=`device2grub $BOOT_PARTITION`
version=`$ROOTCMD rpm -qv kernel | cut -d- -f2-`

if grep '[[:space:]]/boot[[:space:]]' $LOGDIR/fstab; then
	bootdir=''
else
	bootdir='/boot'
fi

mount -o bind /dev $target/dev


$ROOTCMD grub-install --just-copy

$ROOTCMD grub --device-map=/dev/null --no-floppy --batch <<-EOF
	device $bootdev $BOOT_DEVICE
	root $bootpart
	setup $bootdev
	quit
	EOF

umount $target/dev

ln -s ./menu.lst $target/boot/grub/grub.conf

if [ -f $target/boot/grub/splash.xpm.gz ]; then
	pretty="splashimage=$bootpart$bootdir/grub/splash.xpm.gz"
else
	pretty="color cyan/blue white/blue"
fi

if [ -f $target/sbin/dracut ]; then
    # CentOS 6
    iname=initramfs
else
    # CentOS 5
    iname=initrd
fi
title=`head -1 $target/etc/redhat-release`

cat > $target/boot/grub/grub.conf <<-EOF
	timeout 5
	default 0
	$pretty
	hiddenmenu
	
	title $title
	  root $bootpart
	  kernel $bootdir/vmlinuz-$version root=$ROOT_PARTITION ro
	  initrd $bootdir/$iname-$version.img
	EOF


echo ""
echo "Grub installed on $BOOT_DEVICE = $bootdev"
echo "Grub boot partition is $BOOT_PARTITION = $bootpart"
echo "Root partition is $ROOT_PARTITION"
echo "Boot kernel: $version"

exit $error
