#!/bin/sh

set -eu

# We preseed grub-installer/update-nvram to disable creation of
# EFI boot entries by grub and instead do it ourselves here.
#
# The main reason why we do this is that with the grub-created boot entry,
# Dell Latitude 7480 laptops no longer boot Debian from internal disk after
# having booted from USB stick. This apparently happens because, when a bootable
# USB stick is inserted, the firmware can no longer find the debian EFI file
# (it's probably looking at the wrong EFI partition, the one on the USB stick),
# and then enters boot option recovery, which finds the BOOTx64.EFI on the USB
# stick, and then creates a boot entry for that and sets the bootorder to just
# that new entry. After that, the debian boot entry is no longer in the
# bootorder, so booting fails after removing the USB stick.
# Additionally, it is convenient if laptops boot from USB stick automatically,
# without needing to enter the boot menu.
#
# To solve these problems, we create a boot entry for USB sticks, which is tried
# first, and one for Debian on the internal disk.
# We create path-only boot entries, which apparently work more reliably than
# entries which also specify the disk.
# We use hardcoded entry numbers to avoid needing to find available numbers and
# clean up old entries.

# Try mounting efivarfs
mountvirtfs () {
	fstype="$1"
	path="$2"
	mkdir -p "$path"
	if mount -t "$fstype" "$fstype" "$path"; then
		trap "umount $path" HUP INT QUIT KILL PIPE TERM EXIT
	fi
}
mountvirtfs efivarfs /sys/firmware/efi/efivars

# Check if EFI boot is available
if efibootmgr --quiet; then
  efibootmgr --delete-bootorder || true
  efibootmgr --bootnum 0150 --delete-bootnum || true
  efibootmgr --bootnum 0151 --delete-bootnum || true

  # efibootmgr --create-only --bootnum 0150 --label "Removable media" --file-dev-path --loader '\EFI\BOOT\BOOTx64.EFI'
  # efibootmgr --create-only --bootnum 0151 --label "Debian" --file-dev-path --loader '\EFI\debian\shimx64.efi'

  # The version of efibootmgr in bookworm does not support the --file-dev-path
  # argument, so here are commands that directly write to efivarfs.
  # When upgrading from bookworm to trixie, remove the commands below and
  # uncomment the commands above.
  echo "BwAAAAEAAAA0AFIAZQBtAG8AdgBhAGIAbABlACAAbQBlAGQAaQBhAAAABAQwAFwARQBGAEkAXABCAE8ATwBUAFwAQgBPAE8AVAB4ADYANAAuAEUARgBJAAAAf/8EAA==" | \
    base64 --decode - > /sys/firmware/efi/efivars/Boot0150-8be4df61-93ca-11d2-aa0d-00e098032b8c
  echo "BwAAAAEAAAA4AEQAZQBiAGkAYQBuAAAABAQ0AFwARQBGAEkAXABkAGUAYgBpAGEAbgBcAHMAaABpAG0AeAA2ADQALgBlAGYAaQAAAH//BAA=" | \
    base64 --decode - > /sys/firmware/efi/efivars/Boot0151-8be4df61-93ca-11d2-aa0d-00e098032b8c

  efibootmgr --bootorder 0150,0151
fi

# Set up apt lists.
cp -rT /usr/local/share/target-sources /etc/apt/sources.list.d
rm /etc/apt/sources.list

# Create user.
/usr/local/bin/reset-user