#!/bin/bash
# Répertoire des backups
BACKUP_DIR="/mnt/backup_syno/dumps/postgres/$(date +%F)"
mkdir -p "$BACKUP_DIR"

# ---- Paramètres PostgreSQL ----
POSTGRES_CONTAINER="postgres"
POSTGRES_USER="postgres_user"
POSTGRES_PASSWORD="3rL2&dyZMd7%BY"

export PGPASSWORD=$POSTGRES_PASSWORD

# Liste les bases (en se connectant à 'postgres')
DATABASES=$(docker exec -e PGPASSWORD=$POSTGRES_PASSWORD $POSTGRES_CONTAINER \
    psql -U $POSTGRES_USER -d postgres -t -c "SELECT datname FROM pg_database WHERE datistemplate = false;")

for DB in $DATABASES; do
    DB=$(echo $DB | xargs) # supprime espaces éventuels
    echo "Dump PostgreSQL: $DB"
    docker exec -e PGPASSWORD=$POSTGRES_PASSWORD $POSTGRES_CONTAINER \
        pg_dump -U $POSTGRES_USER -d $DB | gzip > "$BACKUP_DIR/${DB}_postgres_$(date +%F).sql.gz"
done

unset PGPASSWORD
