#!/bin/bash
#
# Name: /usr/bin/tuxedo-factory-reset
# Part of tuxedo-btrfs
# Discards all system changes and rolls back to the pristine Snapshot 1.
#

set -e

if [ "$EUID" -ne 0 ]; then
    echo "Error: This script must be run as root!"
    exit 1
fi

# Hardcoded reference to the installer's pristine base snapshot
FACTORY_SNAPSHOT=1

echo "========================================="
echo "   TUXEDO OS - FACTORY RESET SYSTEM      "
echo "========================================="
echo ""
echo "WARNING: This will permanently discard all modifications made to"
echo "the system root configuration and installed packages."
echo "Your personal data in /home will NOT be affected."
echo ""
read -p "Are you sure you want to proceed? (y/N): " confirm

if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
    echo "Factory reset aborted by user."
    exit 0
fi

echo "Triggering Snapper rollback to pristine Factory Image (Snapshot ${FACTORY_SNAPSHOT})..."

# Run snapper rollback specifically targeting snapshot 1
SNAP_OUTPUT=$(snapper --ambit classic rollback "${FACTORY_SNAPSHOT}")
echo "${SNAP_OUTPUT}"

# Extract the newly created writable clone number (e.g., Snapshot 5)
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 "Connecting the fresh factory environment to the bootloader..."
# Call your existing patch script with the new snapshot number
/usr/share/tuxedo-btrfs/rollback-grub-efi-fstab.sh "${NEW_TARGET_NUM}"

echo ""
echo "========================================="
echo " Factory Reset successfully completed!   "
echo " Please reboot your TUXEDO device now.   "
echo "========================================="
exit 0
