#!/usr/bin/env bash
# 完整生产备份：PostgreSQL + uploads 卷，输出 gzip/tar.gz 与 sha256 校验文件。

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=scripts/deploy-lib.sh
source "$SCRIPT_DIR/deploy-lib.sh"

PREFIX="manual"
SKIP_UPLOADS=false

usage() {
  cat <<'EOF'
用法: scripts/backup-prod.sh [选项]

默认流程：
  1. 检查 .env.docker
  2. 启动并等待 PostgreSQL / Redis
  3. 备份 PostgreSQL 到 ./backups/*.sql.gz
  4. 通过正在运行的 api 容器备份 uploads 到 ./backups/*.tar.gz
  5. 为备份文件生成 .sha256 校验文件

选项:
  --prefix NAME    备份文件名前缀，默认 manual
  --skip-uploads   只备份数据库，不备份 uploads
  -h, --help       显示帮助

示例:
  ./scripts/backup-prod.sh
  ./scripts/backup-prod.sh --prefix pre-release
  ./scripts/backup-prod.sh --skip-uploads
EOF
}

while [ $# -gt 0 ]; do
  case "$1" in
    --prefix)
      PREFIX="${2:?缺少 --prefix 参数值}"
      shift 2
      ;;
    --skip-uploads)
      SKIP_UPLOADS=true
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      die "未知参数: $1"
      ;;
  esac
done

cd "$ROOT"
require_docker
ensure_env_file || exit 1
start_infra
backup_database "$PREFIX"

if [ "$SKIP_UPLOADS" = false ]; then
  backup_uploads "$PREFIX"
else
  warn "已跳过 uploads 备份"
fi

prune_old_backups
log "生产备份完成"
