#!/usr/bin/env bash

# Copyright 2022, FOSS-VG Developers and Contributers
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# version 3 along with this program.
# If not, see https://www.gnu.org/licenses/agpl-3.0.en.html

source scripts/lib.sh

echo -n "Using LD_LIBRARY_PATH "
if [ -z "$LD_LIBRARY_PATH" ]; then
    export LD_LIBRARY_PATH=./bin/lib
else
    export LD_LIBRARY_PATH=./bin/lib:"$LD_LIBRARY_PATH"
fi
echo "$LD_LIBRARY_PATH"

echo ">>> Cleaning tests..."
remove bin/test
create_directory bin/test

echo ">>> Building tests..."

# add compile commands to this array
COMPILE_COMMANDS=(
    "$CXX_WITH_FLAGS src/test/nbt_read_write_helpers.cpp -I./include -Lbin/lib -l:nbt.so -o bin/test/nbt_read_write_helpers"
    "$CXX_WITH_FLAGS src/test/cli_argument_parser.cpp -Lbin/lib -l:cli.so -o bin/test/cli_argument_parser"
    "$CXX_WITH_FLAGS src/test/javacompat.cpp -I./include -Lbin/lib -o bin/test/javacompat"
    "$CXX_WITH_FLAGS src/test/nbt_tags.cpp -I./include -Lbin/lib -l:nbt.so -o bin/test/nbt_tags"
    "$CXX_WITH_FLAGS src/test/nbt_size_helpers.cpp -I./include -Lbin/lib -l:nbt.so -o bin/test/nbt_size_helpers"
    "$CXX_WITH_FLAGS src/test/file.cpp -I./include -Lbin/lib -l:file.so -o bin/test/file"
    "$CXX_WITH_FLAGS src/test/varint.cpp -I./include -Lbin/lib -o bin/test/varint"
)
for command in ${!COMPILE_COMMANDS[@]}; do
    echo "${COMPILE_COMMANDS[command]}"
    ${COMPILE_COMMANDS[command]} &
    $WAIT_ANYWAY
done

wait

echo ">>> Running tests..."

# explicitly allow commands to fail at this stage
set +e

for test in $(ls bin/test); do
    bin/test/$test
done

for test in $(ls scripts/test); do
    scripts/test/$test
done
