#!/bin/bash
# ═══════════════════════════════════════════════════════════════
# Script d'installation Salt Minion via packages système
# Date: 03/11/2025
# Usage: curl http://93.21.39.26:8080/install-salt-minion-system.sh | bash
# ═══════════════════════════════════════════════════════════════

set -e

# Couleurs
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Configuration
SALT_MASTER="93.21.39.26"

echo -e "${GREEN}═══════════════════════════════════════════════════${NC}"
echo -e "${GREEN}  Installation Salt Minion (packages système)${NC}"
echo -e "${GREEN}  Master: ${SALT_MASTER}${NC}"
echo -e "${GREEN}═══════════════════════════════════════════════════${NC}"
echo ""

# Vérifier si déjà installé
if systemctl is-active --quiet salt-minion 2>/dev/null; then
    echo -e "${YELLOW}⚠️  Salt Minion déjà installé et actif${NC}"
    echo -e "${YELLOW}   Arrêt et réinstallation...${NC}"
    systemctl stop salt-minion
fi

# Désinstaller version précédente si présente
if command -v salt-minion &> /dev/null; then
    echo -e "${YELLOW}🗑️  Désinstallation ancienne version...${NC}"
    apt-get remove -y salt-minion 2>/dev/null || true
    pip3 uninstall -y salt 2>/dev/null || true
fi

# Ajouter repository SaltStack
echo -e "${GREEN}📦 Configuration repository SaltStack...${NC}"
mkdir -p /etc/apt/keyrings
curl -fsSL https://packages.broadcom.com/artifactory/api/security/keypair/SaltProjectKey/public | \
    gpg --dearmor -o /etc/apt/keyrings/salt-archive-keyring.gpg 2>/dev/null || \
    wget -qO- https://repo.saltproject.io/salt/py3/debian/11/amd64/latest/salt-archive-keyring.gpg | \
    gpg --dearmor -o /etc/apt/keyrings/salt-archive-keyring.gpg

# Créer sources.list pour Salt
cat > /etc/apt/sources.list.d/salt.list <<EOF
deb [signed-by=/etc/apt/keyrings/salt-archive-keyring.gpg] https://repo.saltproject.io/salt/py3/debian/11/amd64/latest bullseye main
EOF

# Update et installation
echo -e "${GREEN}⬇️  Installation Salt Minion...${NC}"
apt-get update -qq
apt-get install -y -qq salt-minion 2>&1 | grep -v "^(Reading\|^Unpacking\|^Setting" || true

# Obtenir MAC address pour l'ID du minion
MAC=$(ip link show eth0 2>/dev/null | awk '/ether/ {print $2}' | tr -d ':' || echo "unknown")
MINION_ID="gateway-mac-${MAC}"

# Créer configuration minion
echo -e "${GREEN}⚙️  Configuration Salt Minion (ID: ${MINION_ID})...${NC}"
mkdir -p /etc/salt
cat > /etc/salt/minion <<EOF
# Configuration Salt Minion - Solena Gateway
# Générée automatiquement le $(date)

master: ${SALT_MASTER}
id: ${MINION_ID}

# Auto-reconnexion
autosign_grains_dir: /etc/salt/autosign_grains
random_startup_delay: 5

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

# Performance
multiprocessing: True
ping_interval: 1
EOF

# Créer répertoire logs
mkdir -p /var/log/salt

# Activer et démarrer service
echo -e "${GREEN}🚀 Démarrage du service...${NC}"
systemctl daemon-reload
systemctl enable salt-minion
systemctl restart salt-minion

# Attendre démarrage
sleep 3

# Vérifier status
if systemctl is-active --quiet salt-minion; then
    echo ""
    echo -e "${GREEN}═══════════════════════════════════════════════════${NC}"
    echo -e "${GREEN}✅ Installation réussie !${NC}"
    echo -e "${GREEN}═══════════════════════════════════════════════════${NC}"
    echo ""
    echo -e "${GREEN}📊 Informations:${NC}"
    echo -e "   Minion ID: ${MINION_ID}"
    echo -e "   Master: ${SALT_MASTER}"
    echo -e "   Version: $(salt-minion --version 2>/dev/null | head -1)"
    echo ""
    echo -e "${GREEN}📝 Status:${NC}"
    systemctl status salt-minion --no-pager -l | head -15
    echo ""
    echo -e "${GREEN}🔑 La clé sera acceptée automatiquement par le Master${NC}"
    echo -e "${GREEN}   (pattern: gateway-*)${NC}"
    echo ""
else
    echo -e "${RED}❌ Erreur: Salt Minion non démarré${NC}"
    echo -e "${RED}   Vérifier les logs: journalctl -u salt-minion -n 50${NC}"
    exit 1
fi
