#!/bin/bash
# ============================================================
#  REBOOTLY ARCHIVES — Nginx Reverse Proxy Sécurisé
#  À lancer sur le serveur VPN 51.178.43.243
#
#  - Nginx reverse proxy HTTPS
#  - Certificat wildcard *.rebootly.cloud
#    via acme.sh + API cPanel o2switch (DNS challenge)
#  - Headers sécurité (HSTS, CSP, X-Frame...)
#  - Rate limiting anti-bruteforce
#  - Intégration fail2ban existant
#
#  Usage :
#    bash 07-nginx-proxy.sh
#
#  Ajouter un client (Nginx + SMTP journal) :
#    bash 07-nginx-proxy.sh --add-client archives.client.rebootly.cloud 10.10.0.101
#
#  → Attribue automatiquement un port SMTP journal (2525+n)
#  → Crée les règles iptables DNAT + MASQUERADE + INPUT
#  → Affiche la config Postfix à copier chez le client
# ============================================================

set -euo pipefail

GREEN='\033[0;32m'; CYAN='\033[0;36m'; YELLOW='\033[1;33m'
RED='\033[0;31m'; BOLD='\033[1m'; NC='\033[0m'
ok()      { echo -e "${GREEN}[✓]${NC} $1"; }
section() { echo -e "\n${CYAN}${BOLD}┌─ $1 ──${NC}"; }
warn()    { echo -e "${YELLOW}[!]${NC} $1"; }
err()     { echo -e "${RED}[✗]${NC} $1"; exit 1; }
info()    { echo -e "    ${CYAN}→${NC} $1"; }

[[ $EUID -ne 0 ]] && err "Root requis"

NGINX_DIR="/etc/nginx"
VHOSTS_DIR="$NGINX_DIR/sites-available"
ENABLED_DIR="$NGINX_DIR/sites-enabled"
CERTS_DIR="/etc/ssl/rebootly"
LETSENCRYPT_WEBROOT="/var/www/letsencrypt"

# ─── Charger la config Wizard si disponible ─────────────────
SCRIPTS_DIR="$(dirname "$0")"
VPN_CONF="${SCRIPTS_DIR}/vpn.conf"
[[ -f "$VPN_CONF" ]] && source "$VPN_CONF"

# Valeurs par défaut si vpn.conf absent (compat SaaS)
DOMAIN="${VPN_BASE_DOMAIN:-rebootly.cloud}"
WG_VPN_IP="${WG0_SERVER_IP:-10.38.100.1}"
VPN_PUBLIC_IP="${VPN_PUBLIC_IP:-51.178.43.243}"
SMTP_JOURNAL_BASE=2525

# ─── Journalisation SMTP — attribution port + règles iptables ───────────────
# Usage : setup_smtp_journal <lxc_ip>
# Retourne (via echo) le port attribué
setup_smtp_journal() {
  local VM_IP="$1"

  # Vérifier si une règle DNAT existe déjà pour cette IP
  local EXISTING
  EXISTING=$(iptables -t nat -L PREROUTING -n 2>/dev/null | \
    grep "DNAT" | grep "${VM_IP}:25" | \
    grep -oP 'dpt:\K[0-9]+' | head -1 || true)
  if [[ -n "$EXISTING" ]]; then
    echo "$EXISTING"
    return 0
  fi

  # Trouver le prochain port disponible (2525, 2526, ...)
  local PORT=$SMTP_JOURNAL_BASE
  while iptables -t nat -L PREROUTING -n 2>/dev/null | grep -q "dpt:${PORT}"; do
    PORT=$((PORT + 1))
  done

  # DNAT : port externe → LXC:25
  iptables -t nat -A PREROUTING -p tcp --dport "$PORT" \
    -j DNAT --to-destination "${VM_IP}:25"

  # MASQUERADE : évite le routage asymétrique (réponses LXC → VPN → client)
  iptables -t nat -A POSTROUTING -p tcp -d "$VM_IP" --dport 25 \
    -j MASQUERADE

  # FORWARD : autoriser le trafic vers le LXC port 25
  iptables -I FORWARD 1 -p tcp -d "$VM_IP" --dport 25 -j ACCEPT
  iptables -I FORWARD 1 -p tcp -s "$VM_IP" --sport 25 \
    -m state --state ESTABLISHED,RELATED -j ACCEPT

  # INPUT : accepter sur le port journal (avant les chaînes UFW)
  iptables -I INPUT 1 -p tcp --dport "$PORT" -j ACCEPT

  # Persister les règles
  mkdir -p /etc/iptables
  iptables-save > /etc/iptables/rules.v4

  echo "$PORT"
}

add_vhost() {
  local VHOST="$1"
  local VM_IP="$2"
  local CLIENT_WG_IP="${3:-}"
  local CONF="$VHOSTS_DIR/${VHOST}.conf"

  # Règle d'accès : IP WireGuard du client uniquement, sinon sous-réseau WG entier
  local ALLOW_RULE=""
  if [[ -n "$CLIENT_WG_IP" ]]; then
    ALLOW_RULE="    # Accès restreint à l'IP WireGuard du client
    allow ${CLIENT_WG_IP};
    deny all;"
  else
    ALLOW_RULE="    # Accès restreint au sous-réseau WireGuard
    allow 10.38.96.0/21;
    deny all;"
  fi

  # Chemins cert : Let's Encrypt ou fallback auto-signé
  local CERT_FULL="/etc/letsencrypt/live/${VHOST}/fullchain.pem"
  local CERT_KEY="/etc/letsencrypt/live/${VHOST}/privkey.pem"
  if [[ ! -f "$CERT_FULL" ]]; then
    # Fallback auto-signé (remplacé par certbot juste après)
    CERT_FULL="${CERTS_DIR}/fullchain.pem"
    CERT_KEY="${CERTS_DIR}/privkey.pem"
  fi

  cat > "$CONF" << EOF
# Rebootly Archives — $VHOST → $VM_IP
# Généré le $(date '+%Y-%m-%d %H:%M')
# Accès : WireGuard uniquement (listen sur ${WG_VPN_IP})

server {
    listen ${WG_VPN_IP}:443 ssl;
    http2 on;
    server_name $VHOST;

    ssl_certificate     ${CERT_FULL};
    ssl_certificate_key ${CERT_KEY};
    ssl_stapling off;

    include snippets/rebootly-security.conf;

    access_log /var/log/nginx/${VHOST}-access.log;
    error_log  /var/log/nginx/${VHOST}-error.log warn;

${ALLOW_RULE}

    # Rate limiting global
    limit_req zone=global burst=50 nodelay;

    # Rate limiting login anti-bruteforce
    location ~ ^/(index\.php|login) {
        limit_req zone=login burst=3 nodelay;
        proxy_pass http://${VM_IP};
        include snippets/rebootly-proxy.conf;
    }

    # SSE / API — pas de buffering pour les streams (Ariana AI, imports...)
    location /rb-api/ {
        proxy_pass http://${VM_IP}/rb-api/;
        include snippets/rebootly-proxy.conf;
        proxy_buffering off;
        proxy_cache off;
    }

    # Proxy principal
    location / {
        proxy_pass http://${VM_IP};
        include snippets/rebootly-proxy.conf;
    }

    # Bloquer fichiers sensibles
    location ~ /\.(ht|git|env) {
        deny all;
        return 404;
    }
}
EOF

  ln -sf "$CONF" "$ENABLED_DIR/"
  nginx -t && systemctl reload nginx
  ok "Vhost créé : https://$VHOST → $VM_IP (WireGuard only)"

  # ── Certificat Let's Encrypt — HTTP-01 webroot ───────────────
  mkdir -p "$LETSENCRYPT_WEBROOT"
  if command -v certbot &>/dev/null; then
    info "Génération certificat Let's Encrypt pour $VHOST (HTTP-01)..."
    # S'assurer que le bloc HTTP sert le webroot pour le challenge
    local HTTP_CHALLENGE_CONF="$NGINX_DIR/conf.d/letsencrypt-challenge.conf"
    if [[ ! -f "$HTTP_CHALLENGE_CONF" ]]; then
      cat > "$HTTP_CHALLENGE_CONF" << 'CHALLENGEEOF'
# Servi en HTTP pour les challenges ACME Let's Encrypt
server {
    listen 80;
    listen [::]:80;
    server_name _;
    location /.well-known/acme-challenge/ {
        root /var/www/letsencrypt;
        allow all;
    }
    location / { return 301 https://$host$request_uri; }
}
CHALLENGEEOF
      # Supprimer l'ancien redirect HTTP si présent
      rm -f "$ENABLED_DIR/00-redirect-http.conf"
      nginx -t && systemctl reload nginx
    fi

    if certbot certonly --webroot -w "$LETSENCRYPT_WEBROOT" \
        -d "$VHOST" --non-interactive --agree-tos \
        --email "admin@${DOMAIN}" --quiet 2>&1; then
      local LE_FULL="/etc/letsencrypt/live/${VHOST}/fullchain.pem"
      local LE_KEY="/etc/letsencrypt/live/${VHOST}/privkey.pem"
      # Mettre à jour le vhost VPN avec le vrai cert
      sed -i "s|ssl_certificate .*|ssl_certificate     ${LE_FULL};|" "$CONF"
      sed -i "s|ssl_certificate_key .*|ssl_certificate_key ${LE_KEY};|" "$CONF"
      # Ajouter bloc public (0.0.0.0:443) → page sécurité VPN avec cert valide
      local PUBLIC_BLOCK
      PUBLIC_BLOCK="# Bloc public — page securite VPN (acces sans VPN actif)
server {
    listen 443 ssl;
    server_name ${VHOST};
    ssl_certificate     ${LE_FULL};
    ssl_certificate_key ${LE_KEY};
    ssl_stapling off;
    root /var/www/rebootly-security;
    index index.html;
    location / { try_files \$uri /index.html =404; }
}

"
      # Insérer le bloc public en tête du fichier vhost
      local TMP_CONF
      TMP_CONF=$(mktemp)
      echo "$PUBLIC_BLOCK" > "$TMP_CONF"
      cat "$CONF" >> "$TMP_CONF"
      mv "$TMP_CONF" "$CONF"
      nginx -t && systemctl reload nginx
      ok "Certificat Let's Encrypt installé pour $VHOST"
      ok "Page securite publique activee pour $VHOST (sans VPN)"
    else
      warn "certbot échoué — vhost actif avec cert auto-signé (DNS propagé ?)"
      warn "Relancer manuellement : certbot certonly --webroot -w /var/www/letsencrypt -d $VHOST"
    fi
  else
    warn "certbot non installé — apt-get install -y certbot puis relancer"
  fi

  # ── Split-DNS : résout vhost → 10.38.100.1 (nginx VPN) via dnsmasq ───────────
  # Les clients WireGuard accèdent via nginx (SSL), pas directement au LXC
  local DNS_CONF="/etc/dnsmasq.d/rebootly.conf"
  if [[ -f "$DNS_CONF" ]]; then
    sed -i "/^address=\/${VHOST//\./\\.}\//d" "$DNS_CONF" 2>/dev/null || true
    echo "address=/${VHOST}/${WG_VPN_IP}" >> "$DNS_CONF"
    systemctl restart dnsmasq 2>/dev/null || true
    ok "Split-DNS : $VHOST → ${WG_VPN_IP} (nginx VPN via dnsmasq)"
  fi

  # ── Journalisation SMTP ───────────────────────────────────────────────────────
  local SMTP_PORT
  SMTP_PORT=$(setup_smtp_journal "$VM_IP")
  ok "Journalisation SMTP : ${VPN_PUBLIC_IP}:${SMTP_PORT} → ${VM_IP}:25"

  echo ""
  echo -e "  ${YELLOW}DNS public à créer dans cPanel o2switch :${NC}"
  echo -e "  Type  : A"
  echo -e "  Nom   : ${VHOST%%.$DOMAIN}"
  echo -e "  Valeur: ${VM_IP}  ← IP privée LXC (injoignable sans VPN)"
  echo -e "  TTL   : 3600"
  echo ""
  echo -e "  ${CYAN}Journalisation SMTP (BCC serveur mail → Mailpiler) :${NC}"
  echo -e "  Adresse journal  : journal@archive-journal.rebootly.local"
  echo -e "  Serveur SMTP     : [${VPN_PUBLIC_IP}]:${SMTP_PORT}"
  echo -e "  → Postfix always_bcc = journal@archive-journal.rebootly.local"
  echo -e "  → Transport map  : journal@archive-journal.rebootly.local smtp:[${VPN_PUBLIC_IP}]:${SMTP_PORT}"
  echo ""
}

# ─── Mode --add-client ───────────────────────────────────────
if [[ "${1:-}" == "--add-client" ]]; then
  VHOST="${2:-}"; VM_IP="${3:-}"; CLIENT_WG_IP="${4:-}"
  [[ -z "$VHOST" || -z "$VM_IP" ]] && \
    err "Usage : bash $0 --add-client archives.client.rebootly.cloud 10.10.0.101 [10.38.100.2]"
  add_vhost "$VHOST" "$VM_IP" "$CLIENT_WG_IP"
  exit 0
fi

# ─── Installation initiale ───────────────────────────────────
clear
echo -e "${CYAN}${BOLD}"
echo "  ┌─────────────────────────────────────────────────────┐"
echo "  │  Rebootly — Nginx Reverse Proxy + SSL Wildcard      │"
echo "  │  DNS via cPanel o2switch                            │"
echo "  └─────────────────────────────────────────────────────┘"
echo -e "${NC}"
echo ""
echo -e "  Il te faut les infos cPanel o2switch où est géré"
echo -e "  la zone DNS de ${BOLD}rebootly.cloud${NC}"
echo ""
read -p "  URL cPanel (ex: https://moncompte.o2switch.net:2083) : " CPANEL_URL
read -p "  Identifiant cPanel                                   : " CPANEL_USER
read -s -p "  Mot de passe cPanel                                  : " CPANEL_PASS
echo ""
[[ -z "$CPANEL_URL" || -z "$CPANEL_USER" || -z "$CPANEL_PASS" ]] && \
  err "Toutes les infos cPanel sont obligatoires"

# Nettoyer l'URL (retirer le slash final)
CPANEL_URL="${CPANEL_URL%/}"

echo ""
read -p "  Continuer ? [o/N] " -n 1 -r; echo
[[ ! $REPLY =~ ^[oO]$ ]] && echo "Annulé." && exit 0

# ─── 1. Nginx ────────────────────────────────────────────────
section "1/5 — Installation Nginx"
apt-get update -qq
apt-get install -y nginx curl socat
ok "Nginx installé"

# ─── 2. acme.sh ──────────────────────────────────────────────
section "2/5 — Installation acme.sh"
if [[ -f "$ACME_DIR/acme.sh" ]]; then
  ok "acme.sh déjà installé"
else
  curl -fsSL https://get.acme.sh | sh -s email=admin@${DOMAIN}
  source ~/.bashrc 2>/dev/null || true
fi
ok "acme.sh prêt"

# ─── 3. Certificat wildcard via cPanel DNS ───────────────────
section "3/5 — Certificat wildcard *.${DOMAIN} (DNS cPanel)"
mkdir -p "$CERTS_DIR"

info "Challenge DNS via API cPanel o2switch..."
info "Domaine : *.${DOMAIN} + ${DOMAIN}"
info "Propagation DNS ~60s — patience..."

export CPANEL_URL="$CPANEL_URL"
export CPANEL_USERNAME="$CPANEL_USER"
export CPANEL_PASSWORD="$CPANEL_PASS"

"$ACME_DIR/acme.sh" \
  --issue \
  --dns dns_cpanel \
  -d "$DOMAIN" \
  -d "*.${DOMAIN}" \
  --server letsencrypt \
  --force 2>&1 | tee /tmp/acme-output.log

# Installer les certificats dans /etc/ssl/rebootly
"$ACME_DIR/acme.sh" \
  --install-cert \
  -d "$DOMAIN" \
  --cert-file      "$CERTS_DIR/cert.pem" \
  --key-file       "$CERTS_DIR/privkey.pem" \
  --fullchain-file "$CERTS_DIR/fullchain.pem" \
  --ca-file        "$CERTS_DIR/chain.pem" \
  --reloadcmd      "systemctl reload nginx"

ok "Certificat wildcard installé dans $CERTS_DIR"

# ─── 4. Configuration Nginx ──────────────────────────────────
section "4/5 — Configuration Nginx sécurisée"

rm -f "$ENABLED_DIR/default" 2>/dev/null || true

# Nginx.conf
cat > "$NGINX_DIR/nginx.conf" << 'EOF'
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 1024;
    multi_accept on;
}

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    server_tokens off;
    client_max_body_size 500M;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    log_format main '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent"';
    access_log /var/log/nginx/access.log;
    error_log  /var/log/nginx/error.log warn;

    # SSL
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;
    ssl_session_tickets off;
    ssl_stapling on;
    ssl_stapling_verify on;
    resolver 1.1.1.1 8.8.8.8 valid=300s;

    # Rate limiting
    limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
    limit_req_zone $binary_remote_addr zone=global:10m rate=100r/s;
    limit_req_status 429;

    gzip on;
    gzip_vary on;
    gzip_types text/plain text/css application/json application/javascript;

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}
EOF

mkdir -p "$NGINX_DIR/snippets"

# Snippet SSL
cat > "$NGINX_DIR/snippets/rebootly-ssl.conf" << EOF
ssl_certificate     $CERTS_DIR/fullchain.pem;
ssl_certificate_key $CERTS_DIR/privkey.pem;
ssl_trusted_certificate $CERTS_DIR/chain.pem;
EOF

# Snippet headers sécurité
cat > "$NGINX_DIR/snippets/rebootly-security.conf" << 'EOF'
server_tokens off;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
EOF

# Snippet proxy
cat > "$NGINX_DIR/snippets/rebootly-proxy.conf" << 'EOF'
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_connect_timeout 30s;
proxy_send_timeout 600s;
proxy_read_timeout 600s;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
client_max_body_size 500M;
EOF

# Redirect HTTP → HTTPS
cat > "$VHOSTS_DIR/00-redirect-http.conf" << 'EOF'
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;
    return 301 https://$host$request_uri;
}
EOF
ln -sf "$VHOSTS_DIR/00-redirect-http.conf" "$ENABLED_DIR/"
ok "Nginx configuré"

# ─── dnsmasq split-DNS ───────────────────────────────────────
section "Split-DNS WireGuard (dnsmasq)"
apt-get install -y dnsmasq -qq

# Config de base : écoute sur wg0, résout *.rebootly.cloud → IPs LXC internes
# N'overwrite que si pas déjà configuré
DNS_CONF="/etc/dnsmasq.d/rebootly.conf"
if [[ ! -f "$DNS_CONF" ]]; then
  cat > "$DNS_CONF" << 'EOF'
# Split-DNS Rebootly — WireGuard clients (Rebootly Connect)
# Résout *.rebootly.cloud vers les IPs LXC internes quand VPN actif
# Les clients utilisent ce serveur DNS uniquement via le tunnel WireGuard

# Écoute sur l'interface WireGuard uniquement
interface=wg0
bind-interfaces
no-hosts
no-resolv

# Fallback DNS public
server=1.1.1.1
server=8.8.8.8

# Les entrées address=/domaine/ip sont ajoutées automatiquement
# par 07-nginx-proxy.sh --add-client et add-archive-peer.sh
EOF
fi

systemctl enable dnsmasq
systemctl restart dnsmasq
ok "dnsmasq split-DNS configuré (écoute sur wg0:53)"

# ─── Fail2ban ────────────────────────────────────────────────
section "Intégration Fail2ban"

cat > /etc/fail2ban/filter.d/mailpiler.conf << 'EOF'
[Definition]
failregex = ^<HOST> .* "(POST|GET) /index.php.* HTTP.*" (401|403)
ignoreregex =
EOF

cat > /etc/fail2ban/filter.d/nginx-limit-req.conf << 'EOF'
[Definition]
failregex = limiting requests, excess:.* by zone.*client: <HOST>
ignoreregex =
EOF

cat > /etc/fail2ban/jail.d/rebootly.conf << 'EOF'
[nginx-http-auth]
enabled  = true
port     = http,https
filter   = nginx-http-auth
logpath  = /var/log/nginx/error.log
maxretry = 5
bantime  = 3600

[mailpiler-auth]
enabled  = true
port     = http,https
filter   = mailpiler
logpath  = /var/log/nginx/access.log
maxretry = 5
bantime  = 7200
findtime = 600

[nginx-limit-req]
enabled  = true
port     = http,https
filter   = nginx-limit-req
logpath  = /var/log/nginx/error.log
maxretry = 10
bantime  = 3600
EOF

systemctl reload fail2ban 2>/dev/null || true
ok "Fail2ban configuré"

# ─── Page sécurité VPN (catch-all sans VPN actif) ────────────
section "Page sécurité — accès sans VPN"
mkdir -p /var/www/rebootly-security

cat > /var/www/rebootly-security/index.html << 'SECEOF'
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Accès restreint — Rebootly Archives</title>
<style>
  *{box-sizing:border-box;margin:0;padding:0}
  body{background:#0a0e1a;color:#c8d6e5;font-family:'Segoe UI',system-ui,sans-serif;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:1.5rem}
  .wrap{display:flex;flex-direction:column;align-items:center;gap:2rem;max-width:500px;width:100%}
  .brand{font-size:1.2rem;font-weight:800;color:#fff;letter-spacing:-.02em}
  .brand span{font-weight:300;background:linear-gradient(135deg,#0044CC,#40D4FF);-webkit-background-clip:text;-webkit-text-fill-color:transparent}
  .card{background:#111827;border:1px solid rgba(64,212,255,.15);border-radius:16px;padding:3rem 2.5rem;width:100%;text-align:center;box-shadow:0 20px 60px rgba(0,0,0,.5)}
  .shield{width:72px;height:72px;margin:0 auto 1.5rem;background:linear-gradient(135deg,#0044CC,#40D4FF);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:2rem}
  h1{font-size:1.4rem;font-weight:700;color:#fff;margin-bottom:.5rem}
  .subtitle{color:#64748b;font-size:.9rem;margin-bottom:2rem;line-height:1.5}
  .steps{text-align:left;list-style:none}
  .steps li{display:flex;gap:.75rem;align-items:flex-start;padding:.75rem 0;border-bottom:1px solid rgba(255,255,255,.06)}
  .steps li:last-child{border-bottom:none}
  .step-num{background:linear-gradient(135deg,#0044CC,#40D4FF);color:#fff;border-radius:50%;width:24px;height:24px;min-width:24px;display:flex;align-items:center;justify-content:center;font-size:.75rem;font-weight:700;margin-top:1px}
  .step-text{font-size:.875rem;line-height:1.5;color:#94a3b8}
  .step-text strong{color:#e2e8f0}
  .badge{display:inline-block;background:rgba(64,212,255,.1);border:1px solid rgba(64,212,255,.2);color:#40D4FF;font-size:.75rem;padding:.25rem .75rem;border-radius:20px;margin-top:2rem}
  .footer{color:#1e2d4a;font-size:.72rem}
</style>
</head>
<body>
<div class="wrap">
  <div class="brand">Rebootly<span> Archives</span></div>
  <div class="card">
    <div class="shield">&#128737;</div>
    <h1>Acces VPN requis</h1>
    <p class="subtitle">Cette ressource est protegee par un acces VPN prive.<br>Connectez-vous via le tunnel securise pour y acceder.</p>
    <ol class="steps">
      <li>
        <span class="step-num">1</span>
        <span class="step-text"><strong>Telechargez</strong> votre configuration VPN depuis votre espace client.</span>
      </li>
      <li>
        <span class="step-num">2</span>
        <span class="step-text"><strong>Installez</strong> Rebootly Connect et importez votre configuration.</span>
      </li>
      <li>
        <span class="step-num">3</span>
        <span class="step-text"><strong>Activez</strong> le tunnel VPN, puis revenez sur cette page.</span>
      </li>
    </ol>
    <span class="badge">&#128274; Connexion chiffree VPN</span>
  </div>
  <p class="footer">Powered by Rebootly Archives</p>
</div>
</body>
</html>
SECEOF

ok "Page sécurité créée : /var/www/rebootly-security/index.html"

# Catch-all HTTPS → page sécurité (utilise le cert du domaine principal si dispo)
CATCHALL_CERT="$CERTS_DIR/fullchain.pem"
CATCHALL_KEY="$CERTS_DIR/privkey.pem"

cat > "$VHOSTS_DIR/00-default-ssl-catchall.conf" << EOF
server {
    listen 443 ssl default_server;
    server_name _;
    ssl_certificate     ${CATCHALL_CERT};
    ssl_certificate_key ${CATCHALL_KEY};
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_stapling off;
    root /var/www/rebootly-security;
    index index.html;
    location / { try_files \$uri /index.html =404; }
}
EOF
ln -sf "$VHOSTS_DIR/00-default-ssl-catchall.conf" "$ENABLED_DIR/"
ok "Catch-all HTTPS configuré → page sécurité VPN"

# ─── 5. Démarrer Nginx ───────────────────────────────────────
section "5/5 — Démarrage Nginx"
nginx -t && systemctl enable nginx && systemctl restart nginx
ok "Nginx démarré"

# ─── Résumé ──────────────────────────────────────────────────
echo ""
echo -e "${CYAN}${BOLD}╔══════════════════════════════════════════════════════════╗"
echo -e "║  Nginx Reverse Proxy opérationnel                       ║"
echo -e "╠══════════════════════════════════════════════════════════╣"
echo -e "║  SSL      : *.rebootly.cloud (Let's Encrypt)            ║"
echo -e "║  HTTPS    : TLS 1.2/1.3 uniquement                      ║"
echo -e "║  Fail2ban : intégré (5 essais → ban 2h)                 ║"
echo -e "║  Rate     : 5 req/min sur login                          ║"
echo -e "╠══════════════════════════════════════════════════════════╣"
echo -e "║  Ajouter un client Mailpiler :                           ║"
echo -e "║  bash 07-nginx-proxy.sh --add-client \\                  ║"
echo -e "║    archives.client.rebootly.cloud 10.10.0.101            ║"
echo -e "║                                                          ║"
echo -e "║  → Nginx HTTPS + port SMTP journal auto-assigné          ║"
echo -e "║  → iptables DNAT + MASQUERADE + INPUT persistés          ║"
echo -e "╚══════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "  ${YELLOW}N'oublie pas d'ouvrir les ports HTTP/HTTPS sur le VPN :${NC}"
echo -e "  iptables -I INPUT -p tcp --dport 80  -j ACCEPT"
echo -e "  iptables -I INPUT -p tcp --dport 443 -j ACCEPT"
echo -e "  iptables-save > /etc/iptables/rules.v4"
echo ""
