#! /bin/bash -
#
# This file is part of the 'dragora-installer'.
#
# Purpose: Installation of GRUB boot loader into /media/dragora-root.

# Exit immediately on any error
set -e

# Make sure to have /proc and /dev available to install GRUB
if ! mountpoint -q /media/dragora-root/dev
then
    mount --bind /dev /media/dragora-root/dev
fi
if ! mountpoint -q /media/dragora-root/proc
then
    mount -t proc proc /media/dragora-root/proc
fi
if ! mountpoint -q /media/dragora-root/sys
then
    mount -t sysfs sysfs /media/dragora-root/sys
fi

# Loop for the main menu
while true
do
    dialog --colors \
     --backtitle "\\ZbBoot loader installation" \
     --title "GRand Unified Bootloader" \
     --default-button "${_default_button:-ok}" \
     --ok-label "Install" \
     --cancel-label "Ignore & Continue" \
     --menu \
"It's time to install a boot loader (GNU GRUB).\\n\\n\
If you do not have a boot loader, it is recommended to install it in\\n\
the Master Boot Record (MBR).  It is possible to overwrite your current \
boot loader.\\n\\n\
You can also install the boot loader on the Root partition (superblock), \
but note that the partition needs the boot flag to boot.  If you have not \
used this flag before when you created the partitions you can do so later \
by invoking 'cfdisk' or 'fdisk'." 19 72 2 \
     "0" "Install GRUB on the Master Boot Record" \
     "1" "Install GRUB on the Super block" \
     2> "${SUBTMPDIR}/return-MenuBootloader" || _status=$?
    if test -n "$_status" && test $_status -gt 0
    then
        if test $_status -eq 1
        then
            return 0		# Ignore exit status on 'Cancel'.
        fi
        return "$_status"	# Any other dialog(1) code.
    fi

    answer="$(cat -- "${SUBTMPDIR}"/return-MenuBootloader)"

    # Check for selected options
    case $answer in
    0 | 1) ## Master Boot Record or Super block

        # Defining the title of the subsequent menu
        if test "$answer" = 0
        then
            _submenu_title="Master Boot Record"
        else
            _submenu_title="Super block"
        fi

        # Check if it is a logical volume
        if pvs | grep -q dev
        then
            array=()

            pvs --ignorelockingfailure --noheadings | awk '{ print $1 }' | \
             while IFS='' read -r line
            do
                array+=("$line")
            done

            # Verify in which partition to install
            if (( ${#array[*]} > 1 ))
            then
                i=0
                for partition in "${array[@]}"
                do
                    partition="${partition/[0-9]*/}"
                    xlist[i++]=$partition
                    xlist[i++]=""
                done
                unset -v i partition

                # Remove possible duplicate elements
                xlist=( $(printf '%s\n' "${xlist[@]}" | awk '!s[$0]++') )

                dialog --colors \
                 --backtitle "\\ZbBoot loader installation" \
                 --title "$_submenu_title" \
                 --menu \
"More than one disk or partition has been detected.\\n\\n\
Please select the boot loader destination:" 0 0 0 "${xlist[@]}" \
                 2> "${SUBTMPDIR}/return-MenuBootloader_cases" || continue;
                BOOT_DEVICE="$(cat -- "${SUBTMPDIR}"/return-MenuBootloader_cases)"
            else
                BOOT_DEVICE="${array[0]}"
            fi

            unset -v array xlist
        fi
        unset -v _submenu_title

        # To fallback if 'BOOT_DEVICE' is not defined, null
        BOOT_DEVICE="${BOOT_DEVICE:=$(cat -- "${SUBTMPDIR}"/root_device)}"

        # If the superblock was not chosen, we do not need
        # the device number to install on the MBR
        if test "$answer" != 1
        then
            BOOT_DEVICE="${BOOT_DEVICE/[0-9]*/}"
        fi
        unset -v answer

        # GRUB Installation

        dialog --clear
        echo "Boot loader installation on $BOOT_DEVICE ..."
        echo ""

        mkdir -p -- /media/dragora-root/boot/grub
        echo ""
        chroot /media/dragora-root /usr/sbin/grub-install --force $BOOT_DEVICE
        echo ""
        echo "Generating configuration file (as /boot/grub/grub.cfg) ..."
        echo ""
        chroot /media/dragora-root /usr/sbin/grub-mkconfig -o /boot/grub/grub.cfg
        sleep 5

        unset -v BOOT_DEVICE

        _default_button=cancel
        continue;
        ;;
    esac
done

