#!/bin/sh

dut=""

ssh_dut(){
	ssh "$dut" -- "$@"
}

prepare_testset(){
	local testdir="$1"

	mkdir -p "$testdir"
	(date;date +%s) > "$testdir/test_start.txt"
	ssh_dut uptime > "$testdir/uptime.txt"
	ssh_dut uname -r > "$testdir/kernel.txt"

	scp flower_placement_tests.sh "$dut":
}

finish_testset(){
	local testdir="$1"

	(date;date +%s) > "$testdir/test_end.txt"
}

run_test(){
	echo $@
	local testsetdir="$1"
	local name="$2"
	shift; shift
	local testdir="$testsetdir/tests/$name"
	mkdir -p "$testdir"

	# prepare dut for test
	ssh_dut ./flower_placement_tests.sh "$@"

	# start snmpdelta with timeout
	timeout 20 snmpdelta -Cp 1 -c public -v 2c -Cs 100.123.154.250  IF-MIB::ifInUcastPkts.1057 IF-MIB::ifOutUcastPkts.1057 | tee "$testdir/snmpdelta.txt"
	ssh_dut tc -s filter show dev enp5s0f0np0 ingress > "$testdir/tc.txt"
}

run_testset(){
	local testdir="test_runs/$(date +%s)"
	prepare_testset "$testdir"

	run_test "$testdir" 'baseline' step01
	run_test "$testdir" 'eswitch' step02
	run_test "$testdir" 'ingress_qdisc' step03
	run_test "$testdir" 'single_matching' step04
	for i in $(seq 1 19) $(seq 20 5 100); do
		run_test "$testdir" "$(printf 'non_matching_and_nothing_%03d' $i)" step05 "$i"
		run_test "$testdir" "$(printf 'non_matching_and_matching_%03d' $i)" step06 "$i"
		run_test "$testdir" "$(printf 'non_matching_and_trap_%03d' $i)" step07 "$i"
		run_test "$testdir" "$(printf 'non_matching_and_non_chain_%03d' $i)" step08 "$i"
		run_test "$testdir" "$(printf 'non_matching_handles_and_matching_%03d' $i)" step09 "$i"
	done
	run_test "$testdir" 'single_matching_sw' step10

	ssh_dut ./flower_placement_tests.sh step04 # remove CPU load
	finish_testset "$testdir"
}

bail(){
	echo "$@" >&2
	exit 1
}

main(){
	local dut=''
	if [ $# -eq 0 ] ; then
		dut='dut'
	elif [ $# -eq 1 ] ; then
		dut="$1"
	else
		bail "Usage: $0 [dut]"
	fi

	run_testset "$dut"
}

main "$@"
