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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
ENV_FILE="${1:-$ROOT_DIR/.env.production}"
BACKUP_DIR="${2:-}"
COMPOSE_FILE="$ROOT_DIR/infra/docker-compose.prod.yml"
RESET_DB="${RESET_DB:-0}"
RESTORE_S3="${RESTORE_S3:-1}"
FORCE="${FORCE:-0}"

if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
  cat <<'USAGE'
Usage:
  scripts/ops/restore-prod.sh [env-file] <backup-dir>

Examples:
  scripts/ops/restore-prod.sh .env.production backups/20260401T120000Z
  FORCE=1 RESET_DB=1 RESTORE_S3=1 scripts/ops/restore-prod.sh .env.production backups/...

Safety flags:
  FORCE=1     required to run restore
  RESET_DB=1  drops and recreates public schema before DB import (recommended)
  RESTORE_S3=1 syncs object storage from backup (default: 1)
USAGE
  exit 0
fi

if [[ "$FORCE" != "1" ]]; then
  echo "[error] restore is destructive; set FORCE=1 to continue" >&2
  exit 1
fi

if [[ ! -f "$ENV_FILE" ]]; then
  echo "[error] env file not found: $ENV_FILE" >&2
  exit 1
fi

if [[ -z "$BACKUP_DIR" ]]; then
  echo "[error] backup directory is required" >&2
  exit 1
fi

if [[ ! -d "$BACKUP_DIR" ]]; then
  echo "[error] backup directory not found: $BACKUP_DIR" >&2
  exit 1
fi

if [[ ! -f "$BACKUP_DIR/postgres.sql.gz" ]]; then
  echo "[error] missing postgres dump: $BACKUP_DIR/postgres.sql.gz" >&2
  exit 1
fi

if ! command -v docker >/dev/null 2>&1; then
  echo "[error] docker CLI is required" >&2
  exit 1
fi

node "$ROOT_DIR/scripts/check-production-env.mjs" "$ENV_FILE"

echo "[step] restoring postgres from $BACKUP_DIR/postgres.sql.gz ..."
if [[ "$RESET_DB" == "1" ]]; then
  docker compose --env-file "$ENV_FILE" -f "$COMPOSE_FILE" exec -T postgres \
    psql -U productier -d productier -v ON_ERROR_STOP=1 \
    -c 'DROP SCHEMA IF EXISTS public CASCADE;' \
    -c 'CREATE SCHEMA public;'
fi

gunzip -c "$BACKUP_DIR/postgres.sql.gz" \
  | docker compose --env-file "$ENV_FILE" -f "$COMPOSE_FILE" exec -T postgres \
    psql -U productier -d productier -v ON_ERROR_STOP=1

if [[ "$RESTORE_S3" == "1" ]]; then
  if [[ -d "$BACKUP_DIR/s3" ]]; then
    echo "[step] restoring object storage from $BACKUP_DIR/s3 ..."
    docker compose --env-file "$ENV_FILE" -f "$COMPOSE_FILE" run --rm --no-deps \
      -v "$BACKUP_DIR/s3:/restore:ro" \
      --entrypoint /bin/sh \
      rustfs-init \
      -lc 'set -euo pipefail; endpoint="http://rustfs:9000"; aws --endpoint-url "$endpoint" s3 sync /restore "s3://${S3_BUCKET:-productier}" --delete --no-progress'
  else
    echo "[warn] object storage restore skipped; backup directory has no s3/ folder"
  fi
fi

echo "[ok] restore complete"
