#!/usr/bin/env bash
set -Eeuo pipefail
ROOT="${SHIRE_ROOT:-/home/shire3d/ARMOR}"
STATE="$ROOT/data/agents/install-state.json"
test -r "$STATE" || { echo "FAIL: install state is missing: $STATE" >&2; exit 1; }
BACKUP="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["backupDir"])' "$STATE")"
test -r "$BACKUP/affected-paths.tar.gz" || { echo "FAIL: backup archive missing: $BACKUP" >&2; exit 1; }
sha256sum -c "$BACKUP/affected-paths.tar.gz.sha256"
echo "This will stop the new Agent services and restore the exact affected paths from:"
echo "  $BACKUP"
read -r -p "Type ROLLBACK to continue: " ANSWER
[[ "$ANSWER" == "ROLLBACK" ]] || { echo "Rollback cancelled."; exit 0; }
sudo systemctl disable --now shire-agent-hub.service shire-marketing-boss.service shire-marketing-boss.timer 2>/dev/null || true
sudo rm -rf "$ROOT/agents" "$ROOT/config/agents" "$ROOT/data/agents" "$ROOT/modules/dental-studio"
sudo rm -f /etc/systemd/system/shire-agent-hub.service /etc/systemd/system/shire-marketing-boss.service /etc/systemd/system/shire-marketing-boss-worker.service /etc/systemd/system/shire-marketing-boss.timer
sudo tar -C / -xzf "$BACKUP/affected-paths.tar.gz"
sudo systemctl daemon-reload
echo "Rollback restored. Marketing campaign files on SHiREVault were preserved as evidence and were not deleted."
