#!/bin/bash

## Copyright (C) 2026 - 2026 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

set -o errexit
set -o nounset
set -o pipefail
set -o errtrace
shopt -s inherit_errexit
shopt -s shift_verbose
export LC_ALL=C

# shellcheck source=../../../../helper-scripts/usr/libexec/helper-scripts/package_installed_check.sh
source /usr/libexec/helper-scripts/package_installed_check.sh

## Debugging.
mkdir --parents -- /var/log/live-config-dist
exec > >(tee --append -- /var/log/live-config-dist/grub-fallback-install.log) 2>&1
debug_err_trap() {
   local rc=$?
   printf '%s\n' "$0: DEBUG: FAILED rc=${rc} at line ${BASH_LINENO[0]}"
}
trap debug_err_trap ERR
printf '%s\n' "$0: DEBUG: id: '$(id)' TMPDIR='${TMPDIR:-<unset>}'"
if [ -n "${TMPDIR:-}" ]; then
   printf '%s\n' "$0: DEBUG: TMPDIR exists: $(test -d "${TMPDIR}" && printf '%s' true || printf '%s' false)"
fi
printf '%s\n' "$0: DEBUG: grub-pc debconf:"
debconf-show grub-pc 2>&1 || true

system_arch="$(dpkg --print-architecture)"

grub_pc_dpkg_query_output="$(dpkg-query --show --showformat='${Status}' "grub-pc" 2>&1)" || true
grub_efi_dpkg_query_output="$(dpkg-query --show --showformat='${Status}' "grub-efi-${system_arch}" 2>&1)" || true

printf '%s\n' "$0: DEBUG: system_arch: '${system_arch}'"
printf '%s\n' "$0: DEBUG: grub-pc grub_pc_dpkg_query_output: '${grub_pc_dpkg_query_output}'"
printf '%s\n' "$0: DEBUG: grub-efi-${system_arch} grub_efi_dpkg_query_output: '${grub_efi_dpkg_query_output}'"

if pkg_installed "grub-efi-${system_arch}"; then
   printf '%s\n' "$0: DEBUG: branch taken: grub-efi-${system_arch}"
   printf '%s\n' "grub-efi-${system_arch} grub2/force_efi_extra_removable boolean true" | debconf-set-selections
   reconfigure_rc=0
   reconfigure_output="$(dpkg-reconfigure-noninteractive "grub-efi-${system_arch}" 2>&1)" || reconfigure_rc=$?
   printf '%s\n' "${reconfigure_output}"
   if [ "${reconfigure_rc}" -ne 0 ]; then
      printf '%s\n' "$0: ERROR: dpkg-reconfigure grub-efi-${system_arch} exited ${reconfigure_rc}" >&2
      exit "${reconfigure_rc}"
   fi

   ## grub-efi's postinst emits a warning when GRUB installaiont fails, but we
   ## want to treat this as fatal.
   case "${reconfigure_output}" in
      *"Failed: grub-install"*)
         printf '%s\n' "$0: ERROR: grub-install failed inside the grub-efi-${system_arch} postinst!" >&2
         exit 1
         ;;
   esac
fi
printf '%s\n' "$0: DEBUG: End of script."
