#!/bin/bash
set -euo pipefail

BACKUP_DIR="/backup"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
DUMP_FILE="${BACKUP_DIR}/fr24_${TIMESTAMP}.sql.gz"
KEEP_LAST=7

echo "[backup] starting dump at ${TIMESTAMP}"

pg_dump \
  -h "${PGHOST:-postgres}" \
  -U "${PGUSER:-fr24}" \
  -d "${PGDATABASE:-fr24}" \
  --no-password \
  | gzip > "${DUMP_FILE}"

echo "[backup] dump written: ${DUMP_FILE} ($(du -sh "${DUMP_FILE}" | cut -f1))"

# Keep only last N dumps
cd "${BACKUP_DIR}"
ls -1t fr24_*.sql.gz 2>/dev/null | tail -n +$((KEEP_LAST + 1)) | xargs -r rm -v

echo "[backup] done. kept last ${KEEP_LAST} dumps."
