#!/bin/bash
# ═══════════════════════════════════════════════════════════════
# Script d'Installation Salt Minion 3006.16 pour Gateway Solena
# ═══════════════════════════════════════════════════════════════
#
# Description:
#   Installation Salt Minion 3006.16
#   Minion ID basé sur adresse MAC Ethernet (unique et stable)
#   Format: gateway-mac-XXXXXXXXXXXX (12 caractères hexa)
#
# Usage:
#   curl http://93.21.39.26:8080/install-salt-mac.sh | bash
#
# Durée: ~3 minutes
# Date: 31/10/2025
# Version: 10.0 (MAC-based ID)
# ═══════════════════════════════════════════════════════════════

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 "  (Minion ID basé sur MAC Ethernet)"
echo "═══════════════════════════════════════════════════"
echo ""
echo "📦 Salt Master: $SALT_MASTER"
echo "📌 Version: $SALT_VERSION"
echo ""

# ========== 1. DÉTECTION MAC ADDRESS ETHERNET ==========
echo "🔍 Détection MAC address Ethernet..."

# Chercher interface Ethernet (eth0, eth1, enp*, eno*, end*)
ETH_INTERFACE=$(ip link show | grep -E '^[0-9]+: (eth|enp|eno|end)' | head -1 | awk -F': ' '{print $2}')

if [ -z "$ETH_INTERFACE" ]; then
    echo "❌ Aucune interface Ethernet trouvée"
    echo "   Interfaces disponibles:"
    ip link show | grep -E '^[0-9]+:' | awk -F': ' '{print "   - " $2}'
    exit 1
fi

# Extraire MAC address
MAC_ADDRESS=$(ip link show $ETH_INTERFACE | grep -o 'link/ether [^ ]*' | awk '{print $2}')

if [ -z "$MAC_ADDRESS" ]; then
    echo "❌ Impossible de récupérer la MAC address de $ETH_INTERFACE"
    exit 1
fi

# Formater MAC (supprimer les : et mettre en minuscules)
MAC_CLEAN=$(echo $MAC_ADDRESS | tr -d ':' | tr 'A-Z' 'a-z')

# Générer Minion ID
MINION_ID="gateway-mac-$MAC_CLEAN"

echo "✅ Interface Ethernet: $ETH_INTERFACE"
echo "✅ MAC Address: $MAC_ADDRESS"
echo "✅ Minion ID: $MINION_ID"
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)
# Interface: $ETH_INTERFACE
# MAC: $MAC_ADDRESS

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-*)"
fi

echo ""

# ========== 9. RÉCAPITULATIF ==========
echo "═══════════════════════════════════════════════════"
echo "  ✅ INSTALLATION RÉUSSIE"
echo "═══════════════════════════════════════════════════"
echo ""
echo "📊 Minion ID: $MINION_ID"
echo "📊 MAC Ethernet: $MAC_ADDRESS ($ETH_INTERFACE)"
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
