# This regression test is a part of SIPp.
# Author: Walter Doekes, OSSO B.V., 2014

init() {
    # Jump into the directory where the test is.
    cd "`dirname "$0"`"

    # Print a nice message.
    printf "Testing %s: " "`basename \`pwd\``"
}

# Allow SIPP=/path/to/sipp to override autodetection.  Please use an
# absolute path.  This allows you to test a different version.
get_sipp() {
    if test -z "$SIPP"; then
        # The cd in init() jumps to the directory where the test lives.
        # We traverse upwards in the directory until we find the sipp
        # binary.
        tmp=`pwd`
        while ! test -x "$tmp/sipp"; do
            tmp=`dirname "$tmp"`
            test "$tmp" = "/" && break
        done
        test -x "$tmp/sipp" || exit 1
        SIPP="$tmp/sipp"
    fi
    echo "$SIPP"
}

sipp() {
    exec "`get_sipp`" "$@"
}

sippversion() {
    "`get_sipp`" -v | sed -e 's/^ //;/SIPp/!d;s/ built.*//'
}

sippfg() {
    timeout -sKILL 183 "`get_sipp`" -nostdin "$@"
}

sippbg() {
    temp=`mktemp`
    sipp -nostdin "$@" >$temp 2>&1 </dev/null &
    pid=$!
    sleep 1
    if ! /bin/kill -0 $pid 2>/dev/null; then
        wait $pid
        ret=$?
        if test $ret -ne 0; then
            echo "sipp $@: startup failure, got $ret:" >&2
            cat $temp
            rm $temp
            exit 1
        fi
    fi
    rm $temp
}

tcplisten() {
    port="$1"
    exec perl -e '
        use Socket;$|=1;(socket(S,PF_INET,SOCK_STREAM,6)&&
        setsockopt(S,SOL_SOCKET,SO_REUSEADDR,1)&&
        bind(S,pack_sockaddr_in('$port',"\0\0\0\0"))&&
        listen(S,1)&&($sa=accept(N,S))&&(($port,$ia)=
        unpack_sockaddr_in($sa))&&($ia=inet_ntoa($ia))&&
        print "Connection from $ia:$port\n")||die($!);
        close(S);while(1){recv(N,$o,2048,0);print "$o";}'
}

udplisten() {
    port="$1"
    exec perl -e '
        use Socket;$|=1;(socket(S,PF_INET,SOCK_DGRAM,17)&&
        bind(S,pack_sockaddr_in('$port',"\0\0\0\0"))&&
        setsockopt(S,SOL_SOCKET,SO_RCVTIMEO,pack("L!L!",3,0))&&
        ($sa=recv(S,$o,2048,0))&&(($port,$ia)=
        unpack_sockaddr_in($sa))&&($ia=inet_ntoa($ia))&&
        print "Connectionless from $ia:$port\n$o\n")||die($!);
        close(S);'
}

cleanup() {
    # Kill all of our children, if there are any.
    pkill -P$$
    wait
}

ok() {
    echo "."
    cleanup
    exit 0
}

fail() {
    test -z "$@" && echo "failed" || echo "failed ($@)"
    cleanup
    exit 1
}

unexpected_ok() {
    echo "unexpected success"
    cleanup
    exit 2
}

expected_fail() {
    echo "x"
    cleanup
    test -n "$VERBOSE_EXITSTATUS" && exit 3
    exit 0
}

skip() {
    echo "skipped ($@)"
    cleanup
    test -n "$VERBOSE_EXITSTATUS" && exit 4
    exit 0
}

# Workaround when no term is set. See also github-#0075.
export TERM=dumb

# vim: set syn=sh ts=8 sw=4 sts=4 et ai:
