#!/bin/sh
# Urutau: once a minute, (1) refresh the set of ports this host serves, (2) append
# the exact counters of the inbound observation table to ingress.counters.
#
# One line per run, cumulative since the table was loaded (the hub takes the
# difference between two lines; a drop means the table was reloaded):
#   ts=1767225600 total=120 tcp=100 udp=15 icmp=5 open=30
# Read-only with respect to the network: it only reads counters and fills a set.
set -eu
t=inet
tab=urutau_ingress
out=${URUTAU_INGRESS_COUNTERS:-/var/log/urutau/ingress.counters}

nft list table "$t" "$tab" >/dev/null 2>&1 || exit 0

# Ports this host serves, so the chain can tell open from closed.
{
	echo "flush set $t $tab open"
	ss -Hlnt | awk '{print $4}' | sed -n 's/.*:\([0-9][0-9]*\)$/tcp . \1/p'
	ss -Hlnu | awk '{print $4}' | sed -n 's/.*:\([0-9][0-9]*\)$/udp . \1/p'
} | sort -u | awk 'NR==1 {print; next} {e = e (e ? ", " : "") $0} END {if (e) print "add element inet urutau_ingress open { " e " }"}' | nft -f - || true

nft list counters table "$t" "$tab" | awk -v ts="$(date +%s)" '
	/^[ \t]*counter / { name = $2 }
	/^[ \t]*packets / && name != "" { v[name] = $2; name = "" }
	END {
		printf "ts=%s total=%d tcp=%d udp=%d icmp=%d open=%d\n", ts, v["in_total"], v["in_tcp"], v["in_udp"], v["in_icmp"], v["in_open"]
	}' >> "$out"
