#!/bin/sh
# shellcheck disable=SC1091,SC2039
# vim: set noexpandtab tabstop=4 shiftwidth=4 softtabstop=4 :

. /lib/overthebox

test_time=5       # Do the iperf during 5 seconds
skip_test_time=1  # Skip the data of the first second of the test

server_ip="$(uci -q get glorytun.tun0.server)" || {
	otb_err "Couldn't find server ip"
	exit 1
}

. /lib/functions.sh
. /lib/functions/network.sh

trap : HUP INT TERM

setup() {
	otb_call_api POST ipt/iperf >/dev/null || return
	/etc/init.d/otb-qos stop 2>/dev/null   || true
}

cleanup() {
	otb_call_api DELETE ipt/iperf >/dev/null
	/etc/init.d/otb-qos start
}

_speedtest() {
	speedtest "$1" | awk -v iface="$1" \
	'{ printf "[%8s]  Upload:  %8d kbits/s  Download: %8d kbit/s\n", iface, $1, $2 }'
}

if setup; then
	if [ "$(uci -q get "network.$1")" = interface ]; then
		_speedtest "$1"
	else
		config_load network
		config_foreach _speedtest interface
	fi
	cleanup
else
	otb_err "Couldn't start iperf3"
	exit 1
fi
