#!/usr/bin/env bash

## Copyright (C) 2019-2021 The VSL Team
## Licensed under MIT
##
##     @script.name [OPTION] ARGUMENTS...
##
## Options:
##     -h, --help                            Prints usage and example
##         --stats                           Execute with stats
##         --prod                            Execute with prod build
##         --use-cblas                       Execute tests using cblas
##         --use-autofree                    Execute tests using atofree
##         --use-gc=STRATEGY                 Execute tests using garbage collector
##         --skip-examples                   Skip examples compilation
##

ROOT=$(realpath "$(dirname "$0")")

source "${ROOT}/util/easyoptions/easyoptions.sh" || exit
source "${ROOT}/util/logs.sh" || exit

set -eo pipefail

vsl_dir_path=$(dirname "$(dirname "$0")")

flags=""

if [[ -n "${use_cblas}" ]]; then
    echo "Running tests using Open BLAS"
    flags="${flags} -d vsl_vlas_cblas"
fi

if [[ -n "${use_autofree}" ]]; then
    echo "Running tests using V Math"
    flags="${flags} -autofree"
fi

if [[ -n "${use_gc}" ]]; then
    echo "Running tests using V Math"
    flags="${flags} -gc ${use_gc}"
fi

if [[ -n "${stats}" ]]; then
    echo "Running tests with stats"
    flags="${flags} -stats"
fi

if [[ -n "${prod}" ]]; then
    echo "Running tests with prod"
    flags="${flags} -prod"
fi

echo "Executing tests with command: \"v ${flags} test .\""
v ${flags} test "${vsl_dir_path}"

find "${vsl_dir_path}" -name '*_test' -exec rm -f {} +

if [[ -z "${skip_examples}" ]]; then
    echo "Compiling examples"
    echo "Compiling Examples with flags ${flags}"
    for file in $(find "${vsl_dir_path}" -wholename '*/examples/*.v'); do
        if [[ "${file}" == *"not_ci"* ]]; then
            echo "Skipping ${file}"
            continue
        fi
        echo "Compiling ${file}"
        v ${flags} -d vsl_vcl_dlopencl -o "${file}.o" "${file}"
        echo "${file}.o created"
        echo "Removing ${file}.o"
        rm -f "${file}.o"
    done
else
    echo "Skipping examples compilation"
fi
