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

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck disable=SC1091
source "$SCRIPT_DIR/pd_backup_lib.sh"

verify_root="${RESTORE_VERIFY_WORK_ROOT:-/mnt/tank/docker/backups/restore-verify}"
remote_source="${RESTORE_VERIFY_CONFIG_SOURCE:-tank-docker/appdata/grafana}"
required_paths="${RESTORE_VERIFY_REQUIRED_PATHS:-grafana.db dashboards}"
stage_dir="$verify_root/appdata-stage"

mkdir -p "$verify_root"
rm -rf "$stage_dir"
mkdir -p "$stage_dir"

remote_path="$SERENITY_BACKUP_ROOT/$remote_source/"

echo "Staging config restore sample from $SERENITY_BACKUP_HOST:$remote_path"
rsync -a -e "$(ssh_cmd)" "$SERENITY_BACKUP_HOST:$remote_path" "$stage_dir/"

for rel in $required_paths; do
  if [[ ! -e "$stage_dir/$rel" ]]; then
    echo "Missing expected restored path: $rel" >&2
    exit 1
  fi
done

if [[ -f "$stage_dir/grafana.db" ]] && command -v sqlite3 >/dev/null 2>&1; then
  sqlite3 "$stage_dir/grafana.db" 'PRAGMA integrity_check;' | grep -qx 'ok'
  echo "Verified SQLite integrity for grafana.db"
fi

echo "Config restore verification passed for $remote_source."
