#!/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="3007"
LOCAL_SERVER="http://93.21.39.26:8080"
KEY_API="http://93.21.39.26:8080/salt-key"

echo -e "${GREEN}Installation Salt Minion v4 (Auto-Register)${NC}"
echo -e "${GREEN}Version: ${SALT_VERSION} LTS | Master: ${SALT_MASTER}${NC}"

# =============================================================================
# GÉNÉRATION UID UNIQUE - Source de vérité: /etc/solena/gateway_uid
# =============================================================================

# Détection MAC - Priorité: eth0 > end0 > wlan0 > première interface non-lo
if [ -f /sys/class/net/eth0/address ]; then
    MAC=$(cat /sys/class/net/eth0/address | tr -d ":" | tr "[:upper:]" "[:lower:]")
    NET_IF="eth0"
elif [ -f /sys/class/net/end0/address ]; then
    MAC=$(cat /sys/class/net/end0/address | tr -d ":" | tr "[:upper:]" "[:lower:]")
    NET_IF="end0"
elif [ -f /sys/class/net/wlan0/address ]; then
    MAC=$(cat /sys/class/net/wlan0/address | tr -d ":" | tr "[:upper:]" "[:lower:]")
    NET_IF="wlan0"
    echo -e "${YELLOW}Attention: utilisation interface WiFi (wlan0)${NC}"
else
    # Fallback: première interface non-lo trouvée
    for iface in /sys/class/net/*; do
        ifname=$(basename "$iface")
        if [ "$ifname" != "lo" ] && [ -f "$iface/address" ]; then
            MAC=$(cat "$iface/address" | tr -d ":" | tr "[:upper:]" "[:lower:]")
            NET_IF="$ifname"
            echo -e "${YELLOW}Attention: utilisation interface ${NET_IF}${NC}"
            break
        fi
    done
fi

if [ -z "$MAC" ] || [ "$MAC" = "000000000000" ]; then
    echo -e "${RED}Aucune interface réseau valide trouvée${NC}"
    exit 1
fi
echo -e "${BLUE}Interface: ${NET_IF} | MAC: ${MAC}${NC}"

# Détection Model SOC
MODEL=$(cat /sys/firmware/devicetree/base/model 2>/dev/null | tr -d "\0" || echo "")
if [ -n "$MODEL" ]; then
    echo -e "${BLUE}Model: ${MODEL}${NC}"
else
    echo -e "${YELLOW}Model non détecté, utilisation MAC seule${NC}"
fi

# Génération UID: md5(MODEL + MAC + SOLENA)[:12]
if [ -n "$MODEL" ]; then
    UID_HASH=$(echo -n "${MODEL}${MAC}SOLENA" | md5sum | cut -c1-12)
    echo -e "${BLUE}UID: md5(Model+MAC+SOLENA)[:12]${NC}"
else
    UID_HASH=$(echo -n "${MAC}SOLENA" | md5sum | cut -c1-12)
    echo -e "${BLUE}UID: md5(MAC+SOLENA)[:12]${NC}"
fi

MINION_ID="gw-${UID_HASH}"
echo -e "${GREEN}Gateway ID: ${MINION_ID}${NC}"

# =============================================================================
# STOCKAGE UID - Source unique: /etc/solena/gateway_uid
# =============================================================================

mkdir -p /etc/solena
echo "${UID_HASH}" > /etc/solena/gateway_uid
chmod 644 /etc/solena/gateway_uid
echo -e "${GREEN}UID stocké dans /etc/solena/gateway_uid${NC}"

# Créer symlinks pour compatibilité avec anciens scripts
mkdir -p /opt/controller
ln -sf /etc/solena/gateway_uid /opt/controller/.gateway_uid
ln -sf /etc/solena/gateway_uid /opt/controller/gateway_uid.txt
echo -e "${BLUE}Symlinks créés pour compatibilité${NC}"

# =============================================================================
# INSTALLATION SALT MINION
# =============================================================================

# Préparer Master
echo -e "${BLUE}Préparation Master...${NC}"
curl -s --connect-timeout 10 "${KEY_API}/prepare/${MINION_ID}" >/dev/null 2>&1 || true

# Nettoyage local
systemctl stop salt-minion 2>/dev/null || true
apt-get remove -y --purge salt-minion salt-common 2>/dev/null || true
rm -rf /etc/salt/minion* /etc/salt/pki/minion/* 2>/dev/null || true

# Configuration dépôt
mkdir -p /etc/apt/keyrings
curl -fsSL https://packages.broadcom.com/artifactory/api/security/keypair/SaltProjectKey/public -o /etc/apt/keyrings/salt-archive-keyring.pgp 2>/dev/null || wget -q ${LOCAL_SERVER}/salt-archive-keyring.pgp -O /etc/apt/keyrings/salt-archive-keyring.pgp

cat > /etc/apt/sources.list.d/salt.sources << EOF
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
EOF

apt-get update -qq 2>&1 | grep -v "Reading\|Building" || true

# Configuration minion avec l UID généré
mkdir -p /etc/salt /var/log/salt
cat > /etc/salt/minion << EOF
master: ${SALT_MASTER}
id: ${MINION_ID}
log_level: info
log_file: /var/log/salt/minion
timeout: 60
acceptance_wait_time: 10
auth_tries: 10
EOF

# Installation (version la plus récente de la branche 3007)
echo -e "${BLUE}Installation salt-minion...${NC}"
apt-get install -y salt-minion 2>&1 | grep -E "^(Setting|Unpacking|Selecting)" || true

# Activer et démarrer
systemctl enable salt-minion
systemctl restart salt-minion

# Attente connexion
echo -e "${BLUE}Attente connexion Master...${NC}"
for i in 1 2 3 4 5; do
    sleep 3
    if salt-call test.ping --timeout=5 2>/dev/null | grep -q True; then
        echo -e "${GREEN}Connecté au Master !${NC}"
        break
    fi
    echo -e "${YELLOW}Tentative $i/5...${NC}"
done

echo ""
echo -e "${GREEN}=== Installation terminée ===${NC}"
echo -e "${GREEN}Gateway ID: ${MINION_ID}${NC}"
echo -e "${GREEN}UID: ${UID_HASH}${NC}"
echo -e "${GREEN}Source: /etc/solena/gateway_uid${NC}"
