#!/bin/bash

TEST_DIR=$(dirname "$0")
TEST_BIN_DIR=${TEST_DIR}/bin

export ASAN_OPTIONS
ASAN_OPTIONS+=':protect_shadow_gap=0'
ASAN_OPTIONS+=':detect_container_overflow=0'

HEADER_CHARS=80

RED='\e[31m'
NORM='\e[0m'

tests=$(find "${TEST_BIN_DIR}" -type f -perm -111)
failed_tests=""

for test in ${tests[@]}; do
    # Test output header
    test_name="${test/${TEST_BIN_DIR}\//}"
    chars=$(echo "${test_name}" | wc -c)
    linechars=$((${HEADER_CHARS} - ${chars} - 6))
    line=$(printf '%*s' ${linechars} | tr ' ' '-')
    echo -e "\n---[ ${test_name} ]${line}"

    "${test}"

    # Check for test failures
    if [ $? -ne 0 ]; then
        case "${test}" in
            # TODO: Find out why these tests are failing in CI
            *lang/mode/metal|*lang/mode/cuda|*lang/mode/opencl)
            ;;
            *)
                failed_tests+="  - ${test}\n";;
        esac
    fi

    # Test output footer
    printf '%*s\n' ${HEADER_CHARS} | tr ' ' '='
done

if [[ "${failed_tests}" != "" ]]; then
    echo -e "\n\n${RED}---[ Failed tests ]----------------------------${NORM}"
    echo -e "${failed_tests}"
    exit 1
fi
