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

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

: "${TEST_PATH=$DNAME}"
: "${TESTBLDDIR=.}"

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

if [ -f "${TESTBLDDIR}/${TOKEN_DRIVER}/testvars" ]; then
    # shellcheck source=/dev/null # we do not care about linting this source
    source "${TESTBLDDIR}/${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 build case (used by
# make distcheck for example)
if [ -f "${TEST_PATH}/t${TEST_NAME}" ]; then
    COMMAND="${TEST_PATH}/t${TEST_NAME}"
else
    COMMAND="${TESTBLDDIR}/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

LOGFILE="${TESTBLDDIR}/${TEST_NAME}.${TOKEN_DRIVER}.log"

echo "Executing ${COMMAND}"
(
  set -o pipefail
  ${COMMAND} 2>&1 | tee "${LOGFILE}"
)
