#!/bin/bash
set -Eeuo pipefail

SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
# shellcheck source=common.sh
source "$SCRIPT_DIR/common.sh"

parse_arguments "$@"
[[ -n "$ROOT_PARTITION" ]] || fail "System partition was not provided."
[[ -n "$EFI_PARTITION" ]] || fail "EFI partition was not provided."
[[ "$RESTORE_MODE" =~ ^[123]$ ]] || fail "Invalid restore mode: $RESTORE_MODE"

trap 'cleanup_mount_tree' EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
show_progress "Preparing mount points"
mount_filesystems
verify_selected_root
repair_root_fstab
repair_mkinitcpio_config

case "$RESTORE_MODE" in
    2) repair_arch_packages 0 ;;
    3) repair_arch_packages 1 ;;
esac
detect_grub_commands

install_args=(
    "$GRUB_INSTALL_COMMAND"
    --target=x86_64-efi
    "--efi-directory=$EFI_MOUNT_PATH"
    "--bootloader-id=$BOOTLOADER_ID"
    --recheck
)
if [[ ! -d /sys/firmware/efi ]]; then
    install_args+=(--no-nvram)
    log_message "EFI variables unavailable; installing boot files without changing NVRAM"
fi
chroot_run "Installing GRUB for EFI" "${install_args[@]}"
refresh_boot_files
validate_boot_files

show_progress "Finishing the restore"
sync
cleanup_mount_tree || fail "GRUB was restored, but a filesystem could not be unmounted."
trap - EXIT
log_message "EFI GRUB restore completed successfully"
printf 'EVENT:SUCCESS:Restore operation completed.\n'
