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

BACKUP_DIR="${BACKUP_DIR:-./database-backups}"
RETENTION_DAYS="${RETENTION_DAYS:-30}"
COMPOSE_PROJECT_NAME="${COMPOSE_PROJECT_NAME:-cnc_precision}"
TIMESTAMP="$(date +%Y%m%d_%H%M%S)"
OUTPUT="$BACKUP_DIR/cnc_eval_db_${TIMESTAMP}.backup"

mkdir -p "$BACKUP_DIR"
docker compose -p "$COMPOSE_PROJECT_NAME" exec -T db pg_dump -U "${POSTGRES_USER:-precision}" -d cnc_eval_db -Fc >"$OUTPUT"
docker compose -p "$COMPOSE_PROJECT_NAME" exec -T db pg_restore --list <"$OUTPUT" >/dev/null
find "$BACKUP_DIR" -type f -name 'cnc_eval_db_*.backup' -mtime +"$RETENTION_DAYS" -delete
echo "Backup verified: $OUTPUT"
