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

SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
ARCHIVE=""
IDENTITY=${HOME}/.config/overdeck/k3s-backup.agekey
TARGET=""

usage() {
  cat <<'USAGE'
Usage:
  restore-control-plane.sh --archive BACKUP.tar.age --target EMPTY_DIRECTORY [--identity AGE_KEY]

This command decrypts and materializes an isolated restore tree only. It never
stops K3s, writes to /, or activates the restored datastore. Follow the
k3s-control-plane-backup-restore runbook for a live recovery.
USAGE
}

while (($#)); do
  case "$1" in
    --archive) ARCHIVE=${2:?missing value for --archive}; shift 2 ;;
    --identity) IDENTITY=${2:?missing value for --identity}; shift 2 ;;
    --target) TARGET=${2:?missing value for --target}; shift 2 ;;
    -h|--help) usage; exit 0 ;;
    *) printf 'restore-control-plane: unknown argument: %s\n' "$1" >&2; usage >&2; exit 64 ;;
  esac
done

[[ -n "$ARCHIVE" && -n "$TARGET" ]] || { usage >&2; exit 64; }
command -v age >/dev/null || { echo 'restore-control-plane: age is required' >&2; exit 69; }
command -v python3 >/dev/null || { echo 'restore-control-plane: python3 is required' >&2; exit 69; }
[[ -f "$ARCHIVE" && ! -L "$ARCHIVE" ]] || { echo "restore-control-plane: unsafe or missing archive: $ARCHIVE" >&2; exit 66; }
[[ -f "$IDENTITY" && ! -L "$IDENTITY" ]] || { echo "restore-control-plane: unsafe or missing age identity: $IDENTITY" >&2; exit 66; }
[[ ! -L "$TARGET" ]] || { echo "restore-control-plane: target must not be a symlink: $TARGET" >&2; exit 66; }

TARGET=$(realpath -m -- "$TARGET")
[[ "$TARGET" != / ]] || { echo 'restore-control-plane: refusing live root /' >&2; exit 64; }
if [[ -e "$TARGET" && ( ! -d "$TARGET" || -n "$(find "$TARGET" -mindepth 1 -maxdepth 1 -print -quit)" ) ]]; then
  echo "restore-control-plane: target must be an empty directory: $TARGET" >&2
  exit 73
fi

TMP=$(mktemp -d "${TMPDIR:-/tmp}/overdeck-k3s-restore.XXXXXXXX")
cleanup() {
  chmod -R u+rwX "$TMP" 2>/dev/null || true
  rm -rf -- "$TMP"
}
trap cleanup EXIT HUP INT TERM

DECRYPTED=$TMP/backup.tar
RESULT=$TMP/verify-result.json
age -d -i "$IDENTITY" -o "$DECRYPTED" "$ARCHIVE"
python3 "$SCRIPT_DIR/verify-backup.py" \
  --archive "$DECRYPTED" \
  --restore-root "$TARGET" \
  --output "$RESULT" >/dev/null
install -m 0600 "$RESULT" "$TARGET/OVERDECK_VERIFY_RESULT.json"

cat "$TARGET/OVERDECK_VERIFY_RESULT.json"
printf '\nRestore materialized at: %s\n' "$TARGET" >&2
printf 'No live K3s service or filesystem was modified.\n' >&2
