#!/bin/sh
# metrics-net.sh - per-WAN latency/jitter/loss probes for busrouter.
#
# Public API:
#   net_probe_iface <iface>   10-ping probe; echo "lat jitter loss"
#   _net_parse_ping           pure parser: ping stdout -> "lat jitter loss" (testable)

LIB_DIR="${LIB_DIR:-/usr/lib/busrouter}"

# Parse BusyBox ping stdout and emit "lat jitter loss".
# lat    = avg RTT across received packets (ms, 1 decimal)
# jitter = population stddev of per-sample RTTs (ms, 1 decimal)
# loss   = packet loss percent (integer); defaults to 100 if no stats line seen
# BusyBox ping summary has no mdev; jitter is computed from individual time= lines.
# Emits "0 0 100" when no replies received.
_net_parse_ping() {
	awk '
		BEGIN { loss = 100 }
		/time=/ {
			split($0, a, "time="); split(a[2], b, " "); t = b[1]+0
			sum += t; sum2 += t*t; cnt++
		}
		/% packet loss/ {
			for (i=1; i<=NF; i++) if ($i ~ /%/) { loss = $i+0; break }
		}
		END {
			if (cnt > 0) {
				avg = sum / cnt
				var = sum2/cnt - avg*avg
				if (var < 0) var = 0
				printf "%.1f %.1f %d\n", avg, sqrt(var), loss
			} else {
				print "0 0 100"
			}
		}
	'
}

# Run a 10-ping probe bound to an interface and emit "lat jitter loss".
# Usage: net_probe_iface <iface>
# <iface>: real interface name (rmnet_mhi0 or eth0)
# -W 3 (timeout per reply) verified on GL-XE3000 BusyBox ping.
net_probe_iface() {
	local iface="$1"
	[ -n "$iface" ] || { logger -t busrouter "net_probe_iface: missing iface arg"; return 1; }
	ping -I "$iface" -c 10 -W 3 1.1.1.1 2>/dev/null | _net_parse_ping
}
