#!/bin/bash
#
# Wrapper for permanently rolling back to the currently running snapshot.
#

set -e

if [ "$EUID" -ne 0 ]; then
    echo "Error: Script has to be run as root!"
    exit 1
fi

if touch /\.writable_test 2>/dev/null; then
    rm /\.writable_test
    echo "Abort: The system is running in normal mode (writable)."
    exit 0
fi

SNAPSHOT_NUM=$(mount | grep "on / type btrfs" | grep -oP '(?<=snapshots/)\d+(?=/snapshot)')

if [ -z "$SNAPSHOT_NUM" ]; then
    echo "Error: The system does not appear to be running in a Snapper snapshot!"
    exit 1
fi

echo "Currently used rescue snapshot number: $SNAPSHOT_NUM"

echo "Performing a Snapper rollback..."
# We run snapper and capture its output to find the newly created writeable snapshot number
SNAP_OUTPUT=$(snapper --ambit classic rollback "$SNAPSHOT_NUM")
echo "$SNAP_OUTPUT"

# Extract the new snapshot number (e.g., "4" or "6") from the German or English snapper output
NEW_TARGET_NUM=$(echo "$SNAP_OUTPUT" | grep -E "(Lesen-Schreiben-Schnappschuss|Creating writable snapshot)" | grep -oP '\d+(?=\.\)$|\)$)')

if [ -z "$NEW_TARGET_NUM" ]; then
    echo "Error: Could not parse the new writable snapshot number from Snapper!"
    exit 1
fi

echo "Updating the bootloader, EFI, and fstab for the new target snapshot $NEW_TARGET_NUM..."
/usr/share/tuxedo-btrfs/rollback-grub-efi-fstab.sh "$NEW_TARGET_NUM"

echo "Rollback completed successfully. You have to reboot immediately!"
exit 0
