#!/bin/bash
# Cyrene PostgreSQL 备份/恢复
# 用法: ./pg-backup.sh backup   # 备份到 ./backups/
#       ./pg-backup.sh restore  # 从最新备份恢复
set -euo pipefail

CONTAINER="cyrene_postgres"
DB="cyrene_ai"
USER="cyrene"
BACKUP_DIR="$(cd "$(dirname "$0")/../backups" && pwd)"

backup() {
  mkdir -p "$BACKUP_DIR"
  local file="$BACKUP_DIR/cyrene_$(date +%Y%m%d_%H%M%S).sql"
  echo "正在备份 $DB → $file ..."
  docker exec "$CONTAINER" pg_dump -U "$USER" -d "$DB" \
    --no-owner --no-acl --clean --if-exists > "$file"
  ls -lh "$file"
  echo "备份完成: $file"

  # 只保留最近 7 个备份
  local count=$(ls -1 "$BACKUP_DIR"/*.sql 2>/dev/null | wc -l)
  if [ "$count" -gt 7 ]; then
    ls -1t "$BACKUP_DIR"/*.sql | tail -n +8 | xargs rm -f
    echo "已清理旧备份 (保留最近 7 个)"
  fi
}

restore() {
  local file
  if [ -n "${1:-}" ]; then
    file="$1"
  else
    file=$(ls -1t "$BACKUP_DIR"/*.sql 2>/dev/null | head -1)
  fi
  if [ -z "$file" ] || [ ! -f "$file" ]; then
    echo "错误: 找不到备份文件" >&2
    exit 1
  fi
  echo "正在从 $file 恢复..."
  docker exec -i "$CONTAINER" psql -U "$USER" -d "$DB" < "$file"
  echo "恢复完成"
}

case "${1:-}" in
  backup)  backup ;;
  restore) restore "${2:-}" ;;
  *)
    echo "用法: $0 backup|restore [文件路径]"
    echo "  backup         备份到 $BACKUP_DIR"
    echo "  restore [file] 恢复备份 (默认最新)"
    exit 1
    ;;
esac
