#!/usr/bin/env bash
# security/ports -- what is listening, and which program owns it
set -o pipefail
SELF=$(readlink -f "${BASH_SOURCE[0]}")
NV_BASE=$(cd "$(dirname "$SELF")/../../.." && pwd)
export NV_BASE
# shellcheck source=/dev/null
. "$NV_BASE/lib/core/bootstrap.sh"

ui_header "$(t sec_m_ports)"

if ! nv_have ss; then
    ui_err "$(t ports_no_ss)"
    exit 1
fi

printf '  %-8s %-22s %-8s %s\n' "$(t ports_proto)" "$(t ports_addr)" "$(t ports_state)" "$(t ports_proc)"
ss -H -tulpn 2>/dev/null | awk '{print $1, $5, $6, $7}' | sort -u | head -n 40 \
    | while read -r proto addr _state proc; do
          port=${addr##*:}
          [ -z "$port" ] && continue
          printf '  %-8s %-22s %-8s %s\n' \
              "${proto:-tcp}" "$(ui_trunc "$addr" 20)" "$port" "$(ui_trunc "${proc:--}" 28)"
      done

ui_blank
ui_info "$(t ports_note)"
exit 0
