#!/bin/sh

set -ue
PATH="/usr/bin:/bin"
export PATH

NC="$(command -v nc.openbsd)"
PORT=12345
TIMEOUT=10
TEMPDIR="${AUTOPKGTEST_TMP:-"${TMPDIR:-/tmp}"}"

# Basic client/server communication test
$NC -l 127.0.0.1 $PORT </dev/null >"$TEMPDIR/stdout" & PID=$!

timeout="$TIMEOUT"
while [ $timeout -ge 0 ]; do
    # give the server a chance to bind(2)
    ss -nOH -lt src = 127.0.0.1 sport = $PORT >"$TEMPDIR/ss.out"
    if test -s "$TEMPDIR/ss.out"; then
        break
    fi
    sleep 1
    timeout=$((timeout - 1))
done
if [ $timeout -le 0 ]; then
    kill $PID
    exit 1
fi

echo hello >"$TEMPDIR/stdin"
$NC -N 127.0.0.1 $PORT <"$TEMPDIR/stdin"

wait $PID
diff -u -- "$TEMPDIR/stdin" "$TEMPDIR/stdout" || exit 1

exit 0
# vim: set filetype=sh :
