#!/bin/bash

# Chemin du projet
PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_NAME="$(basename "$PROJECT_DIR")"
TIMESTAMP="$(date +%Y%m%d_%H%M%S)"
BACKUP_FILENAME="${PROJECT_NAME}_${TIMESTAMP}.tar.gz"
TEMP_BACKUP_DIR="/tmp"
BACKUP_PATH="${TEMP_BACKUP_DIR}/${BACKUP_FILENAME}"

# Charger les variables d'environnement
if [ ! -f "${PROJECT_DIR}/.env-backup" ]; then
    echo "❌ Fichier .env-backup manquant"
    exit 1
fi
source "${PROJECT_DIR}/.env-backup"

# Fonction pour gérer les erreurs
error_exit() {
    echo "❌ $1"
    exit 1
}

# Fonction pour nettoyer les anciens backups
cleanup_old_backups() {
    local server_ip=$1
    local server_port=$2
    local server_user=$3
    local server_key=$4
    local server_path=$5
    
    echo "🧹 Nettoyage des backups plus anciens que ${BACKUP_RETENTION_DAYS} jours sur $server_ip..."
    ssh -i "$server_key" -p "$server_port" "$server_user@$server_ip" \
        "find $server_path -name '${PROJECT_NAME}_*.tar.gz' -type f -mtime +${BACKUP_RETENTION_DAYS} -delete" || \
        echo "⚠️ Avertissement: Nettoyage des anciens backups sur $server_ip échoué"
}

# Création du backup
echo "📦 Création du backup de ${PROJECT_NAME}..."
cd "${PROJECT_DIR}/.."
tar -czf "$BACKUP_PATH" \
    --exclude="${PROJECT_NAME}/build" \
    --exclude="${PROJECT_NAME}/.dart_tool" \
    --exclude="${PROJECT_NAME}/.pub" \
    --exclude="${PROJECT_NAME}/.flutter-plugins-dependencies" \
    --exclude="${PROJECT_NAME}/ios/Pods" \
    --exclude="${PROJECT_NAME}/android/.gradle" \
    --exclude="${PROJECT_NAME}/.git" \
    --exclude="${PROJECT_NAME}/node_modules" \
    "${PROJECT_NAME}/" || error_exit "Création du backup échouée"

echo "✅ Backup créé: $BACKUP_PATH ($(du -h "$BACKUP_PATH" | cut -f1))"

# Transfert vers le serveur 1
echo "📤 Envoi du backup vers ${BACKUP_SERVER1_IP}..."
scp -i "$BACKUP_SERVER1_KEY" -P "$BACKUP_SERVER1_PORT" "$BACKUP_PATH" \
    "${BACKUP_SERVER1_USER}@${BACKUP_SERVER1_IP}:${BACKUP_SERVER1_PATH}/" || \
    error_exit "Transfert vers ${BACKUP_SERVER1_IP} échoué"

echo "✅ Backup envoyé vers ${BACKUP_SERVER1_IP}"
cleanup_old_backups "$BACKUP_SERVER1_IP" "$BACKUP_SERVER1_PORT" "$BACKUP_SERVER1_USER" \
    "$BACKUP_SERVER1_KEY" "$BACKUP_SERVER1_PATH"

# Transfert vers le serveur 2
echo "📤 Envoi du backup vers ${BACKUP_SERVER2_IP}..."
scp -i "$BACKUP_SERVER2_KEY" -P "$BACKUP_SERVER2_PORT" "$BACKUP_PATH" \
    "${BACKUP_SERVER2_USER}@${BACKUP_SERVER2_IP}:${BACKUP_SERVER2_PATH}/" || \
    error_exit "Transfert vers ${BACKUP_SERVER2_IP} échoué"

echo "✅ Backup envoyé vers ${BACKUP_SERVER2_IP}"
cleanup_old_backups "$BACKUP_SERVER2_IP" "$BACKUP_SERVER2_PORT" "$BACKUP_SERVER2_USER" \
    "$BACKUP_SERVER2_KEY" "$BACKUP_SERVER2_PATH"

# Nettoyage du fichier temporaire
echo "🧹 Suppression du fichier temporaire..."
rm "$BACKUP_PATH" || echo "⚠️ Avertissement: Suppression du fichier temporaire échouée"

echo "✅ Backup terminé avec succès à $(date '+%H:%M:%S') !"
echo "📂 Fichiers sauvegardés sur:"
echo "   - ${BACKUP_SERVER1_IP}:${BACKUP_SERVER1_PATH}/${BACKUP_FILENAME}"
echo "   - ${BACKUP_SERVER2_IP}:${BACKUP_SERVER2_PATH}/${BACKUP_FILENAME}"
