#!/bin/bash

set -euo pipefail

OLD_KVER="${OLD_KVER:-5.10.134-19.5.al8.aarch64}"
CONFIRM="${CONFIRM:-}"
OLD_VMLINUZ="/boot/vmlinuz-$OLD_KVER"

if [ "$(id -u)" -ne 0 ]; then
    echo "ERROR: run as root" >&2
    exit 1
fi

if [ ! -f "$OLD_VMLINUZ" ]; then
    echo "ERROR: rollback kernel is missing: $OLD_VMLINUZ" >&2
    exit 1
fi

echo "CURRENT_KERNEL=$(uname -r)"
echo "ROLLBACK_KERNEL=$OLD_KVER"
grubby --info="$OLD_VMLINUZ"

if [ "$CONFIRM" != "ROLLBACK-$OLD_KVER" ]; then
    echo "STOP: inspection only. Re-run with CONFIRM=ROLLBACK-$OLD_KVER."
    exit 2
fi

grubby --set-default "$OLD_VMLINUZ"
echo "DEFAULT_KERNEL=$(grubby --default-kernel)"
echo "ROLLBACK_BOOT_CONFIGURED=1"
echo "Reboot is intentionally not automatic. In an approved window run:"
echo "  sync"
echo "  systemctl reboot"
echo "After reboot require: uname -r = $OLD_KVER"

