#!/usr/bin/bash
set -euo pipefail

target_root="${1:-}"

if [ -z "$target_root" ] || [ "$target_root" = "/" ]; then
    echo "Invalid Calamares target root: ${target_root:-empty}" >&2
    exit 1
fi

if [ ! -d "$target_root/boot/efi" ]; then
    echo "EFI system partition is not mounted at $target_root/boot/efi" >&2
    exit 1
fi

for mountpoint in dev proc sys run; do
    if ! mountpoint -q "$target_root/$mountpoint"; then
        mount --bind "/$mountpoint" "$target_root/$mountpoint"
    fi
done

if [ -d /sys/firmware/efi/efivars ] && [ -d "$target_root/sys/firmware/efi/efivars" ]; then
    mountpoint -q "$target_root/sys/firmware/efi/efivars" \
        || mount -t efivarfs efivarfs "$target_root/sys/firmware/efi/efivars" 2>/dev/null \
        || true
fi

mkdir -p "$target_root/boot/efi/EFI/Tuxenix" "$target_root/boot/efi/EFI/BOOT" "$target_root/boot/grub"

echo "Installing GRUB EFI loader without firmware NVRAM writes..."
chroot "$target_root" grub-install \
    --target=x86_64-efi \
    --efi-directory=/boot/efi \
    --bootloader-id=Tuxenix \
    --no-nvram \
    --force

echo "Installing removable EFI fallback loader..."
chroot "$target_root" grub-install \
    --target=x86_64-efi \
    --efi-directory=/boot/efi \
    --bootloader-id=Tuxenix \
    --removable \
    --no-nvram \
    --force

echo "Generating GRUB configuration..."
chroot "$target_root" grub-mkconfig -o /boot/grub/grub.cfg

echo "GRUB bootloader install complete."
