#!/bin/bash
# ═══════════════════════════════════════════════════════════════
# Script d'Installation Salt Minion 3006.16 via pip (sources locales)
# ═══════════════════════════════════════════════════════════════
#
# Description:
#   Installation Salt Minion 3006.16 EXACTE depuis sources PyPI
#   Sources hébergées localement (19 MB au lieu de 261 MB)
#   Installation native Debian (pas Docker)
#
# Usage:
#   curl http://93.21.39.26:8080/install-salt-3006.16-pip.sh | bash
#
# Durée: ~3 minutes
# Date: 31/10/2025
# Version: 7.0 (3006.16 pip)
# ═══════════════════════════════════════════════════════════════

set -e

SALT_MASTER="93.21.39.26"
SALT_VERSION="3006.16"
SOURCE_URL="http://93.21.39.26:8080/salt-3006.16.tar.gz"

echo "═══════════════════════════════════════════════════"
echo "  INSTALLATION SALT MINION 3006.16 - GATEWAY SOLENA"
echo "  (Installation native via pip)"
echo "═══════════════════════════════════════════════════"
echo ""
echo "📦 Salt Master: $SALT_MASTER"
echo "📌 Version: $SALT_VERSION"
echo "📥 Source: $SOURCE_URL (19 MB)"
echo ""

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

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

echo "IPs détectées:"
echo "$ALL_IPS" | while read ip; do echo "  - $ip"; done
echo ""

IP_COUNT=$(echo "$ALL_IPS" | wc -l)

if [ "$IP_COUNT" -eq 1 ]; then
    GATEWAY_IP=$(echo "$ALL_IPS" | head -1)
    echo "✅ IP unique: $GATEWAY_IP"
else
    echo "⚠️  Plusieurs IPs. Choisissez l'IP principale:"
    echo ""
    PS3="Numéro (ou 'm' pour manuel): "
    select GATEWAY_IP in $ALL_IPS "Manuel"; do
        if [ "$GATEWAY_IP" = "Manuel" ]; then
            echo "Entrez IP (ex: 192.168.1.60):"
            read GATEWAY_IP
        fi
        if [ -n "$GATEWAY_IP" ]; then
            echo "✅ IP: $GATEWAY_IP"
            break
        fi
    done
fi

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 dépendances Python..."

apt-get update -qq 2>&1 | grep -v "^W:" || true

PACKAGES="python3 python3-pip python3-dev python3-setuptools build-essential curl"
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq $PACKAGES 2>&1 | grep -v "^W:" || true

echo "✅ Dépendances système installées"
echo ""

# ========== 3. TÉLÉCHARGEMENT SOURCES SALT ==========
echo "📦 Téléchargement sources Salt $SALT_VERSION..."
echo "   Source: $SOURCE_URL"
echo ""

cd /tmp

if curl -f --progress-bar -o /tmp/salt-$SALT_VERSION.tar.gz "$SOURCE_URL"; then
    SOURCE_SIZE=$(du -h /tmp/salt-$SALT_VERSION.tar.gz | cut -f1)
    echo ""
    echo "✅ Sources téléchargées ($SOURCE_SIZE)"
else
    echo ""
    echo "❌ Impossible de télécharger les sources"
    exit 1
fi

echo ""

# ========== 4. INSTALLATION SALT VIA PIP ==========
echo "⚙️  Installation Salt Minion $SALT_VERSION via pip3..."
echo "   (peut prendre 2-3 minutes...)"
echo ""

# Arrêter service existant si présent
systemctl stop salt-minion 2>/dev/null || true

# Désinstaller version existante
pip3 uninstall -y salt 2>/dev/null || true

# Installer depuis sources locales
pip3 install /tmp/salt-$SALT_VERSION.tar.gz 2>&1 | tail -10

# Nettoyer
rm -f /tmp/salt-$SALT_VERSION.tar.gz

# Vérifier installation
if command -v salt-minion >/dev/null 2>&1; then
    INSTALLED_VERSION=$(salt-minion --version | head -1 | awk '{print $2}')
    echo ""
    echo "✅ Salt Minion installé (version $INSTALLED_VERSION)"
else
    echo ""
    echo "❌ salt-minion non trouvé"
    exit 1
fi

echo ""

# ========== 5. CRÉATION STRUCTURE ==========
echo "📁 Création structure..."

mkdir -p /etc/salt/pki/minion
mkdir -p /var/cache/salt/minion
mkdir -p /var/log/salt
mkdir -p /opt/controller/{data,scripts,logs}

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

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

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

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

cat > /etc/salt/minion <<EOF
# Configuration Salt Minion - Gateway Solena
# Généré: $(date)
# Version: $SALT_VERSION (pip)

master: $SALT_MASTER
id: $MINION_ID

timeout: 30
random_startup_delay: 5

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

cachedir: /var/cache/salt/minion

multiprocessing: True
file_client: remote

auth_tries: 7
auth_timeout: 10
EOF

echo "✅ Configuration: /etc/salt/minion"
echo ""
echo "📋 Salt Minion:"
echo "   Master: $SALT_MASTER"
echo "   Minion ID: $MINION_ID"
echo "   IP Gateway: $GATEWAY_IP"
echo "   Version: $INSTALLED_VERSION"
echo ""

# ========== 7. SERVICE SYSTEMD ==========
echo "⚙️  Service systemd..."

cat > /etc/systemd/system/salt-minion.service <<'EOFSERVICE'
[Unit]
Description=Salt Minion 3006.16
After=network.target

[Service]
Type=notify
NotifyAccess=all
LimitNOFILE=8192
ExecStart=/usr/local/bin/salt-minion
KillMode=process
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOFSERVICE

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

sleep 3

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

echo ""

# ========== 8. VÉRIFICATION CONNEXION ==========
echo "🔍 Connexion Salt Master..."
echo "   Attente (10s)..."
sleep 10

if journalctl -u salt-minion --since "1 min ago" --no-pager 2>/dev/null | grep -q "Attempting to connect"; then
    echo "✅ Connexion au Master"
else
    echo "⚠️  En attente..."
fi

if journalctl -u salt-minion --since "1 min ago" --no-pager 2>/dev/null | grep -q "Authentication accepted"; then
    echo "✅ Authentification OK (clé auto-acceptée)"
elif journalctl -u salt-minion --since "1 min ago" --no-pager 2>/dev/null | grep -q "Waiting for minion key"; then
    echo "⏳ Clé envoyée (auto-acceptation pattern gateway-gw*)"
else
    echo "ℹ️  Statut inconnu"
fi

echo ""

# ========== 9. RÉCAPITULATIF ==========
echo "═══════════════════════════════════════════════════"
echo "  ✅ INSTALLATION RÉUSSIE"
echo "═══════════════════════════════════════════════════"
echo ""
echo "📊 Informations:"
echo "   Minion ID: $MINION_ID"
echo "   IP Gateway: $GATEWAY_IP"
echo "   Master: $SALT_MASTER"
echo "   Version: $INSTALLED_VERSION"
echo "   Binaire: $(which salt-minion)"
echo ""
echo "🔧 Commandes:"
echo "   systemctl status salt-minion"
echo "   journalctl -u salt-minion -f"
echo "   salt-call test.ping"
echo ""
echo "⏭️  Prochaines étapes:"
echo ""
echo "   1. Test connexion:"
echo "      ssh root@$SALT_MASTER \"docker exec salt-master salt '$MINION_ID' test.ping\""
echo ""
echo "   2. Déploiement auto:"
echo "      ssh root@$SALT_MASTER \"docker exec salt-master salt '$MINION_ID' state.apply solena.auto_deploy_gateway\""
echo ""

exit 0
