#!/usr/bin/env bash
# 中学成绩档案 — 从备份包恢复（命令行，适合新服务器迁移）
set -euo pipefail

if [[ $# -lt 1 ]]; then
  echo "用法: sudo bash deploy/restore.sh /path/to/grade-archive_YYYYMMDD_HHMMSS.tar.gz"
  exit 1
fi

ARCHIVE="$1"
INSTALL_DIR="${INSTALL_DIR:-/opt/secondary-school-grade-archive}"
WORK=$(mktemp -d)

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

if [[ ! -f "${ARCHIVE}" ]]; then
  echo "[ERROR] 备份文件不存在: ${ARCHIVE}"
  exit 1
fi

cd "${INSTALL_DIR}"
# shellcheck disable=SC1090
source .env

echo "[WARN] 即将恢复数据库与 uploads，当前数据将被覆盖。"
read -rp "确认继续？[y/N] " confirm
if [[ "${confirm}" != "y" && "${confirm}" != "Y" ]]; then
  echo "已取消"
  exit 0
fi

echo "[INFO] 解压备份…"
tar -xzf "${ARCHIVE}" -C "${WORK}"

if [[ ! -f "${WORK}/database.sql" ]]; then
  echo "[ERROR] 备份包缺少 database.sql"
  exit 1
fi

echo "[INFO] 恢复数据库…"
PGPASSWORD="${POSTGRES_PASSWORD}" psql -h 127.0.0.1 -U "${POSTGRES_USER}" -d "${POSTGRES_DB}" \
  -v ON_ERROR_STOP=1 -f "${WORK}/database.sql"

if [[ -d "${WORK}/uploads" ]]; then
  echo "[INFO] 恢复 uploads…"
  rm -rf "${INSTALL_DIR}/uploads"
  cp -a "${WORK}/uploads" "${INSTALL_DIR}/uploads"
fi

echo "[INFO] 重启服务…"
systemctl restart grade-archive 2>/dev/null || true

echo "[INFO] 恢复完成"
