#!/bin/bash
set -e
export DEBIAN_FRONTEND=noninteractive

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

SALT_MASTER="93.21.39.26"
SALT_VERSION="3006.*"
LOCAL_SERVER="http://93.21.39.26:8080"

echo -e "${GREEN}═══════════════════════════════════════════════════${NC}"
echo -e "${GREEN}  Installation Salt Minion v2${NC}"
echo -e "${GREEN}  Version: ${SALT_VERSION} LTS${NC}"
echo -e "${GREEN}  Master: ${SALT_MASTER}${NC}"
echo -e "${GREEN}═══════════════════════════════════════════════════${NC}"
echo ""

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

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

echo -e "${BLUE}🔑 Étape 2/6: 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
    wget -q ${LOCAL_SERVER}/salt-archive-keyring.pgp -O /etc/apt/keyrings/salt-archive-keyring.pgp || exit 1
    echo -e "${GREEN}   ✅ Clé GPG (serveur local)${NC}"
else
    echo -e "${GREEN}   ✅ Clé GPG (Broadcom)${NC}"
fi

echo -e "${BLUE}📦 Étape 3/6: Configuration dépôt...${NC}"
cat > /etc/apt/sources.list.d/salt.sources << "EOFSALT"
X-Repolib-Name: Salt Project
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
EOFSALT
echo -e "${GREEN}   ✅ Dépôt configuré${NC}"

echo -e "${BLUE}🔄 Étape 4/6: Mise à jour APT...${NC}"
apt-get update -qq 2>&1 | grep -v "Reading\|Building" || true

echo -e "${BLUE}🔍 Détection MAC...${NC}"
MAC=$(ip -o link show | grep -oP "(?<=ether )[0-9a-f:]+" | head -1 | tr -d ":" | tr "[:upper:]" "[:lower:]")
if [ -z "$MAC" ]; then
    echo -e "${RED}   ❌ MAC non détectée${NC}"
    exit 1
fi
MINION_ID="gateway-${MAC}"
echo -e "${GREEN}   ✅ MAC: ${MAC}${NC}"
echo -e "${GREEN}   ✅ ID: ${MINION_ID}${NC}"

echo -e "${BLUE}⚙️  Étape 5/6: Configuration...${NC}"
mkdir -p /etc/salt /var/log/salt
cat > /etc/salt/minion << "EOFMINION"
master: 93.21.39.26
id: MINION_ID_PLACEHOLDER
log_level: info
log_file: /var/log/salt/minion
timeout: 60
acceptance_wait_time: 10
acceptance_wait_time_max: 60
rejected_retry: True
EOFMINION
sed -i "s/MINION_ID_PLACEHOLDER/${MINION_ID}/" /etc/salt/minion

echo -e "${BLUE}⬇️  Étape 6/6: Installation...${NC}"
apt-get install -y -o Dpkg::Options::="--force-confold" salt-minion salt-common 2>&1 | grep -vE "Reading|Unpacking|Setting" || true

if ! command -v salt-minion &> /dev/null; then
    echo -e "${RED}   ❌ Installation échouée${NC}"
    exit 1
fi

echo -e "${BLUE}🚀 Démarrage...${NC}"
systemctl enable salt-minion >/dev/null 2>&1
systemctl restart salt-minion
sleep 3

if systemctl is-active --quiet salt-minion; then
    echo -e "${GREEN}✅ Installation réussie!${NC}"
    echo -e "${GREEN}   Minion ID: ${MINION_ID}${NC}"
    echo -e "${GREEN}   Master: ${SALT_MASTER}${NC}"
    echo -e "${GREEN}   Auto-accepté (pattern: gateway-*)${NC}"
else
    echo -e "${RED}❌ Service non démarré${NC}"
    exit 1
fi
