#!/bin/bash

# Script de sauvegarde automatique pour MediFlash SOS+
# Usage: ./backup.sh [destination]

set -e

BACKUP_DIR=${1:-./backups}
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_NAME="mediflash-backup-$DATE"

echo "🔄 Démarrage sauvegarde MediFlash SOS+ - $DATE"

# Créer répertoire de sauvegarde
mkdir -p $BACKUP_DIR

# 1. Sauvegarde base de données
echo "💾 Sauvegarde base de données..."
docker-compose exec -T postgres pg_dump -U mediflash mediflash > $BACKUP_DIR/$BACKUP_NAME-database.sql

# 2. Sauvegarde fichiers uploads (si applicable)
echo "📁 Sauvegarde fichiers..."
if [ -d "./uploads" ]; then
    tar -czf $BACKUP_DIR/$BACKUP_NAME-uploads.tar.gz uploads/
fi

# 3. Sauvegarde configuration
echo "⚙️ Sauvegarde configuration..."
tar -czf $BACKUP_DIR/$BACKUP_NAME-config.tar.gz .env docker-compose.yml nginx/ || true

# 4. Compression finale
echo "🗜️ Compression finale..."
cd $BACKUP_DIR
tar -czf $BACKUP_NAME-complete.tar.gz $BACKUP_NAME-*
rm $BACKUP_NAME-database.sql $BACKUP_NAME-uploads.tar.gz $BACKUP_NAME-config.tar.gz 2>/dev/null || true
cd ..

# 5. Nettoyage anciennes sauvegardes (garder 7 jours)
find $BACKUP_DIR -name "mediflash-backup-*.tar.gz" -mtime +7 -delete 2>/dev/null || true

echo "✅ Sauvegarde terminée : $BACKUP_DIR/$BACKUP_NAME-complete.tar.gz"
echo "📊 Taille : $(du -h $BACKUP_DIR/$BACKUP_NAME-complete.tar.gz | cut -f1)"