#!/usr/bin/env bash
# ZION TERMINAL - Diagnostico de rede
# Cyberdeck criado por Pablo Murad em 2026
export LC_ALL=C
. /opt/zion-terminal/bin/zion-lib.sh 2>/dev/null
[ "$1" = "--help" ] && { echo "Uso: zion rede [mtr] — interfaces, IPs, gateway, DNS, internet, Tailscale e (opcional) MTR."; exit 0; }

ui_header "DIAGNOSTICO DE REDE"

ui_section "INTERFACES"
ip -brief -4 addr | while read -r ifc st ip _; do
  [ "$ifc" = lo ] && continue
  printf '  %b%-12s%b %b  %b%s%b\n' "$ZWHT" "$ifc" "$ZR" "$([ "$st" = UP ] && ui_state ok || ui_state off)" "$ZGRY" "$ip" "$ZR"
done

ui_section "ROTA / GATEWAY"
gw=$(ip route show default | awk '{print $3; exit}'); dev=$(ip route show default | awk '{print $5; exit}')
ui_kv "Gateway" "${gw:-—} (via ${dev:-—})"
if [ -n "$gw" ] && ping -c1 -W1 "$gw" >/dev/null 2>&1; then printf '  %b%-14s%b %b\n' "$ZDISC" "Ping gateway" "$ZR" "$(ui_state ok)"; else printf '  %b%-14s%b %b\n' "$ZDISC" "Ping gateway" "$ZR" "$(ui_state warn)"; fi

ui_section "DNS"
grep -h '^nameserver' /etc/resolv.conf 2>/dev/null | awk '{print $2}' | while read -r ns; do ui_kv "nameserver" "$ns"; done
printf '  %b%-14s%b %b\n' "$ZDISC" "Resolucao" "$ZR" "$(getent hosts deb.debian.org >/dev/null 2>&1 && ui_state ok || ui_state crit)"

ui_section "CONECTIVIDADE"
printf '  %b%-14s%b %b\n' "$ZDISC" "Internet" "$ZR" "$([ "$(zion_internet)" = disponivel ] && ui_state ok || ui_state off)"
printf '  %b%-14s%b %b  %b%s%b\n' "$ZDISC" "Tailscale" "$ZR" "$([ "$(zion_ts_estado)" = conectado ] && ui_state ok || ui_state off)" "$ZGRY" "$(zion_ip_ts)" "$ZR"

if [ "${1:-}" = mtr ] || [ "${1:-}" = --mtr ]; then
  ui_section "MTR -> 1.1.1.1"
  ui_dep mtr && mtr -r -c3 1.1.1.1 2>/dev/null | sed 's/^/  /'
fi
ui_rule
