#!/bin/sh
# hollywood shim: a small stand-in for speedometer(1) on macOS, where the
# original is not packaged.  Reads the interface byte counters from
# netstat(1) and draws one bar per direction and interval.
#   speedometer -rx IFACE -tx IFACE [-i SECONDS]
iface=
interval=1
while [ -n "$1" ]; do
	case "$1" in
		-rx|-tx) iface="$2"; shift 2 ;;
		-i) interval="$2"; shift 2 ;;
		*) shift ;;
	esac
done
[ -n "$iface" ] || exit 1
netstat -ibn -I "$iface" >/dev/null 2>&1 || exit 1

counters() {
	netstat -ibn -I "$iface" 2>/dev/null | awk '/<Link#/ {print $(NF-4), $(NF-1); exit}'
}

set -- $(counters)
[ -n "$2" ] || exit 1
prx=$1
ptx=$2
while sleep "$interval"; do
	set -- $(counters)
	[ -n "$2" ] || continue
	cols=$(tput cols 2>/dev/null || echo 80)
	awk -v rx=$(($1 - prx)) -v tx=$(($2 - ptx)) -v dt="$interval" -v cols="$cols" -v ifc="$iface" '
	function human(b) {
		if (b >= 1048576) return sprintf("%7.2f MiB/s", b / 1048576)
		if (b >= 1024)    return sprintf("%7.2f KiB/s", b / 1024)
		return sprintf("%7.0f   B/s", b)
	}
	function bar(b, width,   n, s) {
		# logarithmic scale: 1 KiB/s .. 100 MiB/s
		n = (b > 1024) ? int(width * log(b / 1024) / log(102400)) : 0
		if (n > width) n = width
		s = ""
		while (n-- > 0) s = s "#"
		return s
	}
	BEGIN {
		if (rx < 0) rx = 0
		if (tx < 0) tx = 0
		w = cols - 26
		if (w < 4) w = 4
		printf "\033[1;32mRX %s %s\033[0m %s\n", ifc, human(rx / dt), bar(rx / dt, w)
		printf "\033[1;35mTX %s %s\033[0m %s\n", ifc, human(tx / dt), bar(tx / dt, w)
	}'
	prx=$1
	ptx=$2
done
