#!/bin/bash

#
# Update the kernel in an EFI Boot Stub setup on Slackware-current
#
# General design:
#   A multi-kernel setup (A/B) allowing for a kernel upgrade with fallback to 
#   the previous working kernel and initrd.
#
#   Relies on EFI Boot Stub support in Linux kernel (CONFIG_EFI_STUB).
#
#   Requires a UEFI system.  Grub, elilo, and others are not required. 
#
# Process:
#   Use upgradepkg to upgrade the installed package before running this script.
# 
#   This script will copy the newly installed kernel to the correct location on the ESP,
#   generate a new initrd image on the ESP for use with the new kernel.  
#
#   Set the next boot to use the new kernel.
#
# 2025-05-03 Tom Canich <tom@canich.net>
#

# ESP mount point 
# default: /boot/efi
ESP=${ESP:-/boot/efi}

# Location of EFI Boot images
# default /boot/efi/EFI/Linux
IMGDIR=${IMGDIR:-$ESP/EFI/Linux}

# Current EFI Boot Order
BOOTORDER=$(efibootmgr | egrep '^BootOrder' | cut -d: -f2 | sed -e 's/^ //')

# Current and next kernel EFI image
BOOTCURRENT=$(efibootmgr | egrep '^BootCurrent' | cut -d: -f2 | sed -e 's/^ //')
#BOOTNEXT=$(efibootmgr | egrep '^BootNext' | cut -d: -f2)

# New kernel version from package repository or environment
NEWKERNEL=${NEWKERNEL:-$(ls -1 /var/log/packages/kernel-generic-* | cut -d- -f3 | tail -n 1)}

# Current and next image label (A/B)
IMGCURRENT=$(efibootmgr | \
    egrep "^$(echo Boot${BOOTCURRENT} | \
    tr -d '[:blank:]')" | \
    cut -d\  -f3 | \
    cut -c1)
IMGNEXT=$(efibootmgr | \
    egrep -v "^$(echo Boot${BOOTCURRENT} | \
    tr -d '[:blank:]')" | \
    grep 'Linux ' | \
    cut -d\  -f3 | \
    cut -c1)
BOOTNEXT=$(efibootmgr | \
    egrep -v "^$(echo Boot${BOOTCURRENT} | \
    tr -d '[:blank:]')" | \
    grep 'Linux ' | \
    cut -c5-8)

MKINITRD_EXTRA="-o $IMGDIR/initrd-generic-$IMGNEXT.img -l dvorak"

MKINITRD=$(/usr/share/mkinitrd/mkinitrd_command_generator.sh -r -k $NEWKERNEL -a "$MKINITRD_EXTRA")

if [ -d $IMGDIR ]
then
  cp /boot/vmlinuz-generic $IMGDIR/vmlinuz-generic-$IMGNEXT.efi
  rc_cp=$?
  eval $MKINITRD
  rc_mkinitrd=$?
#  rc_mkinitrd=0
else
  echo "Error: $IMGDIR doesn't exist."
  exit 5
fi

if [ $rc_cp ] && [ $rc_mkinitrd ]
then
  echo "Setting Boot${BOOTNEXT} (Linux $IMGNEXT) as next target..."
  efibootmgr -q -n $BOOTNEXT
  rc_next=$?
  echo "Updating boot order: ${BOOTNEXT},${BOOTCURRENT}"
  efibootmgr -q -o ${BOOTNEXT},${BOOTCURRENT},${BOOTORDER}
  if [ $rc_next ] && [ $rc_order ] 
  then 
    echo "Done"
  fi
else
  echo "Failed to copy kernel or generate initrd.  Not updating EFI Boot Order"
fi

exit 0




