#!/usr/bin/env bash
# Restores a MySQL backup produced by backup-database.sh — see
# docs/PROJECT_PLAN.md §0B.23 for where this fits in the full recovery
# sequence (database first, then storage, then a reconciliation scan
# before opening the service to users — see app:reconcile-storage).
#
# Usage: ./restore-database.sh <backup-file.sql.gz>
#        ./restore-database.sh --latest [backup-dir]
#
# DESTRUCTIVE: replaces the contents of the live database. Requires
# explicit confirmation unless CONFIRM=yes is set in the environment
# (for scripted disaster-recovery drills).
set -euo pipefail

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
repo_root="$(cd "$script_dir/../.." && pwd)"

source "$script_dir/lib/env.sh"

if [[ "${1:-}" == "--latest" ]]; then
  backup_dir="${2:-$repo_root/backups/database}"
  backup_file="$(find "$backup_dir" -maxdepth 1 -name 'db-*.sql.gz' -type f | sort -r | head -n1)"
  if [[ -z "$backup_file" ]]; then
    echo "error: no db-*.sql.gz backups found in $backup_dir" >&2
    exit 1
  fi
else
  backup_file="${1:?Usage: $0 <backup-file.sql.gz> | --latest [backup-dir]}"
fi

if [[ ! -f "$backup_file" ]]; then
  echo "error: $backup_file does not exist" >&2
  exit 1
fi

if [[ ! -f "$repo_root/.env" ]]; then
  echo "error: $repo_root/.env not found — run this from a real VPS deployment, not a dev checkout" >&2
  exit 1
fi

MYSQL_DATABASE="$(env_var "$repo_root/.env" MYSQL_DATABASE)"
MYSQL_USER="$(env_var "$repo_root/.env" MYSQL_USER)"
MYSQL_PASSWORD="$(env_var "$repo_root/.env" MYSQL_PASSWORD)"

echo "About to restore $backup_file into database '$MYSQL_DATABASE'."
echo "This REPLACES all current data in that database."
if [[ "${CONFIRM:-}" != "yes" ]]; then
  read -r -p "Type the database name ($MYSQL_DATABASE) to confirm: " typed
  if [[ "$typed" != "$MYSQL_DATABASE" ]]; then
    echo "Aborted: confirmation did not match." >&2
    exit 1
  fi
fi

echo "Restoring..."
gunzip -c "$backup_file" | docker compose -f "$repo_root/docker-compose.yml" exec -T mysql \
  mysql -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" "$MYSQL_DATABASE"

echo "Database restored from $backup_file."
echo "Next: restore storage (restore-storage.sh on the Pi), then run"
echo "  docker compose exec backend php artisan app:reconcile-storage"
echo "before opening the service to users — see PROJECT_PLAN.md §0B.23."
