#!/bin/bash
# ═══════════════════════════════════════════════════════════════
# Script d'Installation Salt Minion pour Gateway Solena
# ═══════════════════════════════════════════════════════════════
#
# Description:
#   Installation automatique de Salt Minion sur gateway DSGW-210
#   Configuration automatique vers Salt Master (93.21.39.26)
#   Auto-génération du Minion ID basé sur l'IP
#
# Usage:
#   bash install-salt-minion.sh
#   OU
#   curl http://93.21.39.26/install-salt-minion.sh | bash
#
# Durée: ~2 minutes
# Date: 31/10/2025
# Version: 1.0
# ═══════════════════════════════════════════════════════════════

set -e

SALT_MASTER="93.21.39.26"
SALT_VERSION="3006"

echo "═══════════════════════════════════════════════════"
echo "  INSTALLATION SALT MINION - GATEWAY SOLENA"
echo "═══════════════════════════════════════════════════"
echo ""
echo "📦 Salt Master: $SALT_MASTER"
echo "📌 Version: $SALT_VERSION"
echo ""

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

# Obtenir l'IP principale (exclure loopback et docker)
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 (ex: 192.168.1.60 → gateway-gw60)
LAST_OCTET=$(echo $GATEWAY_IP | awk -F'.' '{print $4}')
MINION_ID="gateway-gw${LAST_OCTET}"

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

# ========== 2. INSTALLATION DÉPENDANCES ==========
echo "📥 Installation des dépendances..."

# Détecter le gestionnaire de paquets
if command -v apt-get >/dev/null 2>&1; then
    PKG_MANAGER="apt-get"
    echo "  Système: Debian/Ubuntu"
elif command -v yum >/dev/null 2>&1; then
    PKG_MANAGER="yum"
    echo "  Système: RedHat/CentOS"
else
    echo "❌ Gestionnaire de paquets non supporté"
    exit 1
fi

# Mise à jour cache paquets
echo "  Mise à jour cache..."
if [ "$PKG_MANAGER" = "apt-get" ]; then
    apt-get update -qq
else
    yum makecache -q
fi

# Installation curl et gnupg si nécessaire
if ! command -v curl >/dev/null 2>&1; then
    echo "  Installation curl..."
    $PKG_MANAGER install -y -qq curl
fi

if ! command -v gpg >/dev/null 2>&1; then
    echo "  Installation gnupg..."
    $PKG_MANAGER install -y -qq gnupg
fi

echo "✅ Dépendances installées"
echo ""

# ========== 3. INSTALLATION SALT MINION ==========
echo "📦 Installation Salt Minion $SALT_VERSION..."

if [ "$PKG_MANAGER" = "apt-get" ]; then
    # Debian/Ubuntu
    if ! command -v salt-minion >/dev/null 2>&1; then
        echo "  Ajout repository SaltStack..."

        # Ajouter clé GPG SaltStack
        curl -fsSL https://repo.saltproject.io/salt/py3/debian/11/amd64/SALT-PROJECT-GPG-PUBKEY-2023.gpg | gpg --dearmor -o /usr/share/keyrings/salt-archive-keyring.gpg

        # Ajouter repository
        echo "deb [signed-by=/usr/share/keyrings/salt-archive-keyring.gpg arch=amd64] https://repo.saltproject.io/salt/py3/debian/11/amd64/$SALT_VERSION bullseye main" > /etc/apt/sources.list.d/salt.list

        # Mise à jour
        apt-get update -qq

        # Installation
        echo "  Installation salt-minion..."
        DEBIAN_FRONTEND=noninteractive apt-get install -y -qq salt-minion
    else
        echo "  ℹ️  Salt Minion déjà installé"
    fi
else
    # RedHat/CentOS
    if ! command -v salt-minion >/dev/null 2>&1; then
        echo "  Ajout repository SaltStack..."
        yum install -y -q https://repo.saltproject.io/salt/py3/redhat/8/x86_64/$SALT_VERSION/salt-repo-$SALT_VERSION.el8.noarch.rpm

        echo "  Installation salt-minion..."
        yum install -y -q salt-minion
    else
        echo "  ℹ️  Salt Minion déjà installé"
    fi
fi

echo "✅ Salt Minion installé"
echo ""

# ========== 4. 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 si inexistant
mkdir -p /etc/salt

# 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 la configuration
echo ""
echo "📋 Configuration Salt Minion:"
echo "   Master: $SALT_MASTER"
echo "   Minion ID: $MINION_ID"
echo "   IP Gateway: $GATEWAY_IP"
echo ""

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

# Créer répertoires principaux
mkdir -p /opt/controller/{data,scripts,logs}

# Permissions
chown -R root:root /opt/controller
chmod -R 755 /opt/controller

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

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

# Recharger systemd
systemctl daemon-reload

# Activer au démarrage
systemctl enable salt-minion

# Démarrer service
systemctl start salt-minion

# Vérifier statut
sleep 2

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 ""

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

# Attendre que le minion envoie sa clé
echo "  Attente envoi clé au Master (10s)..."
sleep 10

# Vérifier logs
if journalctl -u salt-minion --since "1 minute ago" --no-pager | grep -q "Attempting to connect to"; then
    echo "✅ Minion tente de se connecter au Master"
else
    echo "⚠️  Attention: Aucune tentative de connexion détectée"
fi

if journalctl -u salt-minion --since "1 minute ago" --no-pager | grep -q "Authentication accepted"; then
    echo "✅ Authentification réussie (clé déjà acceptée)"
elif journalctl -u salt-minion --since "1 minute ago" --no-pager | grep -q "Waiting for minion key to be accepted"; then
    echo "⏳ Clé envoyée, en attente d'acceptation par le Master..."
    echo "   La clé sera acceptée automatiquement par le Reactor Salt"
else
    echo "ℹ️  Statut de connexion inconnu, vérifiez les logs:"
    echo "   journalctl -u salt-minion -f"
fi

echo ""

# ========== 8. 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)"
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:"
echo "   1. Le Master va accepter automatiquement la clé"
echo "   2. Le déploiement complet sera lancé automatiquement"
echo "   3. La gateway sera opérationnelle dans ~5 minutes"
echo ""
echo "🎯 Pour suivre le déploiement:"
echo "   journalctl -u salt-minion -f"
echo ""

exit 0
