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

cd "$(dirname "$0")/.."

BACKUP_SOURCE="${1:-}"
STORAGE_HOST_PATH="${STORAGE_HOST_PATH:-./storage}"

if [[ -z "${BACKUP_SOURCE}" || ! -d "${BACKUP_SOURCE}" ]]; then
  echo "Usage: scripts/restore.sh <backup-directory>" >&2
  exit 1
fi

echo "This restore can overwrite database and storage state."
echo "Backup source: ${BACKUP_SOURCE}"
echo "Storage target: ${STORAGE_HOST_PATH}"
read -r -p "Type RESTORE to continue: " confirmation

if [[ "${confirmation}" != "RESTORE" ]]; then
  echo "Restore cancelled"
  exit 0
fi

if [[ -f "${BACKUP_SOURCE}/postgres.sql" ]]; then
  if [[ -n "${POSTGRES_CONTAINER:-}" ]]; then
    echo "==> Restoring PostgreSQL dump into container ${POSTGRES_CONTAINER}"
    docker exec -i "${POSTGRES_CONTAINER}" psql -U "${POSTGRES_USER:-olympus}" "${POSTGRES_DB:-olympus}" < "${BACKUP_SOURCE}/postgres.sql"
  elif command -v psql >/dev/null 2>&1 && [[ -n "${DATABASE_URL:-}" ]]; then
    echo "==> Restoring PostgreSQL dump from DATABASE_URL"
    psql "${DATABASE_URL}" < "${BACKUP_SOURCE}/postgres.sql"
  else
    echo "WARN: PostgreSQL restore skipped. Set POSTGRES_CONTAINER or install psql with DATABASE_URL."
  fi
else
  echo "WARN: postgres.sql not found; database restore skipped."
fi

if [[ -f "${BACKUP_SOURCE}/storage.tar.gz" ]]; then
  mkdir -p "${STORAGE_HOST_PATH}"
  echo "==> Restoring storage archive"
  tar -xzf "${BACKUP_SOURCE}/storage.tar.gz" -C "${STORAGE_HOST_PATH}"
else
  echo "WARN: storage.tar.gz not found; storage restore skipped."
fi

echo "==> Restore completed"
