#!/bin/bash

# omarchy:summary=Add or remove an EFI boot entry for the Omarchy UKI, allowing the system to boot directly
# omarchy:requires-sudo=true

# Apple Silicon boots m1n1, then U-Boot, which finds the bootloader on its own
# and creates its boot entries itself, so there is no direct-boot entry to add
# or remove.
if omarchy-hw-aarch64-apple; then
  echo "Error: Direct boot is not supported on Apple Silicon: U-Boot finds the bootloader itself" >&2
  exit 1
fi

if [[ ! -d /sys/firmware/efi ]]; then
  echo "Error: System is not booted in UEFI mode" >&2
  exit 1
fi

if ! efibootmgr &>/dev/null; then
  echo "Error: efibootmgr is not available or not functional" >&2
  exit 1
fi

bios_vendor=$(cat /sys/class/dmi/id/bios_vendor 2>/dev/null)

case "${bios_vendor,,}" in
  *"american megatrends"*)
    echo "Error: American Megatrends firmware may not safely support custom EFI entries" >&2
    exit 1
    ;;
  *apple*)
    echo "Error: Apple firmware uses its own boot manager" >&2
    exit 1
    ;;
esac

boot_num=$(omarchy-boot-direct --number | head -1)

if [[ -n $boot_num ]]; then
  if gum confirm --affirmative "$(omarchy-i18n common.yes)" --negative "$(omarchy-i18n common.no)" "$(omarchy-i18n directBoot.disable)"; then
    echo "Removing EFI boot entry $boot_num"
    sudo efibootmgr --bootnum "$boot_num" --delete-bootnum >/dev/null
  fi

  exit 0
else
  # bootctl resolves the ESP even when Fedora mounts it below a separate /boot.
  esp_path=$(bootctl --print-esp-path) || exit 1
  uki_file=$(sudo find "$esp_path/EFI/Linux/" -name "omarchy*.efi" -printf "%f\n" 2>/dev/null | head -1)

  if [[ -z $uki_file ]]; then
    echo "Error: No Omarchy UKI found in $esp_path/EFI/Linux/" >&2
    exit 1
  fi

  boot_source=$(findmnt -n -o SOURCE "$esp_path")
  disk=$(echo "$boot_source" | sed 's/p\?[0-9]*$//')
  part=$(echo "$boot_source" | grep -o 'p\?[0-9]*$' | sed 's/^p//')

  if gum confirm --affirmative "$(omarchy-i18n common.yes)" --negative "$(omarchy-i18n common.no)" "$(omarchy-i18n directBoot.setup)"; then
    echo "Creating EFI boot entry for $uki_file"

    sudo efibootmgr --create \
      --disk "$disk" \
      --part "$part" \
      --label "Omarchy" \
      --loader "\\EFI\\Linux\\$uki_file"
  fi
fi
