#!/usr/bin/env bash
set -euo pipefail

BACKUP_ROOT=${BACKUP_ROOT:-/var/backups/guanghu/bootstrap}
BACKUP_DIR=${1:-$(find "$BACKUP_ROOT" -mindepth 1 -maxdepth 1 -type d | sort | tail -1)}

if [[ -z "${BACKUP_DIR:-}" || ! -d "$BACKUP_DIR" ]]; then
  echo "No bootstrap backup found" >&2
  exit 1
fi

systemctl stop guanghu-gatekeeper.service 2>/dev/null || true
[[ -f "$BACKUP_DIR/node.json" ]] && install -m 0640 "$BACKUP_DIR/node.json" /etc/guanghu/node.json
[[ -f "$BACKUP_DIR/gatekeeper.env" ]] && install -m 0640 "$BACKUP_DIR/gatekeeper.env" /etc/guanghu/gatekeeper.env
[[ -f "$BACKUP_DIR/guanghu-gatekeeper.service" ]] && install -m 0644 "$BACKUP_DIR/guanghu-gatekeeper.service" /etc/systemd/system/guanghu-gatekeeper.service
systemctl daemon-reload
systemctl start guanghu-gatekeeper.service 2>/dev/null || true
echo "Rolled back from $BACKUP_DIR"
