#!/bin/bash
# ══════════════════════════════════════════════════════════════════════
# setup_captive_portal.sh - Version NetworkManager uniquement
# Pas besoin de hostapd ni dnsmasq séparément !
# Usage: sudo bash setup_captive_portal.sh
# ══════════════════════════════════════════════════════════════════════

set -e

AP_IP="192.168.4.1"
AP_INTERFACE="wlan0"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
SERVER_SCRIPT="$SCRIPT_DIR/server.py"
SERVICE_NAME="freecad-usb-server"
SSID="FabLab-FreeCAD"
PASSPHRASE="fablab1234"
CON_NAME="hotspot"

echo "══════════════════════════════════════════════"
echo "  Configuration Hotspot via NetworkManager"
echo "══════════════════════════════════════════════"

if [ "$EUID" -ne 0 ]; then
    echo "❌ Lancez avec: sudo bash setup_captive_portal.sh"
    exit 1
fi

# ── 1. Packages ───────────────────────────────────────────────────────
echo ""
echo "📦 [1/5] Vérification des paquets..."
apt-get install -y network-manager iptables 2>/dev/null || true

# Arrête hostapd et dnsmasq s'ils tournent (on n'en a plus besoin)
systemctl stop hostapd 2>/dev/null || true
systemctl disable hostapd 2>/dev/null || true
systemctl stop dnsmasq 2>/dev/null || true
systemctl disable dnsmasq 2>/dev/null || true
systemctl stop lighttpd 2>/dev/null || true
systemctl disable lighttpd 2>/dev/null || true

echo "   ✓ hostapd/dnsmasq/lighttpd désactivés"

# ── 2. NetworkManager gère wlan0 ─────────────────────────────────────
echo "🔌 [2/5] Configuration NetworkManager..."

# Supprime la règle qui bloquait wlan0
rm -f /etc/NetworkManager/conf.d/no-wlan0.conf

# S'assure que NetworkManager est actif
systemctl enable NetworkManager
systemctl start NetworkManager
sleep 2

echo "   ✓ NetworkManager actif"

# ── 3. Création du hotspot WiFi ───────────────────────────────────────
echo "📡 [3/5] Création du hotspot WiFi '$SSID'..."

# Supprime l'ancienne connexion hotspot si elle existe
nmcli con delete "$CON_NAME" 2>/dev/null || true
sleep 1

# Crée le hotspot
nmcli con add \
    type wifi \
    ifname $AP_INTERFACE \
    con-name "$CON_NAME" \
    autoconnect yes \
    ssid "$SSID"

# Configure le mode Access Point
nmcli con modify "$CON_NAME" \
    802-11-wireless.mode ap \
    802-11-wireless.band bg \
    802-11-wireless.channel 6

# Configure la sécurité WPA2
nmcli con modify "$CON_NAME" \
    wifi-sec.key-mgmt wpa-psk \
    wifi-sec.psk "$PASSPHRASE"

# Configure l'IP fixe et le partage (NetworkManager fait le DHCP automatiquement)
nmcli con modify "$CON_NAME" \
    ipv4.method shared \
    ipv4.addresses "$AP_IP/24"

# Désactive IPv6
nmcli con modify "$CON_NAME" \
    ipv6.method disabled

# Active le hotspot
nmcli con up "$CON_NAME"
sleep 3

# Vérifie que wlan0 a l'IP
IP_CHECK=$(ip addr show $AP_INTERFACE | grep "inet $AP_IP" || true)
if [ -n "$IP_CHECK" ]; then
    echo "   ✓ Hotspot actif - WiFi '$SSID' diffusé sur $AP_IP"
else
    echo "   ⚠️  Hotspot créé mais IP non visible encore, continuons..."
fi

# ── 4. iptables: portail captif ───────────────────────────────────────
echo "🔀 [4/5] Configuration portail captif (iptables)..."

# NetworkManager avec ipv4.method=shared fait déjà du NAT
# On ajoute juste la redirection DNS pour le portail captif
# Redirige toutes les requêtes DNS vers notre serveur
iptables -t nat -F PREROUTING 2>/dev/null || true
iptables -t nat -A PREROUTING -i $AP_INTERFACE -p udp --dport 53 -j REDIRECT --to-port 53 2>/dev/null || true
iptables -t nat -A PREROUTING -i $AP_INTERFACE -p tcp --dport 80 -j REDIRECT --to-port 80 2>/dev/null || true

# Sauvegarde
mkdir -p /etc/iptables
iptables-save > /etc/iptables/rules.v4 2>/dev/null || true

# Restore au démarrage
cat > /etc/networkd-dispatcher/routable.d/50-iptables-restore << 'EOF'
#!/bin/bash
iptables-restore < /etc/iptables/rules.v4
EOF
chmod +x /etc/networkd-dispatcher/routable.d/50-iptables-restore 2>/dev/null || true

echo "   ✓ iptables configuré"

# ── 5. Service freecad-usb-server ────────────────────────────────────
echo "⚙️  [5/5] Configuration du service web..."

cat > /etc/systemd/system/$SERVICE_NAME.service << EOF
[Unit]
Description=Serveur FreeCAD USB Upload + Portail Captif
After=network.target NetworkManager.service
Wants=NetworkManager.service

[Service]
Type=simple
User=root
WorkingDirectory=$SCRIPT_DIR
ExecStart=/usr/bin/python3 $SERVER_SCRIPT
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable $SERVICE_NAME
systemctl restart $SERVICE_NAME
sleep 2

systemctl is-active --quiet $SERVICE_NAME \
    && echo "   ✓ Serveur web actif sur http://$AP_IP" \
    || echo "   ⚠️  Problème serveur web: sudo journalctl -u $SERVICE_NAME -n 20"

# ── Résumé final ──────────────────────────────────────────────────────
echo ""
echo "══════════════════════════════════════════════"
echo "  ✅ Configuration terminée !"
echo "══════════════════════════════════════════════"
echo ""
echo "  📡 WiFi:         $SSID"
echo "  🔑 Mot de passe: $PASSPHRASE"
echo "  🌐 Portail:      http://$AP_IP"
echo ""
echo "  État:"
nmcli con show --active | grep -q "$CON_NAME" \
    && echo "  ✓ Hotspot WiFi actif" \
    || echo "  ✗ Hotspot WiFi PROBLÈME"
systemctl is-active $SERVICE_NAME \
    && echo "  ✓ Serveur web actif" \
    || echo "  ✗ Serveur web PROBLÈME"
echo ""
echo "  Commandes utiles:"
echo "    nmcli con show $CON_NAME          # Info hotspot"
echo "    sudo journalctl -u $SERVICE_NAME -f  # Logs serveur"
echo "    ip addr show $AP_INTERFACE           # Vérifier IP"
echo "══════════════════════════════════════════════"
