#!/bin/bash
# ═══════════════════════════════════════════════════════════════
# Script d'installation Salt Minion FINAL (non-interactif)
# Date: 03/11/2025
# Version: 3006.16 LTS
# Fallback: Utilise serveur local si dépôts externes inaccessibles
# Usage: curl http://93.21.39.26:8080/install-salt-minion-final.sh | bash
# ═══════════════════════════════════════════════════════════════

set -e

# Configuration non-interactive
export DEBIAN_FRONTEND=noninteractive

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

# Configuration
SALT_MASTER="93.21.39.26"
SALT_VERSION="3006.16"
LOCAL_SERVER="http://93.21.39.26:8080"

echo -e "${GREEN}═══════════════════════════════════════════════════${NC}"
echo -e "${GREEN}  Installation Salt Minion FINAL${NC}"
echo -e "${GREEN}  Version: ${SALT_VERSION} LTS${NC}"
echo -e "${GREEN}  Master: ${SALT_MASTER}${NC}"
echo -e "${GREEN}  Mode: Non-interactif${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 pour réinstallation...${NC}"
    systemctl stop salt-minion || true
fi

# Nettoyage complet
echo -e "${BLUE}🗑️  Nettoyage complet...${NC}"
systemctl stop salt-minion 2>/dev/null || true
apt-get remove -y salt-minion salt-common 2>/dev/null || true
pip3 uninstall -y salt 2>/dev/null || true
rm -rf /etc/salt/minion 2>/dev/null || true
rm -rf /etc/salt/minion.d/* 2>/dev/null || true
rm -rf /etc/salt/pki/minion/* 2>/dev/null || true

# Étape 1: Créer répertoire pour clés GPG
echo -e "${BLUE}📁 Étape 1/8: Création répertoire clés GPG...${NC}"
mkdir -p /etc/apt/keyrings

# Étape 2: Télécharger clé GPG (avec fallback)
echo -e "${BLUE}🔑 Étape 2/8: Téléchargement clé GPG...${NC}"
if ! curl -fsSL https://packages.broadcom.com/artifactory/api/security/keypair/SaltProjectKey/public \
    -o /etc/apt/keyrings/salt-archive-keyring.pgp 2>/dev/null; then
    echo -e "${YELLOW}   ⚠️  Serveur Broadcom inaccessible, utilisation serveur local...${NC}"
    if wget -q ${LOCAL_SERVER}/salt-archive-keyring.pgp -O /etc/apt/keyrings/salt-archive-keyring.pgp 2>/dev/null; then
        echo -e "${GREEN}   ✅ Clé GPG récupérée depuis serveur local${NC}"
    else
        echo -e "${RED}   ❌ ERREUR: Impossible de récupérer la clé GPG${NC}"
        exit 1
    fi
else
    echo -e "${GREEN}   ✅ Clé GPG récupérée depuis Broadcom${NC}"
fi

# Étape 3: Configurer dépôt Salt (avec fallback)
echo -e "${BLUE}📦 Étape 3/8: Configuration dépôt APT...${NC}"
if ! curl -fsSL https://github.com/saltstack/salt-install-guide/releases/latest/download/salt.sources \
    -o /etc/apt/sources.list.d/salt.sources 2>/dev/null; then
    echo -e "${YELLOW}   ⚠️  GitHub inaccessible, utilisation serveur local...${NC}"
    if wget -q ${LOCAL_SERVER}/salt.sources -O /etc/apt/sources.list.d/salt.sources 2>/dev/null; then
        echo -e "${GREEN}   ✅ Configuration dépôt récupérée depuis serveur local${NC}"
    else
        echo -e "${YELLOW}   Configuration manuelle du dépôt...${NC}"
        cat > /etc/apt/sources.list.d/salt.sources <<'EOF'
X-Repolib-Name: Salt Project
Description: Salt Project Repository
Enabled: yes
Types: deb
URIs: https://packages.broadcom.com/artifactory/saltproject-deb
Signed-By: /etc/apt/keyrings/salt-archive-keyring.pgp
Suites: stable
Components: main
EOF
        echo -e "${GREEN}   ✅ Dépôt configuré manuellement${NC}"
    fi
else
    echo -e "${GREEN}   ✅ Configuration dépôt récupérée depuis GitHub${NC}"
fi

# Étape 4: Mettre à jour index des paquets
echo -e "${BLUE}🔄 Étape 4/8: Mise à jour index APT...${NC}"
apt-get update -qq 2>&1 | grep -v "^(Reading\|^Building" || true

# Étape 5: Épingler version Salt 3006 LTS
echo -e "${BLUE}📌 Étape 5/8: Épinglage version 3006 LTS...${NC}"
cat > /etc/apt/preferences.d/salt-pin-1001 <<EOF
Package: salt-*
Pin: version 3006.*
Pin-Priority: 1001
EOF

# Obtenir MAC address AVANT l'installation
MAC=$(ip link show eth0 2>/dev/null | awk '/ether/ {print $2}' | tr -d ':' || \
      ip link show end0 2>/dev/null | awk '/ether/ {print $2}' | tr -d ':' || \
      ip link show enp 2>/dev/null | awk '/ether/ {print $2}' | tr -d ':' || \
      echo "unknown")
MINION_ID="gateway-mac-${MAC}"

# Créer configuration AVANT l'installation pour éviter les questions
echo -e "${BLUE}⚙️  Pré-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)
# Version: ${SALT_VERSION}

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

# Timeouts
timeout: 60
gather_job_timeout: 60

# Retry
acceptance_wait_time: 10
acceptance_wait_time_max: 60
rejected_retry: True
EOF

# Créer répertoires nécessaires
mkdir -p /var/log/salt
mkdir -p /etc/salt/autosign_grains

# Étape 6: Installer salt-minion (NON-INTERACTIF)
echo -e "${BLUE}⬇️  Étape 6/8: Installation salt-minion ${SALT_VERSION} (non-interactif)...${NC}"
apt-get install -y -o Dpkg::Options::="--force-confold" -o Dpkg::Options::="--force-confdef" \
    salt-minion=${SALT_VERSION} 2>&1 | grep -v "^(Reading\|^Unpacking\|^Setting\|^Selecting" || true

# Vérifier installation
if ! command -v salt-minion &> /dev/null; then
    echo -e "${RED}   ❌ Installation échouée${NC}"
    echo -e "${RED}   Vérifier connectivité réseau et DNS${NC}"
    exit 1
else
    echo -e "${GREEN}   ✅ Salt Minion installé${NC}"
fi

# Étape 7: S'assurer que la configuration est correcte
echo -e "${BLUE}📝 Étape 7/8: Vérification configuration...${NC}"
if [ -f /etc/salt/minion ]; then
    if grep -q "master: ${SALT_MASTER}" /etc/salt/minion && grep -q "id: ${MINION_ID}" /etc/salt/minion; then
        echo -e "${GREEN}   ✅ Configuration OK${NC}"
    else
        echo -e "${YELLOW}   ⚠️  Configuration modifiée, restauration...${NC}"
        cat > /etc/salt/minion <<EOF
master: ${SALT_MASTER}
id: ${MINION_ID}
autosign_grains_dir: /etc/salt/autosign_grains
random_startup_delay: 5
log_level: info
log_file: /var/log/salt/minion
multiprocessing: True
ping_interval: 1
timeout: 60
gather_job_timeout: 60
acceptance_wait_time: 10
acceptance_wait_time_max: 60
rejected_retry: True
EOF
    fi
fi

# Étape 8: Démarrer service
echo -e "${BLUE}🚀 Étape 8/8: Démarrage service...${NC}"
systemctl daemon-reload
systemctl enable salt-minion
systemctl restart salt-minion

# Attendre démarrage
sleep 5

# 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}"
    INSTALLED_VERSION=$(salt-minion --version 2>/dev/null | head -1 || echo "Version inconnue")
    echo -e "   Version: ${INSTALLED_VERSION}"
    echo ""
    echo -e "${GREEN}📝 Status:${NC}"
    systemctl status salt-minion --no-pager -l | head -15
    echo ""
    echo -e "${GREEN}🔑 Prochaines étapes:${NC}"
    echo -e "   ${BLUE}# Depuis Salt Master (93.21.39.26):${NC}"
    echo -e "   docker exec salt-master salt '${MINION_ID}' test.ping"
    echo -e "   docker exec salt-master salt '${MINION_ID}' state.apply solena.auto_deploy_gateway_v4"
    echo ""
else
    echo ""
    echo -e "${RED}═══════════════════════════════════════════════════${NC}"
    echo -e "${RED}❌ Erreur: Salt Minion non démarré${NC}"
    echo -e "${RED}═══════════════════════════════════════════════════${NC}"
    echo ""
    echo -e "${RED}🔍 Diagnostics:${NC}"
    systemctl status salt-minion --no-pager -l 2>&1 | tail -20
    echo ""
    echo -e "${RED}📋 Commandes de dépannage:${NC}"
    echo -e "   journalctl -u salt-minion -n 50 --no-pager"
    echo -e "   salt-minion --version"
    echo -e "   cat /etc/salt/minion"
    echo ""
    exit 1
fi
