#!/usr/bin/env bash
set -Eeuo pipefail
[[ $EUID -eq 0 ]] || { echo 'Use sudo.' >&2;exit 1; }
BASE=/opt/archforge-status
[[ -f "$BASE/previous-release" ]] || { echo 'No previous release snapshot.' >&2;exit 1; }
SNAP=$(cat "$BASE/previous-release")
[[ "$SNAP" == "$BASE"/releases/release-* && -d "$SNAP" ]] || { echo 'Invalid rollback path.' >&2;exit 1; }
read -rp 'Roll back application code (database remains unchanged)? Type ROLLBACK: ' ANSWER
[[ "$ANSWER" == ROLLBACK ]] || exit 1
systemctl stop archforge-status
mv "$BASE/app" "$BASE/releases/undone-$(date -u +%Y%m%d-%H%M%S)"
mv "$SNAP" "$BASE/app"
rm -f "$BASE/previous-release"
systemctl start archforge-status
echo 'Rollback completed. If schema changes are incompatible, use restore.sh with a matching backup.'
