#!/usr/bin/env bash
# Kexec into the currently installed kernel, skipping PS5 firmware POST.
# Locates the ESP wherever it actually lives (bazzite uses /efi, most others
# use /boot/efi, some /boot directly).
set -eu

find_esp() {
    for d in /efi /boot/efi /boot; do
        [ -f "$d/bzImage" ] && [ -f "$d/initrd.img" ] && [ -f "$d/cmdline.txt" ] \
            && { echo "$d"; return 0; }
    done
    # Nothing pre-mounted has the files. Try mounting known-label vfat partitions.
    for lbl in boot BOOT EFI ESP; do
        mkdir -p /boot/efi
        mount "LABEL=$lbl" /boot/efi 2>/dev/null || continue
        if [ -f /boot/efi/bzImage ]; then echo /boot/efi; return 0; fi
        umount /boot/efi 2>/dev/null || true
    done
    return 1
}

ESP=$(find_esp) || { echo "warm-reboot: cannot locate ESP (no bzImage found)" >&2; exit 1; }

CMDLINE=$(cat "$ESP/cmdline.txt")
kexec -l "$ESP/bzImage" --initrd="$ESP/initrd.img" --append="$CMDLINE"
systemctl kexec -i
