#!/bin/sh

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

PORT=12345
TIMEOUT=10

if [ -n "${AUTOPKGTEST_TMP+x}" ]; then
    NC="$(command -v nc.openbsd)"
    TEMPDIR="$AUTOPKGTEST_TMP"
else
    NC="./nc"
    TEMPDIR="${TMPDIR:-/tmp}"
fi
echo "I: Using NC=$NC and TEMPDIR=$TEMPDIR"

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

timeout="$TIMEOUT"
while [ $timeout -ge 0 ]; do
    # give the server a chance to bind(2)
    if $NC -N 127.0.0.1 $PORT <"$TEMPDIR/stdin"; then
        break
    fi
    sleep 1
    timeout=$((timeout - 1))
done
if [ $timeout -le 0 ]; then
    echo Timeout >&2
    kill $PID
    exit 1
fi

wait $PID
if $NC -z 127.0.0.1 $PORT; then
    echo Still listening on $PORT >&2
    exit 1
fi
diff -u -- "$TEMPDIR/stdin" "$TEMPDIR/stdout" || exit 1

exit 0
# vim: set filetype=sh :
