#!/bin/bash
set -euo pipefail

echo "== UFW: Application de la Protection HUB (DURCISSEMENT PROGRESSIF) =="

# 1. Vérification de l'interface WireGuard (Existence)
if ! ip link show dev wg0 >/dev/null 2>&1; then
    echo -e "\033[0;31m[ERREUR]\033[0m Interface wg0 introuvable."
    exit 1
fi

# 2. Vérification de l'IPv4 (Le tunnel doit être fonctionnel)
if ! ip -4 addr show dev wg0 | grep -q "inet "; then
    echo -e "\033[0;31m[ERREUR]\033[0m Pas d'IPv4 sur wg0. Tunnel non provisionné."
    exit 1
fi

# 3. Extraction et validation du LAN_SUBNET
LAN_SUBNET=$(grep '^LAN_SUBNET=' /opt/hub/state/env/core.env | cut -d= -f2 | tr -d '\r')

if ! echo "$LAN_SUBNET" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/[0-9]+$'; then
    echo -e "\033[0;31m[ERREUR]\033[0m Format LAN_SUBNET invalide : '$LAN_SUBNET'"
    exit 1
fi

# --- APPLICATION DES RÈGLES ---

# Reset complet pour repartir sur une base propre
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw default deny routed

# ACCÈS SSH (Sécurité intermédiaire)
# Le fallback global est retiré pour supprimer l'exposition publique
# Le LAN est conservé temporairement comme filet de sécurité
ufw allow from "$LAN_SUBNET" to any port 22 proto tcp comment 'SSH LAN'
ufw allow in on wg0 to any port 22 proto tcp comment 'SSH WG'

# SERVICES CORE (DNS pour Pi-hole) - LAN et WG conservés
ufw allow from "$LAN_SUBNET" to any port 53 proto udp comment 'DNS LAN UDP'
ufw allow from "$LAN_SUBNET" to any port 53 proto tcp comment 'DNS LAN TCP'
ufw allow in on wg0 to any port 53 proto udp comment 'DNS WG UDP'
ufw allow in on wg0 to any port 53 proto tcp comment 'DNS WG TCP'

# FLUX WEB (HTTP/HTTPS) - LAN et WG conservés pour les interfaces locales
ufw allow from "$LAN_SUBNET" to any port 80 proto tcp comment 'WEB LAN 80'
ufw allow from "$LAN_SUBNET" to any port 443 proto tcp comment 'WEB LAN 443'
ufw allow in on wg0 to any port 80 proto tcp comment 'WEB WG 80'
ufw allow in on wg0 to any port 443 proto tcp comment 'WEB WG 443'

# ADMINISTRATION (Uniquement via le Tunnel VPN)
ufw allow in on wg0 to any port 81 proto tcp comment 'Admin NPM'
ufw allow in on wg0 to any port 8053 proto tcp comment 'Admin Pi-hole'

# PARTAGE DE FICHIERS (SMB/NAS) - LAN et WG conservés pour l'usage local
ufw allow from "$LAN_SUBNET" to any port 139 proto tcp comment 'SMB LAN 139'
ufw allow from "$LAN_SUBNET" to any port 445 proto tcp comment 'SMB LAN 445'
ufw allow in on wg0 to any port 139 proto tcp comment 'SMB WG 139'
ufw allow in on wg0 to any port 445 proto tcp comment 'SMB WG 445'

# Activation
ufw --force enable
echo
ufw status verbose