#! /bin/bash

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

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


# CentOS 7 does not have a device.map file, so generate one
if [ -d $target/boot/grub2 -a ! -f $target/boot/grub2/device.map ]; then
    echo "# Generated by FAI" >> $target/boot/grub2/device.map
    centosdisks=$(awk '/[sv]d.$/ {print $4}' /proc/partitions | sort)
    dcount=0
    for d in $centosdisks; do
        echo "(hd$dcount)    /dev/$d" >> $target/boot/grub2/device.map
        dcount=$((dcount + 1))
    done
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

if [ -f $target/usr/sbin/grub2-install ]; then

    # CentOS 7
    $ROOTCMD grub2-install --no-floppy "$BOOT_DEVICE"
    $ROOTCMD grub2-mkconfig --output=/boot/grub2/grub.cfg
else

$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

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

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/initramfs-$version.img
	EOF

fi

umount $target/dev

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
