#!/usr/bin/env bash
set -u

section() {
  printf '\n== %s ==\n' "$1"
}

show_sshd_setting() {
  local key="$1"
  local expected="$2"
  local value

  value="$(sshd -T 2>/dev/null | awk -v key="$key" '$1 == key {print $2; exit}')"
  if [[ -z "$value" ]]; then
    printf '%-32s %s\n' "$key" "indisponible"
    return
  fi

  if [[ "$value" == "$expected" ]]; then
    printf '[OK]   %-26s %s\n' "$key" "$value"
  else
    printf '[VOIR] %-26s %s (cible du cours : %s)\n' "$key" "$value" "$expected"
  fi
}

section "Contexte"
printf 'Hôte : %s\n' "$(hostname)"
printf 'Date : %s\n' "$(date --iso-8601=seconds 2>/dev/null || date)"

section "Configuration SSH effective"
if command -v sshd >/dev/null 2>&1; then
  show_sshd_setting permitrootlogin no
  show_sshd_setting passwordauthentication no
  show_sshd_setting kbdinteractiveauthentication no
  show_sshd_setting pubkeyauthentication yes
  show_sshd_setting maxauthtries 3
  show_sshd_setting x11forwarding no
else
  echo "sshd absent."
fi

section "Sockets d'administration"
if command -v ss >/dev/null 2>&1; then
  ss -lntp 2>/dev/null | awk 'NR == 1 || $4 ~ /:22$/'
else
  echo "ss absent."
fi

section "WireGuard"
if command -v wg >/dev/null 2>&1; then
  wg show 2>/dev/null || echo "Aucune interface WireGuard visible."
else
  echo "wg absent."
fi

section "Règles nftables liées à SSH/VPN"
if command -v nft >/dev/null 2>&1; then
  nft list ruleset 2>/dev/null | grep -E -C 2 'dport 22|10\.254\.0\.0/24|10\.70\.10\.0/24' \
    || echo "Aucune règle correspondante trouvée."
else
  echo "nft absent."
fi

section "Journaux SSH récents"
if command -v journalctl >/dev/null 2>&1; then
  journalctl -u ssh -u sshd --since '-30 min' --no-pager 2>/dev/null | tail -n 20 \
    || echo "Journaux indisponibles."
else
  echo "journalctl absent."
fi

cat <<'EOF'

Ce script est en lecture seule. Un [VOIR] n'est pas automatiquement une faille :
compare la valeur avec le besoin, le système d'exploitation et ton plan de retour arrière.
EOF
