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

action=${1:-}
backup_root=/var/backups/guanghu/jd-control-plane
audit_dir=/var/lib/guanghu/recovery-audit
install -d -o root -g root -m 0700 "$audit_dir"

latest=$(find "$backup_root" -maxdepth 1 -type f -name 'control-plane-*.tgz' -print 2>/dev/null | sort | tail -n 1)
[[ -n "$latest" && -f "${latest%.tgz}.sha256" ]] || { echo "verified backup unavailable" >&2; exit 70; }
(cd "$backup_root" && sha256sum -c "$(basename "${latest%.tgz}.sha256")" >/dev/null)

stamp=$(date -u +%Y%m%dT%H%M%SZ)
case "$action" in
  restore-authz)
    tar -xzf "$latest" -C / opt/guanghu/lake-lamp-authz etc/systemd/system/lake-lamp-authz.service etc/systemd/system/lake-lamp-action-broker.service
    systemctl daemon-reload
    systemctl restart lake-lamp-action-broker.service lake-lamp-authz.service
    ;;
  install-owner-access)
    tar -xzf "$latest" -C / opt/guanghu/lake-lamp-authz/owner-access-broker.js opt/guanghu/lake-lamp-authz/action-client.js etc/systemd/system/lake-lamp-owner-access.service
    systemctl daemon-reload
    systemctl enable --now lake-lamp-owner-access.service
    systemctl restart lake-lamp-authz.service
    ;;
  restore-navigation-map)
    tar -xzf "$latest" -C / etc/guanghu/navigation-maps
    systemctl restart lake-lamp-authz.service
    ;;
  rollback-last-deploy)
    receipt=$(find /var/backups/guanghu/jd-enterprise-repair -maxdepth 1 -type f -name 'jd-authz-*.tgz' -print 2>/dev/null | sort | tail -n 1)
    [[ -n "$receipt" ]] || { echo "rollback backup unavailable" >&2; exit 71; }
    tar -xzf "$receipt" -C /
    systemctl daemon-reload
    systemctl restart lake-lamp-action-broker.service lake-lamp-authz.service
    ;;
  *)
    echo "recovery action denied" >&2
    exit 126
    ;;
esac

printf '{"schema":"guanghu.recovery-audit/v1","at":"%s","action":"%s","source":"%s","result":"ok"}\n' \
  "$stamp" "$action" "${SSH_CONNECTION%% *}" >> "$audit_dir/events.jsonl"
echo "RECOVERY_ACTION_OK=$action"
