#!/bin/bash
set -Eeuo pipefail

COZE_WORKSPACE_PATH="${COZE_WORKSPACE_PATH:-$(pwd)}"
BACKUP_FILE="${1:-}"
TMP_DIR="$(mktemp -d)"

cleanup() {
  rm -rf "${TMP_DIR}"
}
trap cleanup EXIT

if [ -z "${BACKUP_FILE}" ]; then
  echo "Usage: pnpm backup:restore <backup-file.tar.gz>" >&2
  exit 2
fi

if [ ! -f "${BACKUP_FILE}" ]; then
  echo "Backup file not found: ${BACKUP_FILE}" >&2
  exit 2
fi

cd "${COZE_WORKSPACE_PATH}"

if [ -f ".env.local" ]; then
  set +u
  set -a
  # shellcheck disable=SC1091
  source ".env.local"
  set +a
  set -u
fi

if [ -z "${LOCAL_DB_URL:-}" ]; then
  echo "LOCAL_DB_URL is required in .env.local or environment." >&2
  exit 1
fi

command -v pg_restore >/dev/null 2>&1 || {
  echo "pg_restore is required to restore backups." >&2
  exit 1
}

tar -xzf "${BACKUP_FILE}" -C "${TMP_DIR}"

if [ ! -f "${TMP_DIR}/database.dump" ]; then
  echo "Invalid backup: missing database.dump." >&2
  exit 2
fi

pg_restore --clean --if-exists --no-owner --dbname "${LOCAL_DB_URL}" "${TMP_DIR}/database.dump"

if [ -d "${TMP_DIR}/local-storage" ]; then
  STORAGE_TARGET="${LOCAL_STORAGE_DIR:-${COZE_WORKSPACE_PATH}/local-storage}"
  rm -rf "${STORAGE_TARGET}"
  mkdir -p "$(dirname "${STORAGE_TARGET}")"
  cp -a "${TMP_DIR}/local-storage" "${STORAGE_TARGET}"
fi

if [ -f "${TMP_DIR}/.env.local" ]; then
  cp "${TMP_DIR}/.env.local" ".env.local"
  chmod 600 ".env.local"
fi

echo "Restore completed from ${BACKUP_FILE}"
