#!/usr/bin/env bash
# 中学成绩档案 — 数据备份（数据库 + uploads，统一 tar.gz）
set -euo pipefail

INSTALL_DIR="${INSTALL_DIR:-/opt/secondary-school-grade-archive}"
BACKUP_DIR="${BACKUP_DIR:-/root/grade-archive-backups}"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
ARCHIVE="${BACKUP_DIR}/grade-archive_${TIMESTAMP}.tar.gz"
WORK=$(mktemp -d)

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

cd "${INSTALL_DIR}"
# shellcheck disable=SC1090
source .env
mkdir -p "${BACKUP_DIR}"

echo "[INFO] 备份数据库…"
PGPASSWORD="${POSTGRES_PASSWORD}" pg_dump -h 127.0.0.1 -U "${POSTGRES_USER}" "${POSTGRES_DB}" \
  --no-owner --no-privileges --clean --if-exists \
  > "${WORK}/database.sql"

cat > "${WORK}/manifest.json" <<EOF
{
  "app": "secondary-school-grade-archive",
  "created_at": "$(date -Iseconds)",
  "database": "${POSTGRES_DB}"
}
EOF

echo "[INFO] 打包 uploads…"
tar -czf "${ARCHIVE}" -C "${WORK}" database.sql manifest.json -C "${INSTALL_DIR}" uploads/

echo "[INFO] 完成: ${ARCHIVE}"

# 清理 30 天前的备份
find "${BACKUP_DIR}" -name 'grade-archive_*.tar.gz' -mtime +30 -delete 2>/dev/null || true
