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

# Paramètres de connexion (exposés par Docker)
MARIADB_HOST="127.0.0.1"
MARIADB_PORT="3306"
MARIADB_USER="root"
MARIADB_PASSWORD="&22dt4H4&owV8DPb"

# Vérifie si le client mysql est dispo
if ! command -v mysql &> /dev/null; then
    echo "mysql non trouvé. Installation silencieuse du client MariaDB..."
    sudo apt-get update -qq
    sudo DEBIAN_FRONTEND=noninteractive apt-get install -y mariadb-client > /dev/null
fi

# Liste des bases (hors systèmes)
DATABASES=$(mysql -h $MARIADB_HOST -P $MARIADB_PORT -u$MARIADB_USER -p$MARIADB_PASSWORD \
  -e "SHOW DATABASES;" 2>/dev/null | grep -Ev "(Database|information_schema|performance_schema|mysql|sys)")

if [ -z "$DATABASES" ]; then
    echo "Aucune base MariaDB trouvée ! Vérifie la connexion au conteneur."
    exit 1
fi

echo "Bases MariaDB trouvées :"
echo "$DATABASES"

# Dump de chaque base
for DB in $DATABASES; do
    echo "Dump de la base $DB..."
    mysqldump -h $MARIADB_HOST -P $MARIADB_PORT -u$MARIADB_USER -p$MARIADB_PASSWORD $DB \
        | gzip > "$BACKUP_DIR/${DB}_$(date +%F).sql.gz"
done

echo "Backup MariaDB terminé dans $BACKUP_DIR"
