#!/bin/bash
#################################################
#       Title:  mk-setup-grub                   #
#        Date:  2014-11-26                      #
#     Version:  1.0                             #
#      Author:  sharathg@vmware.com             #
#     Options:                                  #
#################################################
#   Overview
#       This is a precursor for the vmware build system.
#       This assumes that an empty hard disk is attached to the build VM.
#       The path to this empty disk is specified in the HDD variable in config.inc
#   End
#
grub_efi_install()
{
    mkdir $BUILDROOT/boot/efi
    mkfs.vfat /dev/sda1
    mount -t vfat /dev/sda1 $BUILDROOT/boot/efi
    cp boot/unifont.pf2 /usr/share/grub/
    grub2-efi-install --target=x86_64-efi --efi-directory=$BUILDROOT/boot/efi --bootloader-id=Boot --root-directory=$BUILDROOT --recheck --debug
    mv $BUILDROOT/boot/efi/EFI/Boot/grubx64.efi $BUILDROOT/boot/efi/EFI/Boot/bootx64.efi
    umount $BUILDROOT/boot/efi
}

grub_mbr_install()
{
    $grubInstallCmd --force --boot-directory=$BUILDROOT/boot "$HDD"
}

set -o errexit      # exit if error...insurance ;)
set -o nounset      # exit if variable not initalized
set +h          # disable hashall
PRGNAME=${0##*/}    # script name minus the path
source config.inc       #   configuration parameters
source function.inc     #   commonn functions
LOGFILE=/var/log/"${PRGNAME}-${LOGFILE}"    #   set log file name
#LOGFILE=/dev/null      #   uncomment to disable log file
ARCH=$(uname -m)    # host architecture
[ ${EUID} -eq 0 ]   || fail "${PRGNAME}: Need to be root user: FAILURE"
> ${LOGFILE}        #   clear/initialize logfile

# Check if passing a HHD and partition
if [ $# -eq 3 ] 
	then
        BOOTMODE=$1
		HDD=$2
		PARTITION=$3
fi

#
#   Install grub2.
#
echo "Changing boot loader to MBR type on raw disk"
sgdisk -m 1:2 "$HDD"
UUID=$(blkid -s UUID -o value $PARTITION)

grubInstallCmd=""
mkdir -p $BUILDROOT/boot/grub2
ln -sfv grub2 $BUILDROOT/boot/grub
command -v grub-install >/dev/null 2>&1 && grubInstallCmd="grub-install" && { echo >&2 "Found grub-install"; }
command -v grub2-install >/dev/null 2>&1 && grubInstallCmd="grub2-install" && { echo >&2 "Found grub2-install"; }
if [ -z $grubInstallCmd ]; then
echo "Unable to find grub install command"
exit 1
fi

cp boot/unifont.pf2 ${BUILDROOT}/boot/grub2/
mkdir -p ${BUILDROOT}/boot/grub2/themes/photon
cp boot/splash.tga ${BUILDROOT}/boot/grub2/themes/photon/photon.tga
cp boot/terminal_*.tga ${BUILDROOT}/boot/grub2/themes/photon/
cp boot/theme.txt ${BUILDROOT}/boot/grub2/themes/photon/

if [ "$BOOTMODE" == "bios" ]; then 
    grub_mbr_install
fi
if [ "$BOOTMODE" == "efi" ]; then 
    grub_efi_install
fi

cat > "$BUILDROOT"/boot/grub2/grub.cfg << "EOF"
# Begin /boot/grub2/grub.cfg
#
# DO NOT EDIT THIS FILE
#
# It is automatically generated by grub-mkconfig using templates
# from /etc/grub.d and settings from /etc/default/grub
#

### BEGIN /etc/grub.d/00_header ###
if [ -s $prefix/grubenv ]; then
  load_env
fi
set default="0"

if [ x"${feature_menuentry_id}" = xy ]; then
  menuentry_id_option="--id"
else
  menuentry_id_option=""
fi

export menuentry_id_option

if [ "${prev_saved_entry}" ]; then
  set saved_entry="${prev_saved_entry}"
  save_env saved_entry
  set prev_saved_entry=
  save_env prev_saved_entry
  set boot_once=true
fi

function savedefault {
  if [ -z "${boot_once}" ]; then
    saved_entry="${chosen}"
    save_env saved_entry
  fi
}

function load_video {
  if [ x$feature_all_video_module = xy ]; then
    insmod all_video
  else
    insmod efi_gop
    insmod efi_uga
    insmod ieee1275_fb
    insmod vbe
    insmod vga
    insmod video_bochs
    insmod video_cirrus
  fi
}

serial --speed=38400 --unit=0 --word=8 --parity=no --stop=1
terminal_input serial
terminal_output serial
set timeout=5
### END /etc/grub.d/00_header ###

### BEGIN /etc/grub.d/10_linux ###
menuentry 'GNU/Linux' --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-simple-UUID_PLACEHOLDER' {
    load_video
    set gfxpayload=keep
    insmod gzio
    insmod part_msdos
    insmod ext2
    set root='hd0,msdos2'
    if [ x$feature_platform_search_hint = xy ]; then
      search --no-floppy --fs-uuid --set=root --hint-bios=hd0,msdos2 --hint-efi=hd0,msdos2 --hint-baremetal=ahci0,msdos2  UUID_PLACEHOLDER
    else
      search --no-floppy --fs-uuid --set=root UUID_PLACEHOLDER
    fi
    echo    'Loading Linux 4.2.0 ...'
    linux   /boot/vmlinuz-4.2.0 root=/dev/sda2 ro console=ttyS0,38400n8 
}
submenu 'Advanced options for GNU/Linux' $menuentry_id_option 'gnulinux-advanced-UUID_PLACEHOLDER' {
    menuentry 'GNU/Linux, with Linux 4.2.0' --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-4.2.0-advanced-UUID_PLACEHOLDER' {
        load_video
        set gfxpayload=keep
        insmod gzio
        insmod part_msdos
        insmod ext2
        set root='hd0,msdos2'
        if [ x$feature_platform_search_hint = xy ]; then
          search --no-floppy --fs-uuid --set=root --hint-bios=hd0,msdos2 --hint-efi=hd0,msdos2 --hint-baremetal=ahci0,msdos2  UUID_PLACEHOLDER
        else
          search --no-floppy --fs-uuid --set=root UUID_PLACEHOLDER
        fi
        echo    'Loading Linux 4.2.0 ...'
        linux   /boot/vmlinuz-4.2.0 root=/dev/sda2 ro console=ttyS0,38400n8 
    }
    menuentry 'GNU/Linux, with Linux 4.2.0 (recovery mode)' --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-4.2.0-recovery-UUID_PLACEHOLDER' {
        load_video
        set gfxpayload=keep
        insmod gzio
        insmod part_msdos
        insmod ext2
        set root='hd0,msdos2'
        if [ x$feature_platform_search_hint = xy ]; then
          search --no-floppy --fs-uuid --set=root --hint-bios=hd0,msdos2 --hint-efi=hd0,msdos2 --hint-baremetal=ahci0,msdos2  UUID_PLACEHOLDER
        else
          search --no-floppy --fs-uuid --set=root UUID_PLACEHOLDER
        fi
        echo    'Loading Linux 4.2.0 ...'
        linux   /boot/vmlinuz-4.2.0 root=/dev/sda2 ro single console=ttyS0,38400n8
    }
}

### END /etc/grub.d/10_linux ###

### BEGIN /etc/grub.d/20_linux_xen ###

### END /etc/grub.d/20_linux_xen ###

### BEGIN /etc/grub.d/30_os-prober ###
### END /etc/grub.d/30_os-prober ###

### BEGIN /etc/grub.d/40_custom ###
# This file provides an easy way to add custom menu entries.  Simply type the
# menu entries you want to add after this comment.  Be careful not to change
# the 'exec tail' line above.
### END /etc/grub.d/40_custom ###

### BEGIN /etc/grub.d/41_custom ###
if [ -f  ${config_directory}/custom.cfg ]; then
  source ${config_directory}/custom.cfg
elif [ -z "${config_directory}" -a -f  $prefix/custom.cfg ]; then
  source $prefix/custom.cfg;
fi
### END /etc/grub.d/41_custom ###

# End /boot/grub2/grub.cfg
EOF

sed -i "s/UUID_PLACEHOLDER/$UUID/" "$BUILDROOT"/boot/grub2/grub.cfg > ${LOGFILE} 

#Cleanup the workspace directory
#find "$BUILDROOT"/{,usr/}{lib,bin,sbin} -type f -exec strip --strip-debug --strip-unneeded '{}' ';' > /dev/null 2>&1
rm -rf "$BUILDROOT"/tools
rm -rf "$BUILDROOT"/RPMS

#umount $BUILDROOT