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

HOST="gra.perf.overthebox.net"

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


_rule_create(){
    nft add rule ip nat socks_emitted_by_myself ip daddr "$HOST" jump socks_decision comment \" Test download proof \"
}

_rule_delete(){
    # get handle of test rule
    rule_handle=$(nft -a list chain ip nat socks_emitted_by_myself | grep "socks_decision" | awk '{print $NF}')

    # delete rule with handle value
    nft delete rule ip nat socks_emitted_by_myself handle "$rule_handle"
}

_chain_exists() {
	nft list chain ip nat "$1" 1>/dev/null 2>/dev/null
}

_speedtest() {
	network_get_ipaddr SOURCE_IP "lan"
	echo "Launching shadowsocks speedtest : $SOURCE_IP"
	speedtest "${SOURCE_IP}"
	echo "${SPEEDTEST}" | jq .
}

if ! _chain_exists "socks_emitted_by_myself" || ! _chain_exists "socks_decision"; then
	echo "Couldn't find the nftables chain to plug myself into.. Please check netfilter."
	return 1
fi

trap : HUP INT TERM

_rule_create
_speedtest
_rule_delete
