#!/usr/bin/env bash
set -Eeuo pipefail
BACKUP='/SHiREVault/Backup/OSBackups/SHIRE-Unified-Learning-0004-PREINSTALL-20260802T042114Z'
UNIFIED_SERVICE='shire-unified-learning.service'
ACADEMY_UI_SERVICE='shire-academy-ui.service'
TIMER='shire-academy-safe-autonomous.timer'
SENTINEL='/home/shire3d/ARMOR/modules/sentinel.py'
EXPECTED_SENTINEL_SHA='4fa53399f013e76ab05b3a4f093a1a7a4d5b48279a5e7a2a336a159a9c271d11'
mapfile -t TARGETS < "$BACKUP/all-target-paths.txt"
mapfile -t EXISTING < "$BACKUP/existing-paths.txt"
for path in "${TARGETS[@]}"; do sudo rm -rf -- "$path"; done
sudo tar --xattrs --acls --numeric-owner -xpf "$BACKUP/live-files.tar" -C /
sudo systemctl restart "$UNIFIED_SERVICE"
sudo systemctl restart "$ACADEMY_UI_SERVICE"
if [[ "$(cat "$BACKUP/timer-was-active.txt")" == "1" ]]; then
  sudo systemctl start "$TIMER"
fi
ACTUAL="$(sha256sum "$SENTINEL" | awk '{print $1}')"
[[ "$ACTUAL" == "$EXPECTED_SENTINEL_SHA" ]] || { echo 'FAIL: Sentinel hash changed during rollback.'; exit 1; }
sha256sum -c "$BACKUP/noncontrol-protected-before.sha256"
echo "ROLLBACK COMPLETE: $BACKUP"
