# ==============================================================================
# 🦎 MODULO OPENSUSE SLOWROLL - INSTALL (Principle of Transparency)
# ==============================================================================

{{ define "install_distro_initramfs" }}
dracut -f --regenerate-all
{{ end }}

{{ define "install_distro_bootloader" }}
# Disabilita SELinux per evitare errori di permessi all'avvio (Permission denied su bash/sh)
if [ -f /etc/selinux/config ]; then
      sed -i 's/^SELINUX=.*/SELINUX=disabled/g' /etc/selinux/config
fi

if [ -f /etc/default/grub ]; then
      if ! grep -q "selinux=0" /etc/default/grub; then
            sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/GRUB_CMDLINE_LINUX_DEFAULT="selinux=0 /g' /etc/default/grub
      fi
      if grep -q "^GRUB_DISABLE_OS_PROBER=" /etc/default/grub; then
            sed -i 's/^GRUB_DISABLE_OS_PROBER=.*/GRUB_DISABLE_OS_PROBER=false/' /etc/default/grub
      else
            echo "GRUB_DISABLE_OS_PROBER=false" >> /etc/default/grub
      fi
fi

# Rilevamento automatico basato su configurazioni attive (Evidence-Based Detection)
if [ -f /boot/limine.conf ] || [ -f /boot/efi/limine.conf ] || [ -f /boot/limine/limine.conf ] || [ -f /boot/efi/limine/limine.conf ] || [ -f /etc/limine-entry-tool.conf ] || [ -f /etc/default/limine ]; then
    echo "-> Evidence found: Limine configuration detected."
    {{ include "install_distro_limine" . }}
elif [ -f /boot/loader/loader.conf ] || [ -f /boot/efi/loader/loader.conf ]; then
    echo "-> Evidence found: systemd-boot configuration detected."
    {{ include "install_distro_systemd_boot" . }}
else
    echo "-> Evidence found: GRUB configuration detected."
    {{ include "install_distro_grub" . }}
fi
{{ end }}

{{ define "install_distro_grub" }}
# Rileva Btrfs e crea il symlink di boot al livello root del filesystem
if [ "$(findmnt -n -o FSTYPE /)" = "btrfs" ]; then
      echo "-> Configurazione Btrfs rilevata. Creazione del symlink /boot al livello root..."
      ROOT_DEV=$(findmnt -n -o SOURCE /)
      mkdir -p /tmp/btrfs-raw
      mount "$ROOT_DEV" /tmp/btrfs-raw
      ln -sf @/boot /tmp/btrfs-raw/boot
      umount /tmp/btrfs-raw
      rmdir /tmp/btrfs-raw
fi

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

      grub2-install --target="$GRUB_TARGET" --efi-directory=/boot/efi --bootloader-id={{ .DistroID }} --recheck --force
      
      # Fallback UEFI Absolute (Garantisce l'avvio anche se la NVRAM fa i capricci)
      mkdir -p /boot/efi/EFI/BOOT
      if [ -f "/boot/efi/EFI/{{ .DistroID }}/shim.efi" ]; then
          cp "/boot/efi/EFI/{{ .DistroID }}/shim.efi" "/boot/efi/EFI/BOOT/$BOOT_BIN"
          if [ -f "/boot/efi/EFI/{{ .DistroID }}/$GRUB_BIN" ]; then
              cp "/boot/efi/EFI/{{ .DistroID }}/$GRUB_BIN" "/boot/efi/EFI/BOOT/$GRUB_BIN"
          elif [ -f "/boot/efi/EFI/{{ .DistroID }}/grub.efi" ]; then
              cp "/boot/efi/EFI/{{ .DistroID }}/grub.efi" "/boot/efi/EFI/BOOT/$GRUB_BIN"
          fi
      else
          if [ -f "/boot/efi/EFI/{{ .DistroID }}/$GRUB_BIN" ]; then
              cp "/boot/efi/EFI/{{ .DistroID }}/$GRUB_BIN" "/boot/efi/EFI/BOOT/$BOOT_BIN"
          elif [ -f "/boot/efi/EFI/{{ .DistroID }}/grub.efi" ]; then
              cp "/boot/efi/EFI/{{ .DistroID }}/grub.efi" "/boot/efi/EFI/BOOT/$BOOT_BIN"
          fi
      fi

      grub2-mkconfig -o /boot/grub2/grub.cfg
      mkdir -p "/boot/efi/EFI/{{ .DistroID }}"
      grub2-mkconfig -o "/boot/efi/EFI/{{ .DistroID }}/grub.cfg"
else
      TARGET_DISK=$(grub2-probe -t disk / 2>/dev/null || echo "/dev/sda")
      grub2-install --target=i386-pc --recheck "$TARGET_DISK"
      grub2-mkconfig -o /boot/grub2/grub.cfg
fi
{{ end }}

{{ define "install_distro_systemd_boot" }}
echo "-> Installazione di systemd-boot (bootctl) su openSUSE..."
bootctl install --esp-path=/boot/efi

mkdir -p /boot/efi/loader/entries

KERNEL_FILE=$(ls -1 /boot/vmlinuz-* 2>/dev/null | grep -v rescue | head -n 1 | xargs basename)
INITRD_FILE=$(ls -1 /boot/initramfs-* /boot/initrd-* 2>/dev/null | grep -v rescue | grep -v oa-initrd | head -n 1 | xargs basename)

cp -L /boot/$KERNEL_FILE /boot/efi/
cp -L /boot/$INITRD_FILE /boot/efi/

ROOT_PART=$(awk '$2 == "/" && $1 !~ /^#/ {print $1}' /etc/fstab)
if [ -z "$ROOT_PART" ]; then
    ROOT_PART=$(df / | awk 'NR==2 {print $1}')
fi
ROOT_FSTYPE=$(awk '$2 == "/" {print $3}' /etc/fstab)
ROOTFLAGS=""
if [ "$ROOT_FSTYPE" = "btrfs" ]; then
    ROOTFLAGS="rootflags=subvol=@"
fi

PRETTY_NAME=$(grep ^PRETTY_NAME= /etc/os-release | cut -d= -f2 | tr -d '"')
if [ -z "$PRETTY_NAME" ]; then
    PRETTY_NAME="openSUSE"
fi

cat <<EOF > /boot/efi/loader/entries/{{ .DistroID }}.conf
title   $PRETTY_NAME
linux   /$KERNEL_FILE
initrd  /$INITRD_FILE
options root=$ROOT_PART rw $ROOTFLAGS
EOF

if [ ! -f /boot/efi/loader/loader.conf ]; then
cat <<EOF > /boot/efi/loader/loader.conf
default {{ .DistroID }}.conf
timeout 5
console-mode max
editor yes
EOF
fi
{{ end }}

{{ define "install_distro_limine" }}
echo "-> Installazione di Limine bootloader su openSUSE..."
if [ -d /sys/firmware/efi ]; then
    # UEFI
    mkdir -p /boot/efi/EFI/BOOT /boot/efi/EFI/limine
    cp /usr/share/limine/BOOTX64.EFI /boot/efi/EFI/BOOT/ 2>/dev/null || true
    cp /usr/share/limine/BOOTX64.EFI /boot/efi/EFI/limine/ 2>/dev/null || true
    if command -v efibootmgr &>/dev/null; then
        ESP_DEV=$(df /boot/efi | awk 'NR==2 {print $1}')
        if [ -n "$ESP_DEV" ]; then
            DISK=$(echo "$ESP_DEV" | sed -E 's/p?[0-9]+$//')
            PARTNUM=$(echo "$ESP_DEV" | grep -o '[0-9]*$')
            if [ -n "$DISK" ] && [ -n "$PARTNUM" ]; then
                echo "-> Registering Limine entry in UEFI NVRAM via efibootmgr..."
                efibootmgr -c -d "$DISK" -p "$PARTNUM" -l '\EFI\limine\BOOTX64.EFI' -L "Limine" -u || true
            fi
        fi
    fi
    
    KERNEL_PATH=$(ls -1 /boot/vmlinuz-* 2>/dev/null | grep -v rescue | head -n 1)
    INITRD_PATH=$(ls -1 /boot/initramfs-* /boot/initrd-* 2>/dev/null | grep -v rescue | grep -v oa-initrd | head -n 1)
    KERNEL_FILE=$(basename "$KERNEL_PATH")
    INITRD_FILE=$(basename "$INITRD_PATH")

    cp "$KERNEL_PATH" "/boot/efi/$KERNEL_FILE" 2>/dev/null || true
    cp "$INITRD_PATH" "/boot/efi/$INITRD_FILE" 2>/dev/null || true

    ROOT_PART=$(awk '$2 == "/" && $1 !~ /^#/ {print $1}' /etc/fstab)
    if [ -z "$ROOT_PART" ]; then
        ROOT_PART=$(df / | awk 'NR==2 {print $1}')
    fi
    ROOT_FSTYPE=$(awk '$2 == "/" {print $3}' /etc/fstab)
    ROOTFLAGS=""
    if [ "$ROOT_FSTYPE" = "btrfs" ]; then
        ROOTFLAGS="rootflags=subvol=@"
    fi
    
    PRETTY_NAME=$(grep ^PRETTY_NAME= /etc/os-release | cut -d= -f2 | tr -d '"')
    if [ -z "$PRETTY_NAME" ]; then
        PRETTY_NAME="openSUSE"
    fi

    SPLASH_IMG=""
    for candidate in \
        /usr/share/wallpapers/cachyos-wallpapers/limine-splash.png \
        /usr/share/wallpapers/cachyos-wallpapers/splash.png \
        /etc/penguins-eggs.d/brain.d/assets/splash.png \
        /usr/share/limine/splash.png \
        /boot/splash.png \
        /boot/limine-splash.png; do
        if [ -f "$candidate" ]; then
            SPLASH_IMG="$candidate"
            break
        fi
    done

    WALLPAPER_CONF=""
    if [ -n "$SPLASH_IMG" ]; then
        cp -f "$SPLASH_IMG" /boot/efi/splash.png 2>/dev/null || true
        cp -f "$SPLASH_IMG" /boot/splash.png 2>/dev/null || true
        WALLPAPER_CONF="wallpaper: boot:///splash.png
wallpaper_style: stretched"
    fi

    if [ ! -f /boot/efi/limine.conf ]; then
    cat <<EOF > /boot/efi/limine.conf
timeout: 5
${WALLPAPER_CONF}

/: $PRETTY_NAME
    protocol: linux
    kernel_path: boot:///$KERNEL_FILE
    module_path: boot:///$INITRD_FILE
    cmdline: root=$ROOT_PART rw $ROOTFLAGS
EOF
    fi
    cp /boot/efi/limine.conf /boot/efi/EFI/BOOT/limine.conf
else
    # BIOS/Legacy
    TARGET_DISK=$(grub2-probe -t disk / 2>/dev/null || echo "/dev/sda")
    limine bios-install "$TARGET_DISK"
    
    KERNEL_PATH=$(ls -1 /boot/vmlinuz-* 2>/dev/null | grep -v rescue | head -n 1)
    INITRD_PATH=$(ls -1 /boot/initramfs-* /boot/initrd-* 2>/dev/null | grep -v rescue | grep -v oa-initrd | head -n 1)
    KERNEL_FILE=$(basename "$KERNEL_PATH")
    INITRD_FILE=$(basename "$INITRD_PATH")

    ROOT_PART=$(awk '$2 == "/" && $1 !~ /^#/ {print $1}' /etc/fstab)
    if [ -z "$ROOT_PART" ]; then
        ROOT_PART=$(df / | awk 'NR==2 {print $1}')
    fi
    ROOT_FSTYPE=$(awk '$2 == "/" {print $3}' /etc/fstab)
    ROOTFLAGS=""
    if [ "$ROOT_FSTYPE" = "btrfs" ]; then
        ROOTFLAGS="rootflags=subvol=@"
    fi
    
    PRETTY_NAME=$(grep ^PRETTY_NAME= /etc/os-release | cut -d= -f2 | tr -d '"')
    if [ -z "$PRETTY_NAME" ]; then
        PRETTY_NAME="openSUSE"
    fi

    SPLASH_IMG=""
    for candidate in \
        /usr/share/wallpapers/cachyos-wallpapers/limine-splash.png \
        /usr/share/wallpapers/cachyos-wallpapers/splash.png \
        /etc/penguins-eggs.d/brain.d/assets/splash.png \
        /usr/share/limine/splash.png \
        /boot/splash.png \
        /boot/limine-splash.png; do
        if [ -f "$candidate" ]; then
            SPLASH_IMG="$candidate"
            break
        fi
    done

    WALLPAPER_CONF=""
    if [ -n "$SPLASH_IMG" ]; then
        cp -f "$SPLASH_IMG" /boot/splash.png 2>/dev/null || true
        WALLPAPER_CONF="wallpaper: boot:///splash.png
wallpaper_style: stretched"
    fi

    if [ ! -f /boot/limine.conf ]; then
    cat <<EOF > /boot/limine.conf
timeout: 5
${WALLPAPER_CONF}

/: $PRETTY_NAME
    protocol: linux
    kernel_path: boot:///$KERNEL_FILE
    module_path: boot:///$INITRD_FILE
    cmdline: root=$ROOT_PART rw $ROOTFLAGS
EOF
    fi
fi
{{ end }}
