#!/bin/bash
# ═══════════════════════════════════════════════════════════════
# Script d'Installation Salt Minion 3006.16 SIMPLE pour Gateway Solena
# ═══════════════════════════════════════════════════════════════
#
# Description:
#   Installation Salt Minion 3006.16 depuis sources PyPI
#   Minion ID basé sur hostname ou demandé en paramètre
#   Installation native Debian
#
# Usage:
#   curl http://93.21.39.26:8080/install-salt-simple.sh | bash
#   OU avec Minion ID custom:
#   curl http://93.21.39.26:8080/install-salt-simple.sh | bash -s gateway-gw60
#
# Durée: ~3 minutes
# Date: 31/10/2025
# Version: 9.0 (SIMPLE)
# ═══════════════════════════════════════════════════════════════

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 "═══════════════════════════════════════════════════"
echo ""
echo "📦 Salt Master: $SALT_MASTER"
echo "📌 Version: $SALT_VERSION"
echo ""

# ========== 1. DÉTERMINATION MINION ID ==========
echo "🔍 Détermination Minion ID..."

if [ -n "$1" ]; then
    # Minion ID fourni en paramètre
    MINION_ID="$1"
    echo "✅ Minion ID fourni: $MINION_ID"
else
    # Générer depuis hostname
    HOSTNAME=$(hostname)

    # Si hostname est "DUSUN" ou générique, demander
    if [ "$HOSTNAME" = "DUSUN" ] || [ "$HOSTNAME" = "localhost" ]; then
        # Essayer de générer depuis MAC address (dernier octet)
        MAC_LAST=$(ip link show | grep -o 'link/ether [^ ]*' | head -1 | awk '{print $2}' | awk -F':' '{print $6}')
        MINION_ID="gateway-gw${MAC_LAST}"
        echo "✅ Minion ID généré depuis MAC: $MINION_ID"
    else
        MINION_ID="gateway-$HOSTNAME"
        echo "✅ Minion ID basé sur hostname: $MINION_ID"
    fi
fi

echo ""

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

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 installées"
echo ""

# ========== 3. TÉLÉCHARGEMENT SOURCES SALT ==========
echo "📦 Téléchargement sources Salt $SALT_VERSION (19 MB)..."

cd /tmp

if curl -f -s -o /tmp/salt-$SALT_VERSION.tar.gz "$SOURCE_URL"; then
    SOURCE_SIZE=$(du -h /tmp/salt-$SALT_VERSION.tar.gz | cut -f1)
    echo "✅ Sources téléchargées ($SOURCE_SIZE)"
else
    echo "❌ Téléchargement échoué"
    exit 1
fi

echo ""

# ========== 4. INSTALLATION SALT ==========
echo "⚙️  Installation Salt Minion $SALT_VERSION..."
echo "   (compilation en cours, ~2-3 min...)"
echo ""

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

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

# Installer
pip3 install /tmp/salt-$SALT_VERSION.tar.gz 2>&1 | grep -E '(Successfully|Collecting|Installing)' || true

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

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

echo ""

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

mkdir -p /etc/salt/pki/minion /var/cache/salt/minion /var/log/salt /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 ==========
echo "⚙️  Configuration..."

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

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

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 créée"
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 démarré"
else
    echo "❌ Service non démarré"
    systemctl status salt-minion --no-pager
    exit 1
fi

echo ""

# ========== 8. CONNEXION ==========
echo "🔍 Vérification connexion..."
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"
fi

if journalctl -u salt-minion --since "1 min ago" --no-pager 2>/dev/null | grep -q "Authentication accepted"; then
    echo "✅ Authentification OK"
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*)"
fi

echo ""

# ========== 9. RÉCAPITULATIF ==========
echo "═══════════════════════════════════════════════════"
echo "  ✅ INSTALLATION RÉUSSIE"
echo "═══════════════════════════════════════════════════"
echo ""
echo "📊 Minion ID: $MINION_ID"
echo "📊 Master: $SALT_MASTER"
echo "📊 Version: $INSTALLED_VERSION"
echo ""
echo "🔧 Commandes:"
echo "   systemctl status salt-minion"
echo "   journalctl -u salt-minion -f"
echo "   salt-call test.ping"
echo ""
echo "⏭️  Test depuis Master:"
echo "   docker exec salt-master salt '$MINION_ID' test.ping"
echo ""
echo "⏭️  Déploiement auto:"
echo "   docker exec salt-master salt '$MINION_ID' state.apply solena.auto_deploy_gateway"
echo ""

exit 0
