#!/usr/bin/env bash
set -Eeuo pipefail
BACKUP='/SHiREVault/Backup/OSBackups/SHIRE-Unified-Learning-0005-PREINSTALL-20260802T053528Z'
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'
STATE='/home/shire3d/ARMOR/data/academy/design_mastery/runtime/practice_state.json'
AUTOPILOT='/home/shire3d/ARMOR/data/academy/design_mastery/runtime/autopilot_state.json'
SPRINT='/home/shire3d/ARMOR/data/academy/design_mastery/runtime/commercial_design_sprint.json'
INDEX='/home/shire3d/ARMOR/data/academy/design_mastery/runtime/academy_index.sqlite3'
mapfile -t TARGETS < "$BACKUP/all-target-paths.txt"
for path in "${TARGETS[@]}"; do rm -rf -- "$path"; done
tar --xattrs --acls --numeric-owner -xpf "$BACKUP/live-files.tar" -C /
systemctl daemon-reload
systemctl restart "$UNIFIED_SERVICE"
systemctl restart "$ACADEMY_UI_SERVICE"
if [[ "$(cat "$BACKUP/timer-was-enabled.txt")" == "1" ]]; then
  systemctl enable "$TIMER" >/dev/null
else
  systemctl disable "$TIMER" >/dev/null 2>&1 || true
fi
if [[ "$(cat "$BACKUP/timer-was-active.txt")" == "1" ]]; then
  systemctl start "$TIMER"
else
  systemctl stop "$TIMER" >/dev/null 2>&1 || true
fi
ACTUAL="$(sha256sum "$SENTINEL" | awk '{print $1}')"
[[ "$ACTUAL" == "$EXPECTED_SENTINEL_SHA" ]] || { echo 'FAIL: Sentinel hash changed during rollback.'; exit 1; }
python3 "$BACKUP/protected_state.py" verify   --practice "$STATE"   --autopilot "$AUTOPILOT"   --sprint "$SPRINT"   --index "$INDEX"   --expected "$BACKUP/protected-before.json"
echo "ROLLBACK COMPLETE: $BACKUP"
