#!/usr/bin/env bash
set -euo pipefail

PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
BACKUP_DIR="${BACKUP_DIR:-$PROJECT_DIR/backups}"
TIMESTAMP="$(date +%Y%m%d-%H%M%S)"
COMPOSE_FILE="${COMPOSE_FILE:-$PROJECT_DIR/docker-compose.yml}"
DB_SERVICE="${DB_SERVICE:-db}"
DATABASE="${POSTGRES_DB:-davos_assessment}"
USER="${POSTGRES_USER:-davos}"
ALERT_WEBHOOK_URL="${ALERT_WEBHOOK_URL:-}"
KEEP_DAYS="${KEEP_DAYS:-14}"

DUMP_FILE="$BACKUP_DIR/davos-assessment-$TIMESTAMP.dump"
SHA_FILE="$DUMP_FILE.sha256"
META_FILE="$DUMP_FILE.meta"
LATEST_LINK="$BACKUP_DIR/latest.dump"

notify_failure() {
  if [ -z "$ALERT_WEBHOOK_URL" ]; then
    return
  fi
  local msg="${1:-数据库备份失败}"
  curl -sS -X POST "$ALERT_WEBHOOK_URL" \
    -H "Content-Type: application/json" \
    -d "{\"title\":\"DB_BACKUP_FAILED\",\"message\":\"${msg}\"}" >/dev/null || true
}

trap 'notify_failure "backup-db.sh 在 $(date "+%F %T") 执行失败"' ERR

mkdir -p "$BACKUP_DIR"

cd "$PROJECT_DIR"
docker compose -f "$COMPOSE_FILE" exec -T "$DB_SERVICE" \
  pg_dump -U "$USER" -d "$DATABASE" -Fc > "$DUMP_FILE"

if [ ! -s "$DUMP_FILE" ]; then
  echo "备份失败：导出文件为空"
  exit 1
fi

shasum -a 256 "$DUMP_FILE" > "$SHA_FILE"
{
  echo "timestamp=$TIMESTAMP"
  echo "database=$DATABASE"
  echo "user=$USER"
  echo "compose_file=$COMPOSE_FILE"
  echo "db_service=$DB_SERVICE"
  echo "size_bytes=$(wc -c < "$DUMP_FILE" | tr -d ' ')"
} > "$META_FILE"

ln -sfn "$(basename "$DUMP_FILE")" "$LATEST_LINK"
find "$BACKUP_DIR" -type f \( -name 'davos-assessment-*.dump' -o -name 'davos-assessment-*.dump.sha256' -o -name 'davos-assessment-*.dump.meta' \) -mtime +"$KEEP_DAYS" -delete

echo "数据库备份完成：$DUMP_FILE"
echo "校验文件：$SHA_FILE"
echo "元数据：$META_FILE"
