#!/bin/bash
#
# ntshow - count network connections per remote IP, with GeoIP country
#
# Usage:
#   ntshow          incoming connections only (default)
#   ntshow -b       both incoming and outgoing
#   ntshow -d       add per-port detail, e.g.  54.220.145.91  (80=4,443=45)
#   ntshow -b -d    both, with detail (outgoing ports shown as out:443=12)
#
# "Incoming" = the local port is one this server listens on (80, 443, 22...).
# In detail mode, incoming shows the local service port; outgoing shows the
# remote port the server connected to.

source /usr/local/afribin/src/functions.sh

usage() {
    sed -n '3,13p' "$0" | sed 's/^# \{0,1\}//'
    exit "${1:-0}"
}

BOTH=0
DETAIL=0
while getopts ":bdh" opt; do
    case "$opt" in
        b) BOTH=1 ;;
        d) DETAIL=1 ;;
        h) usage 0 ;;
        *) echo "Unknown option: -$OPTARG" >&2; usage 1 ;;
    esac
done

# get_linux_info from functions.sh
LINUX_VERSION=$(get_linux_info VERSION)
if [[ $LINUX_VERSION -ge 8 ]] ; then
    GEOIP=/usr/local/afribin/geoip3
else
    GEOIP=/usr/local/afribin/geoip
fi

RAW="$(mktemp)"
trap 'rm -f "$RAW"' EXIT

# ports this server is listening on (port = text after the last ":")
LISTEN_PORTS="$(netstat -lntu | awk 'NR>2 {n=split($4,a,":"); print a[n]}' | sort -u | tr '\n' ' ')"

# One line per connection: "<remote ip> <port label>"
netstat -ntu | awk -v ports="$LISTEN_PORTS" -v both="$BOTH" '
    BEGIN { split(ports, p, " "); for (i in p) L[p[i]] = 1 }
    /^(tcp|udp)/ {
        n = split($4, l, ":"); lport = l[n]
        m = split($5, r, ":"); rport = r[m]
        ip = $5; sub(/:[^:]*$/, "", ip); sub(/^::ffff:/, "", ip)
        if (lport in L)  print ip, lport            # incoming
        else if (both)   print ip, "out:" rport     # outgoing
    }' > "$RAW"

if [[ $DETAIL -eq 0 ]]; then
    awk '{print $1}' "$RAW" | sort | uniq -c | sort -n | "$GEOIP"
    exit 0
fi

# Detail: "ip  (port=count,port=count)" joined onto the GeoIP output
DETAILS="$(sort "$RAW" | uniq -c | sort -k2,2 -k3,3V | awk '
    $2 != ip { if (ip != "") print ip, list; ip = $2; list = "" }
    { list = list (list == "" ? "" : ",") $3 "=" $1 }
    END { if (ip != "") print ip, list }')"

awk '{print $1}' "$RAW" | sort | uniq -c | sort -n | "$GEOIP" \
  | awk -v details="$DETAILS" '
      BEGIN { n = split(details, d, "\n"); for (i = 1; i <= n; i++) { split(d[i], f, " "); D[f[1]] = f[2] } }
      { line = $0; if ($NF in D) line = sprintf("%-40s (%s)", line, D[$NF]); print line }'

