#!/bin/bash

# external.test

SCRIPT_DIR="$(dirname "$0")"

server=www.wolfssl.com
ca=./certs/wolfssl-website-ca.pem

[ ! -x ./examples/client/client ] && echo -e "\n\nClient doesn't exist" && exit 1

# www.wolfssl.com isn't using RFC 8446 yet but the draft instead.
if ! ./examples/client/client -V | grep -q 3; then
    echo 'skipping external.test because TLS1.2 is not available.' 1>&2
    exit 77
fi

# cloudflare seems to change CAs quickly, disabled by default
if test -n "$WOLFSSL_EXTERNAL_TEST"; then

    BUILD_FLAGS="$(./examples/client/client '-#')"
    if echo "$BUILD_FLAGS" | fgrep -q -e ' -DWOLFSSL_SNIFFER '; then
        echo 'skipping WOLFSSL_EXTERNAL_TEST because -DWOLFSSL_SNIFFER configuration of build is incompatible.'
        exit 77
    fi

    if echo "$BUILD_FLAGS" | fgrep -v -q -e ' -DHAVE_ECC '; then
        echo 'skipping WOLFSSL_EXTERNAL_TEST because -UHAVE_ECC configuration of build is incompatible.'
        exit 77
    fi

    echo "WOLFSSL_EXTERNAL_TEST set, running test..."
else
    echo "WOLFSSL_EXTERNAL_TEST NOT set, won't run"
    exit 77
fi

# is our desired server there?
"${SCRIPT_DIR}"/ping.test $server 2
RESULT=$?
[ $RESULT -ne 0 ] && exit 0

# client test against the server
./examples/client/client -X -C -h $server -p 443 -g -A $ca
RESULT=$?
[ $RESULT -ne 0 ] && echo -e "\n\nClient connection failed" && exit 1

# test again, but using system CA certs to verify the server if support is enabled.
# We don't want to use --sys-ca-certs with static memory, as we don't know how
# much memory will be required to store an unbounded number of certs
BUILD_FLAGS="$(./examples/client/client '-#')"
if echo "$BUILD_FLAGS" | grep -q "WOLFSSL_SYS_CA_CERTS" && ! echo "$BUILD_FLAGS" | grep -q "WOLFSSL_STATIC_MEMORY"; then
    echo -e "\nConnecting using WOLFSSL_SYS_CA_CERTS..."
    ./examples/client/client -X -C -h $server -p 443 -g --sys-ca-certs
    RESULT=$?
    [ $RESULT -ne 0 ] && echo -e "\n\nClient connection failed when using WOLFSSL_SYS_CA_CERTS" && exit 1
fi

exit 0
