#!/bin/bash

# omarchy:summary=Guide through enabling, checking, or disabling UEFI Secure Boot
# omarchy:requires-sudo=true

set -euo pipefail

TEST_ROOT=""
if (( EUID != 0 )) && [[ -n ${OMARCHY_SECURE_BOOT_TEST_ROOT:-} ]]; then
  TEST_ROOT=${OMARCHY_SECURE_BOOT_TEST_ROOT%/}
fi

readonly BOOT_STORE="${TEST_ROOT}/var/lib/omarchy/boot"
readonly EFIVARS_DIR="${TEST_ROOT}/sys/firmware/efi/efivars"
readonly DMI_DIR="${TEST_ROOT}/sys/class/dmi/id"
readonly PARTUUID_DIR="${TEST_ROOT}/dev/disk/by-partuuid"
readonly PROC_BOOT_ID="${TEST_ROOT}/proc/sys/kernel/random/boot_id"
readonly EFI_GLOBAL_GUID="8be4df61-93ca-11d2-aa0d-00e098032b8c"

state_get() {
  [[ -f $BOOT_STORE/state ]] || return 0
  sed -n "s/^$1=//p" "$BOOT_STORE/state" | tail -1
}

efivar_bool() {
  local path="$EFIVARS_DIR/$1-$EFI_GLOBAL_GUID" val
  [[ -r $path ]] || return 0
  val=$(od -An -t u1 -j 4 -N 1 "$path" 2>/dev/null | tr -d '[:space:]') || return 0
  if [[ $val == "0" || $val == "1" ]]; then
    echo "$val"
  fi
}

is_asus() {
  local f
  for f in sys_vendor board_vendor; do
    if [[ -r $DMI_DIR/$f ]] && [[ $(<"$DMI_DIR/$f") == *[Aa][Ss][Uu][Ss]* ]]; then
      return 0
    fi
  done
  return 1
}

vendor_bios_guidance() {
  local f v
  for f in sys_vendor board_vendor; do
    [[ -r $DMI_DIR/$f ]] || continue
    v=$(<"$DMI_DIR/$f")
    case "${v,,}" in
      *dell*) printf '%s\n%s\n' "Dell: Boot Configuration > Secure Boot > Expert Key Management > Enable Custom Mode > Delete All Keys" "Keep Custom Mode enabled."; return 0 ;;
      *lenovo*) echo "Lenovo: Security > Secure Boot > Reset to Setup Mode (clear all keys, not just PK)"; return 0 ;;
      *asus*) printf '%s\n%s\n' "ASUS: Boot > Secure Boot > Key Management > Clear Secure Boot Keys" "If Secure Boot stays off after enabling, set OS Type to Windows UEFI Mode."; return 0 ;;
      *micro-star*|*msi*) echo "MSI: Settings > Security > Secure Boot > Secure Boot Mode: Custom > Key Management > Delete All Secure Boot Variables"; return 0 ;;
      *gigabyte*) echo "Gigabyte: Boot > Secure Boot > Secure Boot Mode: Custom > Key Management > Reset to Setup Mode"; return 0 ;;
      *asrock*) echo "ASRock: Security > Secure Boot > Secure Boot Mode: Custom > Key Management > Clear Secure Boot Keys"; return 0 ;;
      *hewlett*|hp|"hp "*) echo "HP: Security > Secure Boot Configuration > Clear Secure Boot Keys"; return 0 ;;
      *framework*) printf '%s\n%s\n' "Framework: Security > Secure Boot > Erase all Secure Boot Settings" "Keep Enforce Secure Boot enabled."; return 0 ;;
    esac
  done
  echo "UEFI: Secure Boot > Key Management > Clear all Secure Boot keys (Setup Mode)"
}

# A "Windows Boot Manager" firmware entry proves nothing by itself: boards keep a placeholder with no
# disk behind it, and entries outlive the drive they pointed to. Windows is here only when its boot
# manager sits on a partition that exists.
has_windows() {
  local uuid
  while read -r uuid; do
    if [[ -e $PARTUUID_DIR/${uuid,,} ]]; then
      return 0
    fi
  done < <(efibootmgr 2>/dev/null | grep -i 'bootmgfw\.efi' | grep -oiE 'HD\([0-9]+,GPT,[0-9a-f-]+' | cut -d, -f3)

  sudo test -f "$TEST_ROOT/efi/EFI/Microsoft/Boot/bootmgfw.efi" -o -f "$TEST_ROOT/boot/EFI/Microsoft/Boot/bootmgfw.efi" 2>/dev/null
}

boot_chain_ready() {
  [[ $1 == *"PASS  omarchy CA in db"* && $1 == *"PASS  ESP loader"* && $1 == *"PASS  ESP kernel"* ]]
}

ca_enrolled() {
  local out
  out=$(sudo omarchy-boot-secure status 2>/dev/null || true)
  [[ $out == *"PASS  omarchy CA in db"* ]]
}

has_sbctl_keys() {
  local keys_dir="" conf="${TEST_ROOT}/etc/sbctl/sbctl.conf"
  if [[ -f $conf ]]; then
    keys_dir=$(sudo sbctl --disable-landlock --json --config "$conf" setup --print-config 2>/dev/null | jq -r '.keydir // empty' 2>/dev/null || true)
    if [[ -n $keys_dir && -n $TEST_ROOT && $keys_dir != "$TEST_ROOT"* ]]; then
      keys_dir="${TEST_ROOT}${keys_dir}"
    fi
  elif sudo test -d "${TEST_ROOT}/usr/share/secureboot" 2>/dev/null; then
    keys_dir="${TEST_ROOT}/usr/share/secureboot/keys"
  fi
  keys_dir=${keys_dir:-"${TEST_ROOT}/var/lib/sbctl/keys"}
  sudo test -f "$keys_dir/PK/PK.key" -a -f "$keys_dir/KEK/KEK.key" 2>/dev/null
}

# Some firmware (HP, ASUS/AMI) keeps reporting Setup Mode until the next boot even though the platform
# key went in. Keys present while Setup Mode is still on can only mean this boot enrolled them.
is_awaiting_firmware_restart() {
  local pk="$EFIVARS_DIR/PK-$EFI_GLOBAL_GUID"
  [[ $(efivar_bool SetupMode) == "1" ]] && (( $(stat -c %s "$pk" 2>/dev/null || echo 0) > 4 ))
}

is_pending_reboot() {
  local current stored
  if is_awaiting_firmware_restart; then
    return 0
  fi
  [[ -r $PROC_BOOT_ID ]] || return 1
  current=$(<"$PROC_BOOT_ID")
  stored=$(sudo cat "$BOOT_STORE/.secure-boot-pending-reboot" 2>/dev/null || true)
  [[ -n $current && $stored == "$current" ]]
}

# Each reboot this setup asks for is a step in it, so it reopens by itself at the next login.
queue_resume() {
  omarchy-provision-next-boot add omarchy-setup-security-secure-boot-resume
}

restart_and_resume() {
  queue_resume
  omarchy-system "$1"
}

# Every path from here reads the firmware keys and boot files as root, so say why before sudo asks.
authenticate() {
  if ! sudo -n true 2>/dev/null; then
    printf '\033[1mSecure Boot\033[0m\nChecking firmware keys and boot files needs administrator rights.\n\n'
    sudo -v
    echo ""
  fi
}

confirm() {
  local rc=0
  gum confirm "$@" || rc=$?
  if (( rc == 130 )); then
    exit 130
  fi
  return "$rc"
}

choose() {
  local out rc=0
  out=$(gum choose "$@") || rc=$?
  if (( rc != 0 )); then
    exit "$rc"
  fi
  printf '%s\n' "$out"
}

warn_bitlocker() {
  gum style --border normal --border-foreground 3 --padding "0 2" --width 80 \
    "Windows detected — suspend BitLocker before changing Secure Boot keys" \
    "" \
    "1. Save your 48-digit BitLocker recovery key." \
    "2. In an elevated Windows PowerShell, run:" \
    "   manage-bde -protectors -disable C: -RebootCount 0"
  echo ""
}

require_bitlocker_ready() {
  (( $1 )) || return 0
  warn_bitlocker
  if ! confirm "BitLocker is suspended (or not used)?"; then
    exit 0
  fi
  echo ""
}

# Show all passing checks in a compact 2-column grid so the presentation
# window never clips the logo; when any check fails, show every failing line
# verbatim alongside the pass count.
print_status() {
  local line label passes=() fails=() half i
  while IFS= read -r line; do
    if [[ $line == "PASS  "* ]]; then
      label=${line:6:22}
      label=${label%"${label##*[![:space:]]}"}
      passes+=("$label")
    elif [[ $line == "FAIL  "* ]]; then
      fails+=("${line#FAIL}")
    fi
  done <<<"$1"

  if (( ${#fails[@]} == 0 )); then
    half=$(( (${#passes[@]} + 1) / 2 ))
    for (( i = 0; i < half; i++ )); do
      printf '  \033[32m✓\033[0m %-24s' "${passes[$i]}"
      if (( i + half < ${#passes[@]} )); then
        printf '  \033[32m✓\033[0m %s' "${passes[$((i + half))]}"
      fi
      printf '\n'
    done
  else
    for line in "${fails[@]}"; do
      printf '  \033[31m✗\033[0m%s\n' "$line"
    done
    local total=$(( ${#passes[@]} + ${#fails[@]} ))
    printf '\n%d of %d checks passed. Full details: sudo omarchy boot secure status\n' "${#passes[@]}" "$total"
  fi
}

handle_disable() {
  if [[ $(efivar_bool SecureBoot) == "1" ]]; then
    echo ""
    printf '\033[1mTurn off Secure Boot in UEFI first\033[0m\n\n'
    if has_windows; then
      echo "  1. Suspend BitLocker in Windows: manage-bde -protectors -disable C: -RebootCount 0"
      echo "  2. Set Secure Boot to Disabled in UEFI settings."
      echo "  3. Boot Armbian. This setup reopens to finish."
    else
      echo "  1. Set Secure Boot to Disabled in UEFI settings."
      echo "  2. Boot Armbian. This setup reopens to finish."
    fi
    echo ""
    if confirm "Reboot into UEFI settings now?"; then
      restart_and_resume firmware
    fi
    return 0
  fi

  echo ""
  local win=0
  if has_windows; then
    win=1
    warn_bitlocker
  fi
  if confirm "Turn off Omarchy Secure Boot?"; then
    sudo omarchy-boot-secure disable --yes
    printf '\n\033[1;32mSecure Boot is off\033[0m\n'
    if (( win )); then
      echo "If you restore factory keys in UEFI, boot Windows and run: manage-bde -protectors -enable C:"
    fi
  fi
}

handle_configured() {
  local status_out="" status_rc=0 sb choice
  status_out=$(sudo omarchy-boot-secure status 2>&1) || status_rc=$?
  if (( status_rc != 0 )) && [[ $status_out != *"PASS  "* && $status_out != *"FAIL  "* ]]; then
    printf '%s\n' "$status_out" >&2
    exit "$status_rc"
  fi

  sb=$(efivar_bool SecureBoot)
  if (( status_rc == 0 )); then
    printf '\033[1;32mSecure Boot is active\033[0m\nReady for Easy Anti-Cheat and Fortnite.\n\n'
    print_status "$status_out"
    echo ""
    choice=$(choose --header "" "Done" "Turn off Secure Boot")
  elif [[ $sb == "0" ]] && boot_chain_ready "$status_out" && is_pending_reboot; then
    printf '\033[1;33mReboot to activate Secure Boot\033[0m\nKeys are enrolled and boot entries are ready.\n'
    if is_asus; then
      echo "On ASUS boards, if Secure Boot stays off after reboot, set OS Type to Windows UEFI Mode."
    fi
    echo ""
    if confirm "Reboot now?"; then
      restart_and_resume reboot
    fi
    return 0
  elif [[ $sb == "0" ]] && boot_chain_ready "$status_out"; then
    printf '\033[1;33mKeys are enrolled — turn Secure Boot on in UEFI settings\033[0m\n'
    if is_asus; then
      echo "On ASUS boards, set OS Type to Windows UEFI Mode."
    else
      echo "Open UEFI settings and set Secure Boot to Enabled."
    fi
    echo ""
    print_status "$status_out"
    echo ""
    choice=$(choose --header "" "Reboot into UEFI settings" "Turn off Secure Boot" "Done")
  else
    printf '\033[1;33mSecure Boot needs attention\033[0m\nFix the failing checks below before playing.\n\n'
    print_status "$status_out"
    echo ""
    choice=$(choose --header "" "Done" "Turn off Secure Boot")
  fi

  case "$choice" in
    "Reboot into UEFI settings")
      local win=0
      if has_windows; then
        win=1
      fi
      echo ""
      require_bitlocker_ready "$win"
      restart_and_resume firmware
      ;;
    "Turn off Secure Boot") handle_disable ;;
    "Done") ;;
  esac
}

# omarchy-boot-secure reads Setup Mode back after enrolling and fails when it is still on. On firmware
# that only leaves Setup Mode at the next boot (HP, ASUS), everything is in place by then, so a
# complete boot chain turns that failure into the ordinary reboot prompt.
enable_secure_boot() {
  local err rc=0
  err=$(mktemp)
  sudo omarchy-boot-secure enable --yes 2>"$err" || rc=$?

  if (( rc != 0 )) && is_awaiting_firmware_restart &&
    boot_chain_ready "$(sudo omarchy-boot-secure status 2>/dev/null || true)"; then
    grep -v "still in Setup Mode" "$err" >&2 || true
    rc=0
  else
    cat "$err" >&2
  fi

  rm -f "$err"
  if (( rc != 0 )); then
    exit "$rc"
  fi
}

handle_setup() {
  if ! sudo omarchy-boot-secure --check; then
    exit 1
  fi

  local win=0 setup_mode ready_reason=""
  if has_windows; then
    win=1
  fi
  setup_mode=$(efivar_bool SetupMode)

  if [[ $setup_mode == "1" ]]; then
    ready_reason="UEFI Setup Mode is active."
  elif ca_enrolled; then
    ready_reason="Omarchy's Root CA is already enrolled in firmware."
  elif has_sbctl_keys; then
    ready_reason="Existing sbctl keys found — Omarchy appends its Root CA without replacing your keys."
  fi

  if [[ -z $ready_reason ]]; then
    printf '\033[1mEnter UEFI Setup Mode\033[0m\nClear Secure Boot keys in firmware so Armbian can enroll its Root CA.\n\n'
    require_bitlocker_ready "$win"
    gum style --border normal --padding "0 2" --width 80 "$(vendor_bios_guidance)"
    printf '\nKeep TPM 2.0 and IOMMU enabled. Do not choose Restore Factory Keys.\n'
    printf 'After saving and rebooting, this setup reopens to continue.\n\n'
    if confirm "Reboot into UEFI settings now?"; then
      restart_and_resume firmware
    fi
    return 0
  fi

  printf '\033[1mReady to enable Secure Boot\033[0m\n%s\n\n' "$ready_reason"
  require_bitlocker_ready "$win"
  echo "  • Enrolls Armbian's Root CA alongside Microsoft keys (reversible anytime)."
  echo "  • Switches boot entries to signed kernel and systemd-boot binaries."
  echo "  • Hibernation and pre-Secure-Boot snapshots are unavailable while active."
  echo ""
  if ! confirm "Enable Secure Boot now?"; then
    exit 0
  fi

  echo ""
  enable_secure_boot
  printf '\n\033[1;32mSecure Boot is configured\033[0m\n'
  echo "Reboot to activate Secure Boot. This setup reopens afterwards to verify."
  if is_asus; then
    echo "On ASUS boards, if Secure Boot stays off after reboot, set OS Type to Windows UEFI Mode."
  fi
  if (( win )); then
    echo "To re-enable BitLocker, boot Windows directly and run: manage-bde -protectors -enable C:"
  fi
  echo ""
  if confirm "Reboot now?"; then
    restart_and_resume reboot
  fi
}

# Secure Boot needs systemd-boot, so a Limine machine moves to it first. The move can't be undone.
switch_to_systemd_boot() {
  printf '\033[1mStep 1 of 3 — Prepare the boot loader\033[0m\n'
  echo "Secure Boot needs systemd-boot in place of Limine. This change can't be undone."
  echo ""
  echo "  • Snapshots taken before the switch finishes are deleted."
  echo "  • Other systems in the boot menu may leave it (the check below names them)."
  echo "    Make sure your computer's own boot menu can start them first."
  echo "  • Your UEFI settings must let you clear the Secure Boot keys. Some laptops,"
  echo "    like many Razer Blades, can't, and can't use Secure Boot yet."
  echo "  • Two reboots finish it. If the first doesn't come up, a reset brings back Limine."
  echo ""

  if ! omarchy-boot-switch --check; then
    exit 1
  fi
  echo ""
  if ! confirm "Make this change? It can't be undone."; then
    exit 0
  fi

  # The switch queues this setup to reopen.
  omarchy-boot-switch --yes
  echo "This setup reopens after the reboot to continue."
  echo ""
  if confirm "Reboot now?"; then
    omarchy-system reboot
  fi
}

# omarchy-boot-confirm moves the switch along once each boot is up, and its
# last step installs packages and rebuilds the boot images. A reboot offered
# before it is done would cut that short.
boot_confirm_pending() {
  [[ $(systemctl show -p ActiveState --value omarchy-boot-confirm.service 2>/dev/null) == "activating" ]] ||
    [[ -n $(systemctl list-jobs --no-legend omarchy-boot-confirm.service 2>/dev/null) ]]
}

offer_reboot() {
  echo "This setup reopens afterwards."
  echo ""
  queue_resume
  if confirm "Reboot now?"; then
    omarchy-system reboot
  fi
  exit 0
}

# The switch reports here, in the terminal that reopens after each of its
# reboots, from what omarchy-boot-switch confirm left in the boot store.
if boot_confirm_pending; then
  echo "Finishing the boot loader switch. Don't restart until it's done..."
  while boot_confirm_pending; do sleep 1; done
  echo ""
fi

case $(state_get phase) in
trial)
  printf '\033[1mBootloader switch in progress\033[0m\n\n'
  echo "Reboot to start the systemd-boot trial."
  offer_reboot
  ;;
trial-failed)
  printf '\033[1mThe switch to systemd-boot did not take\033[0m\n\n'
  if [[ $(state_get notice_key) == "firmwareKeptLimine" ]]; then
    echo "This machine's firmware ignored the new boot order, so Armbian stays on Limine."
    echo "Run omarchy-boot-switch revert to clean up."
    exit 1
  fi
  echo "The systemd-boot trial didn't come up. This boot came from Limine, which keeps working."
  echo "Try again below, or run omarchy-boot-switch revert to clean up."
  echo ""
  ;;
promoted)
  if [[ $(state_get trial_boot_id) == "$(cat "$PROC_BOOT_ID" 2>/dev/null)" ]]; then
    printf '\033[1mOmarchy started with systemd-boot\033[0m\n\n'
    echo "Reboot once more to finish the switch. Limine stays as the fallback until then."
    offer_reboot
  fi

  # Only what this boot's finish said: an earlier boot's reason, or its call
  # for a reboot, no longer holds.
  finish_notice=""
  if [[ $(state_get notice_boot) == "$(cat "$PROC_BOOT_ID" 2>/dev/null)" ]]; then
    finish_notice=$(state_get notice_key)
  fi

  printf '\033[1mFinishing the switch to systemd-boot failed\033[0m\n\n'
  case $finish_notice in
  finishInterrupted)
    echo "This boot came from Limine, which the switch had begun removing."
    echo "systemd-boot is first again: reboot to finish."
    offer_reboot
    ;;
  finishNoPackage) echo "The omarchy-boot-systemd package wasn't in the boot store." ;;
  finishInstallFailed)
    echo "Installing omarchy-boot-systemd failed. See journalctl -u omarchy-boot-confirm."
    if [[ -e $TEST_ROOT/var/lib/pacman/db.lck ]]; then
      echo "pacman's lock is in the way, as a finish cut short by a power loss leaves it."
      echo "If no package manager is running, remove it first: sudo rm /var/lib/pacman/db.lck"
    fi
    ;;
  finishNoRecoveryEntry) echo "The recovery snapshot $(state_get notice_arg) has no boot entry." ;;
  *) echo "This boot didn't finish it. See journalctl -u omarchy-boot-confirm." ;;
  esac
  echo "systemd-boot keeps starting this machine. There is no need to reboot."
  echo ""
  if confirm "Try finishing again now?"; then
    # --apply fetches the package again if it went missing.
    sudo omarchy-boot-switch --apply
    sudo systemctl restart omarchy-boot-confirm.service || true
    exec "$0"
  fi
  # Until the finish is through, every login says where it stands.
  queue_resume
  exit 1
  ;;
active)
  # Said once, at the login after the boot that finished the switch.
  notice_seen=${XDG_STATE_HOME:-$HOME/.local/state}/omarchy/boot-switch-seen
  if [[ $(state_get notice_key) == "switched" && ! -e $notice_seen ]]; then
    printf '\033[1mOmarchy now boots with systemd-boot\033[0m\n'
    printf 'Snapshots are in the boot menu (hold Space while starting) and under System > Snapshots.\n\n'
    mkdir -p "$(dirname "$notice_seen")"
    touch "$notice_seen"
  fi
  ;;
esac

if [[ $(omarchy-boot-backend) != "systemd-boot" ]]; then
  switch_to_systemd_boot
  exit 0
fi

authenticate

if [[ $(state_get secure_boot) == "enabled" ]]; then
  handle_configured
else
  handle_setup
fi
