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

TEST_PATH=$(dirname "${1}")
BNAME=$(basename "${1}")

# the test name is {TEST_NAME}-{TOKEN_DRIVER}.t
# split extension
NAME=${BNAME%.*}
TEST_NAME=${NAME%-*}
TOKEN_DRIVER=${NAME#*-}

if [ -f "./tmp.${TOKEN_DRIVER}/testvars" ]; then
    # shellcheck source=/dev/null # we do not care about linting this source
    source "./tmp.${TOKEN_DRIVER}/testvars"
else
    exit 77 # token not configured, skip
fi

# some tests are compiled, others are just distributed scripts
# so we need to check both the current tests build dir and the
# source tests dir in the out-of-source buils case (used by
# make distcheck for example)
if [ -f "${TEST_PATH}/t${TEST_NAME}" ]; then
    COMMAND="${TEST_PATH}/t${TEST_NAME}"
else
    COMMAND="./t${TEST_NAME}"
fi

# Run the tests under valgrind with appropriate flags
if [ -n "$VALGRIND" ] && [ -n "$LOG_COMPILER" ]; then
    CHECKER="$LOG_COMPILER"
fi

# for compiled tests, we need to add valgrind/checker
if [ -f "${TEST_PATH}/t${TEST_NAME}.c" ]; then
    COMMAND="$CHECKER $COMMAND"
fi

for option in "${TEST_PARAMS[@]}"; do
    if [[ "$option" == "proxy" ]]; then
        COMMAND="${TESTSSRCDIR}/softhsm-proxy.sh $COMMAND"
    fi
done

echo "Executing ${COMMAND}"
${COMMAND}
