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

if [[ $# -ne 1 ]]; then
  echo "Usage: $0 /opt/bytelyst/open-notebook-pilot/backups/open-notebook-pilot-YYYYmmddTHHMMSSZ.tar.gz" >&2
  exit 2
fi

BACKUP=$1
COMPOSE_FILE=${COMPOSE_FILE:-/opt/bytelyst/learning_ai_devops_tools/deployments/open-notebook-pilot/docker-compose.yml}
ENV_FILE=${ENV_FILE:-/etc/bytelyst/open-notebook-pilot.env}
RESTORE_ROOT=${RESTORE_ROOT:-/opt/bytelyst/open-notebook-pilot/restore-test}

[[ -f "$BACKUP" ]] || { echo "Backup not found: $BACKUP" >&2; exit 1; }
mkdir -p "$RESTORE_ROOT"
chmod 700 "$RESTORE_ROOT"
rm -rf "$RESTORE_ROOT/extracted"
mkdir -p "$RESTORE_ROOT/extracted"

tar -xzf "$BACKUP" -C "$RESTORE_ROOT/extracted"

for required in \
  "$RESTORE_ROOT/extracted/opt/bytelyst/open-notebook-pilot/surreal_data" \
  "$RESTORE_ROOT/extracted/opt/bytelyst/open-notebook-pilot/notebook_data" \
  "$RESTORE_ROOT/extracted/etc/bytelyst/open-notebook-pilot.env"; do
  [[ -e "$required" ]] || { echo "Missing expected restore payload: $required" >&2; exit 1; }
done

# Verify the live compose can be parsed with the protected env file; this is a
# non-destructive restore readiness check. Actual restore requires planned
# downtime and replacing DATA_DIR contents from the extracted payload.
docker compose --env-file "$ENV_FILE" -f "$COMPOSE_FILE" config --quiet

printf 'restore_test=ok\nbackup=%s\nrestore_root=%s\n' "$BACKUP" "$RESTORE_ROOT/extracted"
