#!/bin/bash

# Tool...: /usr/sbin/update-grub
# Purpose: Install GRUB to the file system of supported Hardware Models.
# Date...: 28-Jun-2024
# Stuart Winter <MoZes@slackware.com>
#
# Maintenance notes:
# This command line should be kept in sync with the grub-install within
# slackwareaarch64-<ver>/source/installer/arm/hwm-configure/platform/aarch64/installer/helper.scr/000-grub-configure
# Within the Slackware Installer the script is:
# /usr/share/hwm-configure/platform/aarch64/installer/helper.scr/000-grub-configure

INSTPTH=/boot
INSTPTHEFI=$INSTPTH/efi
GRUBCFG=${INSTPTH}/grub/grub.cfg

# Don't run this from within the Slackware Installer, as the Installer has its own
# GRUB installation routine (see above):
[ -f /.installer-version ] && exit 0

echo "Hardware Model: $( slk-hwm-discover )"

# Todo:
# validate Hardware model support before updating.
# This enables us to automatically install the new GRUB boot loader when the a/grub
# package is upgraded.
# Doing this though really needs a shared library between the Slackware Installer and
# this script, to avoid duplicating the checking code.
# This needs to be updated:"
# /source/installer/arm/hwm-configure/platform/aarch64/installer/helper.scr/000-grub-configure
# and some shared checking code needs to go somewhere - maybe within the GRUB package?
# doinst.sh needs updating too.

# Sanity checks:
#[ ! -d "${INSTPTHEFI}" ] && {
#   printf "Error: ${INSTPTHEFI} does not exist\n"
mountpoint -q /boot/efi || {
   printf "Error: ${INSTPTHEFI} is not mounted.\n"
   printf "GRUB may not be required for this Hardware Model.\n"
   exit 1 ;}

[ ! -s "${GRUBCFG}" ] && {
  printf "Error: GRUB configuration file '${GRUBCFG}' is missing or empty\n"
  exit 1 ;}

echo "Installing GRUB to $INSTPTHEFI"
grub-install \
   -d /usr/lib64/grub/arm64-efi \
   --force \
   --removable \
   --no-floppy \
   --target=arm64-efi \
   --boot-directory=$INSTPTH \
   --efi-directory=$INSTPTHEFI
