# This shell script uses nc-like executables to send and receive the file at
# $1, and prints the checksums. 3 such executables are
# github.com/h2so5/utp/ucat, invoked as h2so5-ucat, libutp-ucat, which is the
# ucat or ucat-static generated by the C++ libutp, and lastly, ./cmd/ucat from
# this repository. A good file in my experiments is no more than a few 100MB,
# or you'll be waiting a while.

set -eu
# set -x

# Passed to invocations of godo for package ./cmd/ucat.
#GODOFLAGS=-race

#export GO_UTP_PACKET_DROP=0.1
export GOPPROF=

# Invokes the implementation to test against. If there's an arg, then it's
# expected to listen.
function other_ucat() {
	if [[ $# != 0 ]]; then
		libutp-ucat -l -p "$port"
		# h2so5-ucat -l :"$port"
	else
		libutp-ucat localhost "$port"
		# h2so5-ucat localhost:"$port"
	fi
}

function md5cmd() {
	(which md5sum > /dev/null && md5sum "$@") || (which md5 > /dev/null && md5 "$@") || md5sum "$@"
}

# Check what the correct result is.
md5cmd "$1"

rate() {
	pv -a -W -b
}

port=4000

echo 'utp->other_ucat'
# Send from this uTP implementation to another client.
other_ucat -l | rate | md5cmd &
# sleep 1
godo ${GODOFLAGS-} ./cmd/ucat localhost "$port" < "$1"
wait

echo 'other_ucat->utp'
# Send from the other implementation, to this one.
GO_UTP_LOGGING=0 godo ${GODOFLAGS-} ./cmd/ucat -l -p "$port" | rate | md5cmd &
# Never receive from h2so5's ucat without a small sleep first. Don't know why.
sleep 1
other_ucat < "$1"
wait

echo 'libutp->libutp'
libutp-ucat -l -p "$port" | rate | md5cmd &
libutp-ucat localhost "$port" < "$1"
wait

echo 'utp->utp'
godo ./cmd/ucat -l -p "$port" | rate | md5cmd &
sleep 1
godo ./cmd/ucat localhost "$port" < "$1"
wait

# Now check the hashes match (yes you).
