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

BACKUP_ROOT="${BACKUP_ROOT:-/root/xiaoxia-backups}"
POSTGRES_CONTAINER="${POSTGRES_CONTAINER:-xiaoxia-postgres}"
POSTGRES_USER="${POSTGRES_USER:-xiaoxia}"
POSTGRES_DB="${POSTGRES_DB:-xiaoxia_saas}"

TS="$(date +%Y%m%d-%H%M%S)"
BACKUP_DIR="$BACKUP_ROOT/$TS"
DUMP_PATH="$BACKUP_DIR/${POSTGRES_DB}.dump"
VERSION_PATH="$BACKUP_DIR/alembic_version.txt"
MANIFEST_PATH="$BACKUP_DIR/manifest.txt"

mkdir -p "$BACKUP_DIR"

docker exec "$POSTGRES_CONTAINER" pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Fc > "$DUMP_PATH"
docker exec "$POSTGRES_CONTAINER" psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Atc 'select version_num from alembic_version;' > "$VERSION_PATH" 2>/dev/null || true

if [ ! -s "$DUMP_PATH" ]; then
  echo "ERROR: backup dump is empty: $DUMP_PATH" >&2
  exit 1
fi

{
  echo "created_at=$TS"
  echo "postgres_container=$POSTGRES_CONTAINER"
  echo "postgres_user=$POSTGRES_USER"
  echo "postgres_db=$POSTGRES_DB"
  echo "dump_path=$DUMP_PATH"
  echo "alembic_version=$(cat "$VERSION_PATH" 2>/dev/null || true)"
  echo "dump_size_bytes=$(wc -c < "$DUMP_PATH")"
} > "$MANIFEST_PATH"

ls -lh "$DUMP_PATH"
echo "OK backup created: $BACKUP_DIR"
