#!/bin/sh
# shellcheck disable=1091,1090,2317

[ -n "$1" ] || exit

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

set_interface() {
	OTB_TRACKER_STATUS="$1"
	for tracker_bin in /usr/share/otb/post-tracking.d/*; do
		[ -x "$tracker_bin" ] && (
			_log() {
				logger -t "post-tracking-${tracker_bin##*/}" "$*"
			}
			. "$tracker_bin"
		)
	done
}

# Export vars used by post-tracking scripts
export OTB_TRACKER_INTERFACE="$1"
export OTB_TRACKER_LATENCY=0
export OTB_TRACKER_STATUS=OK
export OTB_TRACKER_DEVICE
export OTB_TRACKER_DEVICE_GATEWAY
export OTB_TRACKER_DEVICE_GATEWAY_V6
export OTB_TRACKER_DEVICE_IP

hosts="$(uci get otb-tracker.defaults.hosts)"
interval="$(uci get otb-tracker.defaults.interval)"
host_index=1
host_length="$(echo "$hosts" | awk '{n=split($0,array," "); print(n);}')"

while true; do
	host_index=1

	# Flush network cache to avoid obsolete IP addresses
	network_flush_cache

        # Check interface proto, override for lte
        if [ "$(uci get network."$OTB_TRACKER_INTERFACE".proto)" = "modemmanager" ]; then
            OTB_TRACKER_DEVICE="wwan0"
        fi

        network_get_ipaddr OTB_TRACKER_DEVICE_IP "$OTB_TRACKER_INTERFACE" || exit

	OTB_TRACKER_DEVICE_GATEWAY=$(ip -4 -o route show table "$OTB_TRACKER_TABLE" | awk 'NR==1 {if($1 == "default") print $3}')

	# Get IPv6 gateway of tun0 interface
	[ "$OTB_TRACKER_INTERFACE" = "tun0" ] && {
		ip6table=$(uci -q get network.tun0.ip6table)

		[ -n "$ip6table" ] && {
		OTB_TRACKER_DEVICE_GATEWAY_V6=$(ip -6 -o route show table "$ip6table" | awk '{if($1 == "default") print $3}')
		}
	}

	while [ "$host_index" -le "$host_length" ]; do
		host="$(echo "$hosts" | awk '{print $'$host_index';}')"

		OTB_TRACKER_LATENCY="$(ping -Q 184 -I "$OTB_TRACKER_DEVICE_IP" -i "$interval" -w 5 -c 3 "$host" | \
			grep "bytes from $host" | \
			awk 'match($0,/time=(\d+)/){print substr($0, RSTART+5, RLENGTH-5); exit;}')"

		if [ -n "$OTB_TRACKER_LATENCY" ]; then
			host_index=1
			set_interface "OK"
		else
			host_index=$((host_index + 1))
		fi
	done
	set_interface "ERROR"
done
