#!/usr/bin/env bash
# backup-postgres.sh — Sauvegarde quotidienne rs971_db → Backblaze B2
#
# Prérequis :
#   1. rclone installé sur le VPS : apt-get install rclone
#   2. rclone configuré avec un remote nommé "b2" pointant sur Backblaze B2 :
#        rclone config  (choisir "b2", entrer account ID + application key)
#   3. Bucket B2 créé (ex : rs971-backups)
#
# Installation cron VPS (3h UTC chaque nuit) :
#   crontab -e
#   0 3 * * * /opt/stack/apps/radarsargasses971/scripts/backup-postgres.sh >> /var/log/rs971-backup.log 2>&1

set -euo pipefail

# ── Configuration ──────────────────────────────────────────────────────────
DB_CONTAINER="db_global"
DB_USER="postgres"
DB_NAME="rs971_db"
RCLONE_REMOTE="b2"
RCLONE_BUCKET="rs971-backups"
RETENTION_DAYS=30
BACKUP_DIR="/tmp/rs971-backups"
# ───────────────────────────────────────────────────────────────────────────

mkdir -p "$BACKUP_DIR"

TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="${BACKUP_DIR}/${DB_NAME}_${TIMESTAMP}.sql.gz"

echo "[$(date -Iseconds)] === Début sauvegarde ${DB_NAME} ==="

# Dump compressé directement dans le fichier
docker exec "$DB_CONTAINER" pg_dump -U "$DB_USER" --no-password "$DB_NAME" \
    | gzip > "$BACKUP_FILE"

SIZE=$(du -sh "$BACKUP_FILE" | cut -f1)
echo "[$(date -Iseconds)] Sauvegarde locale : ${BACKUP_FILE} (${SIZE})"

# Upload vers B2
rclone copy "$BACKUP_FILE" "${RCLONE_REMOTE}:${RCLONE_BUCKET}/$(hostname)/"
echo "[$(date -Iseconds)] Upload B2 OK → ${RCLONE_REMOTE}:${RCLONE_BUCKET}/$(hostname)/"

# Nettoyage fichier local
rm -f "$BACKUP_FILE"

# Suppression des backups distants > RETENTION_DAYS jours
rclone delete --min-age "${RETENTION_DAYS}d" "${RCLONE_REMOTE}:${RCLONE_BUCKET}/$(hostname)/"
echo "[$(date -Iseconds)] Nettoyage remote > ${RETENTION_DAYS} jours OK"

echo "[$(date -Iseconds)] === Sauvegarde terminée ==="
