# ==============================================================================
# ⛰️ MODULO ALPINE LINUX - INSTALL
# ==============================================================================

{{ define "install_distro_initramfs" }}
ROOT_FSTYPE=$(awk '$2 == "/" {print $3}' /etc/fstab)
if [ "$ROOT_FSTYPE" = "btrfs" ]; then
    if ! grep -q 'features=.*btrfs' /etc/mkinitfs/mkinitfs.conf; then
        sed -i '/^features=/ s/"$/ btrfs"/' /etc/mkinitfs/mkinitfs.conf
    fi
fi
KVER=$(uname -r)
[ -d "/lib/modules/$KVER" ] || KVER=$(ls -1 /lib/modules/ | head -n 1)
mkinitfs -o /boot/initramfs-$KVER $KVER
{{ end }}

{{ define "install_distro_bootloader" }}
if [ -d /sys/firmware/efi ]; then
    ARCH=$(uname -m)
    case "$ARCH" in
        x86_64)
            GRUB_TARGET="x86_64-efi"
            GRUB_BIN="grubx64.efi"
            BOOT_BIN="BOOTX64.EFI"
            ;;
        aarch64|arm64)
            GRUB_TARGET="arm64-efi"
            GRUB_BIN="grubaa64.efi"
            BOOT_BIN="BOOTAA64.EFI"
            ;;
        riscv64)
            GRUB_TARGET="riscv64-efi"
            GRUB_BIN="grubriscv64.efi"
            BOOT_BIN="BOOTRISCV64.EFI"
            ;;
        i386|i686)
            GRUB_TARGET="i386-efi"
            GRUB_BIN="grubia32.efi"
            BOOT_BIN="BOOTIA32.EFI"
            ;;
        *)
            GRUB_TARGET="x86_64-efi"
            GRUB_BIN="grubx64.efi"
            BOOT_BIN="BOOTX64.EFI"
            ;;
    esac

    if ! grub-install --target="$GRUB_TARGET" --efi-directory=/boot/efi --bootloader-id={{ .DistroID }} --recheck; then
        [ -f "/boot/efi/EFI/{{ .DistroID }}/$GRUB_BIN" ] || { echo "[FATAL ERROR] grub-install failed and no EFI binary was written"; exit 1; }
    fi

    # Removable fallback
    mkdir -p /boot/efi/EFI/BOOT
    [ -f "/boot/efi/EFI/{{ .DistroID }}/$GRUB_BIN" ] && cp -f "/boot/efi/EFI/{{ .DistroID }}/$GRUB_BIN" "/boot/efi/EFI/BOOT/$BOOT_BIN"
else
    TARGET_DISK=$(grub-probe -t disk / 2>/dev/null || echo "/dev/sda")
    grub-install --target=i386-pc --recheck "$TARGET_DISK"
fi
grub-mkconfig -o /boot/grub/grub.cfg
{{ end }}
