#!/usr/bin/env bash
# SPDX-License-Identifier: LicenseRef-CMSD-1.0
# Copyright (c) 2026 CyberMind — Gérald Kerma <devel@cybermind.fr>
# Source-Disclosed License — All rights reserved except as expressly granted.
# See LICENCE-CMSD-1.0.md for terms.

# SecuBox-Deb :: secubox-netboot-serve (#737, Phase 2 — côté SERVEUR)
# Active CE host comme source de boot réseau (TFTP + HTTP), de façon NON-INVASIVE :
# n'écrit AUCUN env U-Boot, ne pose AUCUN overlay sur ce host (il reste untouched
# côté boot). Crée juste les racines, configure tftpd-hpa, vérifie la location nginx.
#   secubox-netboot-serve up      # crée racines + tftpd-hpa pointant /srv/secubox/netboot/tftp
#   secubox-netboot-serve status
set -uo pipefail
readonly MODULE="secubox-netboot-serve"
readonly ROOT=/srv/secubox/netboot
readonly TFTP="$ROOT/tftp" HTTP="$ROOT/http"
readonly TFTPCONF=/etc/default/tftpd-hpa

log(){ printf '[%s] %s\n' "$MODULE" "$*" >&2; }

# Adresse d'écoute du vhost de boot (#3100/#3117). Le live et ses images ne se servent qu'au réseau local.
# adresse_admise IP EXPLICITE : IPv4 privée, hors ponts conteneurs (10.0.3/24, 10.100.0/24) et maillage
# (10.10.0/24). Détectée (EXPLICITE=0) : 192.168/16 et 172.16/12 seulement — un 10/8 côté route par défaut
# peut être le réseau du FAI ou d'un immeuble, il faut alors SBX_NETBOOT_ADRESSE.
adresse_admise() {
  local a="$1" explicite="$2"
  [[ "$a" =~ ^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$ ]] || return 1
  local o1=${BASH_REMATCH[1]} o2=${BASH_REMATCH[2]} o3=${BASH_REMATCH[3]} o4=${BASH_REMATCH[4]} o
  for o in "$o1" "$o2" "$o3" "$o4"; do [ "$((10#$o))" -le 255 ] || return 1; done
  case "$o1.$o2.$o3" in 10.0.3|10.100.0|10.10.0) return 1 ;; esac
  if { [ "$o1" = 192 ] && [ "$o2" = 168 ]; } || { [ "$o1" = 172 ] && [ "$o2" -ge 16 ] && [ "$o2" -le 31 ]; } \
     || { [ "$o1" = 10 ] && [ "$explicite" = 1 ]; }; then
    printf '%s\n' "$a"; return 0
  fi
  return 1
}

# SBX_NETBOOT_ADRESSE, sinon la source de la route par défaut (le réseau où l'on branche les box à netbooter,
# derrière la box FAI sur gk1/gk2).
adresse_lan() {
  if [ -n "${SBX_NETBOOT_ADRESSE:-}" ]; then
    adresse_admise "$SBX_NETBOOT_ADRESSE" 1
  else
    adresse_admise "$(ip -4 -o route get 1.1.1.1 2>/dev/null | sed -n 's/.* src \([0-9.]*\).*/\1/p')" 0
  fi
}

cmd_up() {
  install -d -m0755 "$TFTP" "$HTTP"
  log "racines: $TFTP (TFTP) , $HTTP (HTTP, vhost de boot :8099)"
  if command -v in.tftpd >/dev/null 2>&1 || dpkg -s tftpd-hpa >/dev/null 2>&1; then
    cat > "$TFTPCONF" <<CFG
# SecuBox netboot (#737) — TFTP read-only sur la racine de boot
TFTP_USERNAME="tftp"
TFTP_DIRECTORY="$TFTP"
TFTP_ADDRESS="0.0.0.0:69"
TFTP_OPTIONS="--secure --blocksize 1468"
CFG
    systemctl enable --now tftpd-hpa 2>/dev/null || systemctl restart tftpd-hpa 2>/dev/null || true
    log "tftpd-hpa -> $TFTP ($(systemctl is-active tftpd-hpa 2>/dev/null))"
  else
    log "WARN tftpd-hpa absent : 'apt install tftpd-hpa' (repli HTTP reste possible)"
  fi
  # nginx : activer le VHOST de boot dédié (boot.<board>.secubox.in, HTTP simple,
  # hors WAF) — livré par le paquet dans share/, posé ICI (install non-invasif).
  local vsrc=/usr/share/secubox/netboot/nginx/boot-vhost.conf
  local vdst=/etc/nginx/sites-enabled/secubox-netboot-boot.conf
  local adresse
  if [ -f "$vsrc" ] && ! adresse="$(adresse_lan)"; then
    log "WARN aucune adresse LAN privée : vhost de boot non posé (SBX_NETBOOT_ADRESSE=<ip> pour l'imposer)"
  elif [ -f "$vsrc" ]; then
    # temporaires HORS de sites-enabled (nginx y inclut tout fichier) ; l'ancien vhost est rendu si nginx -t refuse
    local tmp prec
    tmp="$(mktemp /etc/nginx/.secubox-netboot-boot.XXXXXX)" || { log "WARN mktemp impossible"; cmd_status; return 0; }
    prec="$(mktemp /etc/nginx/.secubox-netboot-boot-prec.XXXXXX)" || { rm -f -- "$tmp"; cmd_status; return 0; }
    local avait=0; [ -f "$vdst" ] && cp -p -- "$vdst" "$prec" && avait=1
    sed "s/@ADRESSE_LAN@/$adresse/g" "$vsrc" > "$tmp" && chmod 0644 "$tmp" && mv -f -- "$tmp" "$vdst"
    if nginx -t 2>/dev/null; then
      systemctl reload nginx 2>/dev/null || true
      log "vhost boot posé ($vdst, écoute $adresse:8099) + nginx reload"
    elif [ "$avait" = 1 ]; then
      mv -f -- "$prec" "$vdst"; log "WARN nginx -t KO → vhost de boot précédent rendu"
    else
      rm -f -- "$vdst"; log "WARN nginx -t KO → vhost boot retiré (SBX_NETBOOT_ADRESSE=<ip> pour imposer l'adresse)"
    fi
    rm -f -- "$tmp" "$prec"
  else
    log "WARN vhost source absent: $vsrc"
  fi
  cmd_status
}

cmd_status() {
  local tftp_act=absent; command -v systemctl >/dev/null && tftp_act="$(systemctl is-active tftpd-hpa 2>/dev/null || echo absent)"
  # Le vhost POSÉ fait foi, pas `nginx -T` (#3233) : l'API tourne sous ProtectSystem=strict, où nginx -t ne peut
  # ouvrir ses journaux et échoue — la page disait « no » alors que le vhost servait ; nginx -T relisait aussi toute
  # la configuration de gk2 à chaque rafraîchissement.
  local http_ok=no vhost="${SBX_NETBOOT_VHOST:-/etc/nginx/sites-enabled/secubox-netboot-boot.conf}"
  if [ -f "$vhost" ] && grep -q '/srv/secubox/netboot/http' "$vhost" 2>/dev/null; then http_ok=yes; fi
  local boards=0; [ -d "$HTTP" ] && boards="$(find "$HTTP" -maxdepth 1 -mindepth 1 -type d 2>/dev/null | wc -l)"
  cat <<JSON
{ "module":"$MODULE","tftp_root":"$TFTP","http_root":"$HTTP","tftpd":"$tftp_act",
  "nginx_sbxboot":"$http_ok","published_boards":$boards }
JSON
}

# Sourcé avec --bibliotheque (tests) : fonctions seulement.
# shellcheck disable=SC2317  # exit : seulement si lancé (et non sourcé) avec --bibliotheque
[ "${1:-}" = "--bibliotheque" ] && { return 0 2>/dev/null || exit 0; }

case "${1:-status}" in
  up) cmd_up ;;
  status) cmd_status ;;
  *) echo "usage: $MODULE {up|status}" >&2; exit 2 ;;
esac
