#!/bin/bash
# ═══════════════════════════════════════════════════════════════
# Script d'Installation Salt Minion 3006.16 via Docker pour Gateway Solena
# ═══════════════════════════════════════════════════════════════
#
# Description:
#   Installation Salt Minion 3006.16 dans container Docker
#   Même version et même méthode que le Salt Master
#   Configuration automatique vers Salt Master (93.21.39.26)
#
# Usage:
#   curl http://93.21.39.26:8080/install-salt-minion-docker-3006.16.sh | bash
#
# Durée: ~2 minutes
# Date: 31/10/2025
# Version: 4.0 (Docker 3006.16)
# ═══════════════════════════════════════════════════════════════

set -e

SALT_MASTER="93.21.39.26"
SALT_VERSION="3006.16"
DOCKER_IMAGE="saltstack/salt:$SALT_VERSION"

echo "═══════════════════════════════════════════════════"
echo "  INSTALLATION SALT MINION 3006.16 - GATEWAY SOLENA"
echo "  (Via Docker - même version que Master)"
echo "═══════════════════════════════════════════════════"
echo ""
echo "📦 Salt Master: $SALT_MASTER"
echo "📌 Version: $SALT_VERSION (Docker)"
echo "🐳 Image: $DOCKER_IMAGE"
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 DOCKER ==========
echo "🐳 Vérification Docker..."

if ! command -v docker >/dev/null 2>&1; then
    echo "❌ Docker n'est pas installé"
    echo "   Installation de Docker..."

    # Installation Docker (Debian/Ubuntu)
    curl -fsSL https://get.docker.com -o /tmp/get-docker.sh
    sh /tmp/get-docker.sh
    rm /tmp/get-docker.sh

    # Démarrer Docker
    systemctl enable docker
    systemctl start docker

    echo "✅ Docker installé"
else
    echo "✅ Docker disponible (version $(docker --version | awk '{print $3}' | tr -d ','))"
fi

# Vérifier que Docker fonctionne
if ! docker ps >/dev/null 2>&1; then
    echo "❌ Docker ne fonctionne pas correctement"
    systemctl restart docker
    sleep 3
fi

echo ""

# ========== 3. ARRÊT CONTAINER EXISTANT ==========
if docker ps -a --format '{{.Names}}' | grep -q '^salt-minion$'; then
    echo "🛑 Arrêt et suppression container salt-minion existant..."
    docker stop salt-minion 2>/dev/null || true
    docker rm salt-minion 2>/dev/null || true
    echo "✅ Container existant supprimé"
    echo ""
fi

# ========== 4. CRÉATION STRUCTURE RÉPERTOIRES ==========
echo "📁 Création structure de configuration..."

# Créer répertoires pour Salt
mkdir -p /etc/salt/pki/minion
mkdir -p /var/cache/salt/minion
mkdir -p /var/log/salt
mkdir -p /opt/controller/{data,scripts,logs}

# Permissions
chmod -R 755 /etc/salt
chmod -R 755 /var/cache/salt
chmod -R 755 /var/log/salt
chmod -R 755 /opt/controller

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

# ========== 5. CONFIGURATION SALT MINION ==========
echo "⚙️  Création configuration Salt Minion..."

# 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)
# Version: $SALT_VERSION (Docker)

# 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
log_level_logfile: info

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

# Performance
multiprocessing: True

# File client
file_client: remote

# Retry options
auth_tries: 7
auth_timeout: 10
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 "   Version: $SALT_VERSION (Docker)"
echo ""

# ========== 6. TÉLÉCHARGEMENT IMAGE DOCKER ==========
echo "📦 Téléchargement image Docker Salt $SALT_VERSION..."

# Vérifier si l'image existe déjà
if docker images | grep -q "saltstack/salt.*$SALT_VERSION"; then
    echo "✅ Image déjà présente"
else
    docker pull $DOCKER_IMAGE 2>&1 | tail -5 || {
        echo "⚠️  Téléchargement depuis Docker Hub échoué"
        echo "   Utilisation de l'image latest..."
        DOCKER_IMAGE="saltstack/salt:latest"
        docker pull $DOCKER_IMAGE
    }
    echo "✅ Image téléchargée"
fi

echo ""

# ========== 7. CRÉATION CONTAINER SALT MINION ==========
echo "🚀 Création container Salt Minion..."

docker run -d \
  --name salt-minion \
  --hostname $MINION_ID \
  --restart=unless-stopped \
  --network host \
  -v /etc/salt:/etc/salt:ro \
  -v /etc/salt/pki:/etc/salt/pki:rw \
  -v /var/cache/salt:/var/cache/salt:rw \
  -v /var/log/salt:/var/log/salt:rw \
  -v /opt/controller:/opt/controller:rw \
  -e SALT_MASTER=$SALT_MASTER \
  -e SALT_MINION_ID=$MINION_ID \
  $DOCKER_IMAGE \
  salt-minion

# Attendre que le container démarre
sleep 3

# Vérifier que le container fonctionne
if docker ps | grep -q salt-minion; then
    echo "✅ Container salt-minion démarré"
else
    echo "❌ Erreur: Container non démarré"
    docker logs salt-minion --tail=20
    exit 1
fi

echo ""

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

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

# Vérifier logs du container
if docker logs salt-minion --tail=50 2>&1 | grep -q "Attempting to connect to"; then
    echo "✅ Minion tente de se connecter au Master"
else
    echo "⚠️  En attente de connexion..."
fi

if docker logs salt-minion --tail=50 2>&1 | grep -q "Authentication accepted"; then
    echo "✅ Authentification réussie (clé acceptée)"
elif docker logs salt-minion --tail=50 2>&1 | 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 ""

# ========== 9. CRÉATION SERVICE SYSTEMD (optionnel) ==========
echo "⚙️  Création service systemd pour auto-restart..."

cat > /etc/systemd/system/salt-minion-docker.service <<'EOFSERVICE'
[Unit]
Description=Salt Minion (Docker)
After=docker.service
Requires=docker.service

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/bin/docker start salt-minion
ExecStop=/usr/bin/docker stop salt-minion
Restart=always

[Install]
WantedBy=multi-user.target
EOFSERVICE

systemctl daemon-reload
systemctl enable salt-minion-docker 2>&1 | grep -v "^Created symlink" || true

echo "✅ Service systemd configuré"
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 "   Version: $SALT_VERSION (Docker)"
echo "   Container: salt-minion"
echo "   Image: $DOCKER_IMAGE"
echo ""
echo "🔧 Commandes utiles:"
echo "   docker ps                          # Voir containers"
echo "   docker logs salt-minion -f         # Logs en temps réel"
echo "   docker exec salt-minion salt-call test.ping  # Test local"
echo "   docker restart salt-minion         # Redémarrer"
echo "   systemctl status salt-minion-docker  # Statut service"
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
