# -*- shell-script -*-
# Copyright 2021-2022 Ian Jackson and contributors to Hippotat
# SPDX-License-Identifier: GPL-3.0-or-later WITH LicenseRef-Hippotat-OpenSSL-Exception
# There is NO WARRANTY.

set -o pipefail
set -x

ssrc="${0%/*}"
src="$ssrc"/..
test="$src/test"

target_bin_dir=${TARGET_RELEASE_DIR-target/debug}
target_bin_prefix=${target_bin_dir}${target_bin_dir+/}

fail () { echo >&2 "$0: fail: $*"; exit 1; }

determine-tname () {
    local prefix=$1; shift
    case "${0##*/}" in
    $prefix-*) tname="${0##*/}" ;;
    *) fail "bad test script name $0" ;;
    esac
}

test-prep () {
    determine-tname t

    tmp=tmp/$tname
    rm -rf "$tmp"
    mkdir -p $tmp

    $test/netns-setup "$tname"

    trap '
	rc=$?
	shutdown
	if [ $rc = 0 ]; then echo "OK $tname"; fi
	exit $rc
    ' 0
}

kill-pids () {
    for p in $pids; do kill -9 $p; done
}

shutdown () {
    kill-pids
}

in-ns () {
    local client_server=$1; shift
    $exec ip netns exec hippotat-t-$tname-$client_server "$@"
}

run-client () {
    in-ns client \
    ${target_bin_prefix}hippotat --config $test/test.cfg -DD "$@"
}
run-server () {
    in-ns server \
    ${target_bin_prefix}hippotatd --config $test/test.cfg -DD "$@"
}
spawn () {
    { exec=exec; "$@"; } &
    pids+=" $!"
}

in-ns-await-up () {
    local sc="$1"; shift
    local addr="$1"; shift
    local t=1
    while sleep $(( $t / 10 )).$(( $t % 10 )); do
	if in-ns $sc ip -o addr show | fgrep " inet $addr "; then
	    return
	fi
	t=$(( $t + 1 ))
	if [ $t -gt 10 ]; then fail "$sc did not come up $addr"; fi
    done
}

start-server () {
    spawn run-server
    in-ns-await-up server 192.0.2.1
}
start-client () {
    spawn run-client
    in-ns-await-up client 192.0.2.3
}
