#!/bin/bash
# ═══════════════════════════════════════════════════════════════
# Script d'Installation Salt Minion OFFLINE pour Gateway Solena
# ═══════════════════════════════════════════════════════════════
#
# Description:
#   Installation Salt Minion depuis package .deb hébergé localement
#   Évite les problèmes DNS et dépendances externes
#   Configuration automatique vers Salt Master (93.21.39.26)
#
# Usage:
#   curl http://93.21.39.26:8080/install-salt-minion-offline.sh | bash
#
# Durée: ~1 minute
# Date: 31/10/2025
# Version: 2.0 (Offline)
# ═══════════════════════════════════════════════════════════════

set -e

SALT_MASTER="93.21.39.26"
PACKAGE_URL="http://93.21.39.26:8080/salt-minion_3007.8_amd64.deb"

echo "═══════════════════════════════════════════════════"
echo "  INSTALLATION SALT MINION - GATEWAY SOLENA"
echo "  (MODE OFFLINE - Package local)"
echo "═══════════════════════════════════════════════════"
echo ""
echo "📦 Salt Master: $SALT_MASTER"
echo "📥 Package: $PACKAGE_URL"
echo ""

# ========== 1. DÉTECTION IP GATEWAY ==========
echo "🔍 Détection de l'IP de la gateway..."

GATEWAY_IP=$(ip -4 addr show | grep -oP '(?<=inet\s)\d+(\.\d+){3}' | grep -v '127.0.0.1' | grep -v '172.' | head -1)

if [ -z "$GATEWAY_IP" ]; then
    echo "❌ Impossible de détecter l'IP de la gateway"
    exit 1
fi

echo "✅ IP détectée: $GATEWAY_IP"

# Générer Minion ID basé sur l'IP
LAST_OCTET=$(echo $GATEWAY_IP | awk -F'.' '{print $4}')
MINION_ID="gateway-gw${LAST_OCTET}"

echo "🏷️  Minion ID: $MINION_ID"
echo ""

# ========== 2. VÉRIFICATION SI DÉJÀ INSTALLÉ ==========
if command -v salt-minion >/dev/null 2>&1; then
    CURRENT_VERSION=$(salt-minion --version 2>/dev/null | head -1 | awk '{print $2}')
    echo "ℹ️  Salt Minion déjà installé (version $CURRENT_VERSION)"
    echo "   Mise à jour de la configuration..."
else
    # ========== 3. INSTALLATION DÉPENDANCES ==========
    echo "📥 Vérification des dépendances..."

    # Installer curl si manquant
    if ! command -v curl >/dev/null 2>&1; then
        echo "  Installation curl..."
        apt-get update -qq 2>&1 | grep -v "^W:" || true
        apt-get install -y -qq curl 2>&1 | grep -v "^W:" || true
    fi

    echo "✅ Dépendances OK"
    echo ""

    # ========== 4. TÉLÉCHARGEMENT PACKAGE SALT ==========
    echo "📦 Téléchargement package Salt Minion..."

    cd /tmp

    if curl -f -s -o /tmp/salt-minion.deb "$PACKAGE_URL"; then
        echo "✅ Package téléchargé ($(du -h /tmp/salt-minion.deb | cut -f1))"
    else
        echo "❌ Erreur: Impossible de télécharger le package"
        echo "   URL: $PACKAGE_URL"
        echo "   Vérifiez que le serveur $SALT_MASTER est accessible"
        exit 1
    fi

    echo ""

    # ========== 5. INSTALLATION PACKAGE ==========
    echo "⚙️  Installation Salt Minion..."

    # Mettre à jour cache apt (pour dépendances)
    echo "  Mise à jour cache apt..."
    apt-get update -qq 2>&1 | grep -v "^W:" || true

    # Installer le package (avec dépendances automatiques)
    echo "  Installation du package .deb..."
    if dpkg -i /tmp/salt-minion.deb 2>&1 | grep -v "^W:" || true; then
        echo "  Package installé"
    fi

    # Résoudre les dépendances manquantes si nécessaire
    echo "  Résolution des dépendances..."
    apt-get install -f -y -qq 2>&1 | grep -v "^W:" || true

    # Vérifier que salt-minion est maintenant installé
    if command -v salt-minion >/dev/null 2>&1; then
        INSTALLED_VERSION=$(salt-minion --version | head -1 | awk '{print $2}')
        echo "✅ Salt Minion installé (version $INSTALLED_VERSION)"
    else
        echo "❌ Erreur: Installation échouée"
        exit 1
    fi

    # Nettoyer
    rm -f /tmp/salt-minion.deb

    echo ""
fi

# ========== 6. CONFIGURATION SALT MINION ==========
echo "⚙️  Configuration Salt Minion..."

# Arrêter service si en cours
if systemctl is-active --quiet salt-minion 2>/dev/null; then
    echo "  Arrêt service salt-minion..."
    systemctl stop salt-minion
fi

# Créer répertoire config
mkdir -p /etc/salt

# Backup ancienne config si existe
if [ -f /etc/salt/minion ]; then
    cp /etc/salt/minion /etc/salt/minion.backup.$(date +%Y%m%d_%H%M%S)
fi

# Configuration minion
cat > /etc/salt/minion <<EOF
# Configuration Salt Minion - Gateway Solena
# Généré automatiquement le $(date)

# Salt Master
master: $SALT_MASTER

# Minion ID
id: $MINION_ID

# Timeouts
timeout: 30
random_startup_delay: 5

# Logs
log_level: info
log_file: /var/log/salt/minion

# Cache
cachedir: /var/cache/salt/minion

# Performance
multiprocessing: True
EOF

echo "✅ Configuration créée: /etc/salt/minion"

# Afficher config
echo ""
echo "📋 Configuration Salt Minion:"
echo "   Master: $SALT_MASTER"
echo "   Minion ID: $MINION_ID"
echo "   IP Gateway: $GATEWAY_IP"
echo ""

# ========== 7. CRÉATION STRUCTURE RÉPERTOIRES ==========
echo "📁 Création structure /opt/controller..."

mkdir -p /opt/controller/{data,scripts,logs}
chown -R root:root /opt/controller
chmod -R 755 /opt/controller

echo "✅ Structure créée"
echo ""

# ========== 8. DÉMARRAGE SALT MINION ==========
echo "🚀 Démarrage Salt Minion..."

# Recharger systemd
systemctl daemon-reload

# Activer au démarrage
systemctl enable salt-minion 2>&1 | grep -v "^Created symlink" || true

# Démarrer service
systemctl start salt-minion

# Vérifier statut
sleep 3

if systemctl is-active --quiet salt-minion; then
    echo "✅ Service salt-minion démarré"
else
    echo "❌ Erreur: Service salt-minion non démarré"
    systemctl status salt-minion --no-pager -l
    exit 1
fi

echo ""

# ========== 9. VÉRIFICATION CONNEXION ==========
echo "🔍 Vérification connexion Salt Master..."

echo "  Attente envoi clé au Master (10s)..."
sleep 10

# Vérifier logs
if journalctl -u salt-minion --since "1 minute ago" --no-pager 2>/dev/null | grep -q "Attempting to connect to"; then
    echo "✅ Minion tente de se connecter au Master"
else
    echo "⚠️  En attente de connexion..."
fi

if journalctl -u salt-minion --since "1 minute ago" --no-pager 2>/dev/null | grep -q "Authentication accepted"; then
    echo "✅ Authentification réussie (clé acceptée)"
elif journalctl -u salt-minion --since "1 minute ago" --no-pager 2>/dev/null | grep -q "Waiting for minion key to be accepted"; then
    echo "⏳ Clé envoyée, en attente d'acceptation..."
else
    echo "ℹ️  Statut de connexion inconnu"
fi

echo ""

# ========== 10. RÉCAPITULATIF ==========
echo "═══════════════════════════════════════════════════"
echo "  ✅ INSTALLATION RÉUSSIE"
echo "═══════════════════════════════════════════════════"
echo ""
echo "📊 Informations:"
echo "   Minion ID: $MINION_ID"
echo "   IP Gateway: $GATEWAY_IP"
echo "   Salt Master: $SALT_MASTER"
echo "   Service: salt-minion (actif)"
if [ -n "$INSTALLED_VERSION" ]; then
    echo "   Version: $INSTALLED_VERSION"
fi
echo ""
echo "🔧 Commandes utiles:"
echo "   systemctl status salt-minion    # Statut service"
echo "   journalctl -u salt-minion -f    # Logs en temps réel"
echo "   salt-call test.ping             # Test local"
echo ""
echo "⏳ Prochaines étapes (sur le Salt Master):"
echo ""
echo "   1. Accepter la clé:"
echo "      docker exec salt-master salt-key -a $MINION_ID -y"
echo ""
echo "   2. Tester la connexion:"
echo "      docker exec salt-master salt '$MINION_ID' test.ping"
echo ""
echo "   3. Lancer le déploiement automatique:"
echo "      docker exec salt-master salt '$MINION_ID' state.apply solena.auto_deploy_gateway"
echo ""
echo "📝 Ou en une seule commande depuis votre PC:"
echo "   ssh root@$SALT_MASTER \"docker exec salt-master bash -c 'salt-key -a $MINION_ID -y && salt \\\"$MINION_ID\\\" state.apply solena.auto_deploy_gateway'\""
echo ""

exit 0
