From dce99f58d70917c2929ba199fa735d3c4d1866c9 Mon Sep 17 00:00:00 2001 From: Matthieu THOLOT Date: Thu, 2 Apr 2026 08:08:06 +0000 Subject: [PATCH] feat : add Discord notifications to backup script Co-Authored-By: Claude Opus 4.6 (1M context) --- .env.example | 3 +++ backup.sh | 60 ++++++++++++++++++++++++++++++++++++++++++++++------ 2 files changed, 57 insertions(+), 6 deletions(-) diff --git a/.env.example b/.env.example index 6357059..533c274 100644 --- a/.env.example +++ b/.env.example @@ -1,3 +1,6 @@ # Superuser PostgreSQL (utilise pour creer les BDD/users au premier lancement) POSTGRES_USER=admin POSTGRES_PASSWORD=change-me + +# Notifications Discord (optionnel) +DISCORD_WEBHOOK_URL= diff --git a/backup.sh b/backup.sh index 6c4c678..9bddbfa 100755 --- a/backup.sh +++ b/backup.sh @@ -3,16 +3,64 @@ set -euo pipefail cd "$(dirname "$0")" +# Charger les variables d'environnement +source .env + BACKUP_DIR="./backups" +DATABASES=("sirh_prod" "inventory_prod" "lesstime_prod") DATE=$(date +%Y-%m-%d_%H%M%S) +LOG_FILE="${BACKUP_DIR}/backup.log" +WEBHOOK_URL="${DISCORD_WEBHOOK_URL:-}" mkdir -p "$BACKUP_DIR" -echo "==> Dumping all databases..." -docker compose exec -T postgres pg_dumpall -U admin > "${BACKUP_DIR}/all-databases-${DATE}.sql" +log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOG_FILE"; } -echo "==> Backup saved to ${BACKUP_DIR}/all-databases-${DATE}.sql" +discord() { + local color="$1" title="$2" msg="$3" + [[ -z "$WEBHOOK_URL" ]] && return 0 + curl -fsS -H "Content-Type: application/json" -d "{ + \"embeds\": [{ + \"title\": \"${title}\", + \"description\": \"${msg}\", + \"color\": ${color} + }] + }" "$WEBHOOK_URL" >/dev/null 2>&1 || true +} -# Garder les 7 derniers backups -ls -t "${BACKUP_DIR}"/all-databases-*.sql | tail -n +8 | xargs -r rm -- -echo "==> Old backups cleaned (keeping last 7)." +fail() { + log "ERROR: $1" + discord 16711680 "Backup PostgreSQL - ECHEC" "$1" + exit 1 +} + +# Verifications +command -v docker &>/dev/null || fail "docker n'est pas installe" + +# Supprimer les anciens backups (on ne garde que le dernier) +rm -f "${BACKUP_DIR}"/*.sql + +log "Debut backup PostgreSQL" + +DETAILS="" +ERRORS=0 + +for DB in "${DATABASES[@]}"; do + log "Dumping ${DB}..." + if docker compose exec -T postgres pg_dump -U admin "$DB" > "${BACKUP_DIR}/${DB}-${DATE}.sql" 2>/dev/null; then + SIZE=$(du -h "${BACKUP_DIR}/${DB}-${DATE}.sql" | cut -f1) + log "${DB} sauvegarde (${SIZE})" + DETAILS="${DETAILS}\\n- **${DB}** : ${SIZE}" + else + log "ERREUR sur ${DB}" + DETAILS="${DETAILS}\\n- **${DB}** : ERREUR" + ((ERRORS++)) + fi +done + +if [[ $ERRORS -gt 0 ]]; then + fail "Backup termine avec ${ERRORS} erreur(s) :${DETAILS}" +fi + +log "Backup termine avec succes" +discord 65280 "Backup PostgreSQL - OK" "Backup **${DATE}** termine\\n${DETAILS}"