#!/bin/bash -e
# Copyright (C) 2023 Simo Sorce <simo@redhat.com>
# SPDX-License-Identifier: Apache-2.0

source "${TESTSSRCDIR}/helpers.sh"

title PARA "Test SSL_CTX creation"
$CHECKER ./tlsctx

title PARA "Test an actual TLS connection"

rm -f "${TMPPDIR}/s_server_output"
rm -f "${TMPPDIR}/s_server_ready"
mkfifo "${TMPPDIR}/s_server_ready"

SERVER_PID=-1
# Make sure we terminate programs if test fails in the middle
# shellcheck disable=SC2317  # Shellcheck for some reason does not follow trap
wait_for_server_at_exit() {
    wait "$1"
    echo "Server output:"
    cat "${TMPPDIR}/s_server_output"
}
trap 'wait_for_server_at_exit $SERVER_PID;' EXIT

PORT=23456

expect -c "spawn $CHECKER openssl s_server -accept \"${PORT}\" -naccept 1 -key \"${PRIURI}\" -cert \"${CRTURI}\";
    set timeout 60;
    expect {
        \"ACCEPT\" {};
        default {exit 1;};
    }
    set server_ready [open \"${TMPPDIR}/s_server_ready\" w+];
    puts \$server_ready \"READY\n\";
    close \$server_ready;
    expect {
        \"END SSL SESSION PARAMETERS\" {};
        default {exit 1;};
    }
    send \" TLS SUCCESSFUL \n\"
    send \"Q\n\"
    expect {
        eof {exit 0;};
        default {exit 1;};
    }" > "${TMPPDIR}/s_server_output" &
SERVER_PID=$!

read -r < "${TMPPDIR}/s_server_ready"

expect -c "spawn $CHECKER openssl s_client -connect \"localhost:${PORT}\";
    set timeout 60;
    expect {
        \" TLS SUCCESSFUL \" {};
        default {exit 1;};
    }
    expect {
        eof {exit 0;};
        default {exit 1;};
    }"

exit 0;
