#!/bin/sh
# Copyright (C) 2020 OpenCFD Ltd.
# SPDX-License-Identifier: (GPL-3.0+)

# Script-based definition of tutorial tests
# Run from top-level directory, or from debian directory

# Process debian/tests/tutorials.list
# where each line corresponds to a tutorials/directory/name.
#
# Blank and comment lines are ignored.

# ---------------------------------------------------------------------------

# The debian directory is the parent directory
debianDir="${0%/*}/.."

if [ -f "$debianDir"/tests/control ]
then
    # Change to debian/tests
    cd "$debianDir"/tests || exit 1
else
    echo "${0##*/} Error: no tests/control file" 1>&2
    exit 2
fi

[ -w control ] || {
    echo "${0##*/} Error: non-writable tests/control file" 1>&2
    exit 1
}


# Content for no tests
noTests()
{
    cat <<NO_TEST
# No tests defined.
# Use debian/scripts/config-tests to generate tests

Test-Command: true
NO_TEST
}


# Reset with fresh tests
noTests > control

unset binary

case "$1" in
(-clean | -remove | clean | remove)
    exit 0  # Already done
    ;;

(-binary=*)
    binary="${1#*=}"
    ;;
esac


# Create tests

[ -f tutorials.list ] || {
    echo "${0##*/} Error: no tests/tutorials.list" 1>&2
    exit 2
}

[ -n "$binary" ] || {
    echo "${0##*/} Error: no test binary specified." 1>&2
    echo "    Eg, -binary=/usr/bin/openfoamXYZ" 1>&2
    exit 1
}

cat << HEADER > control
# Tests generated for $binary
# from  debian/tests/tutorials.list
# using debian/scripts/config-tests
HEADER

count=0
while read -r line
do
    tutorial=$(echo "$line" | sed -e 's@#.*$@@' -e 's@[ ]*@@g')
    [ -n "$tutorial" ] || continue

    index=$(printf "%02d" $count)
    count="$((count + 1))"

    # InputDir: incompressible/icoFoam/cavity/cavity
    # TestName: icoFoam_cavity

    solver="${tutorial#*/}"
    solver="${solver%%/*}"
    testName="test$index.${solver}_${tutorial##*/}"

cat << TEST >> control

Test-Command: $binary -test-tutorial -- \\
    $tutorial
Restrictions: allow-stderr
Features:     test-name=$testName
TEST

done < tutorials.list


if [ "$count" -eq 0 ]
then
    echo "Warning: no tests defined" 1>&2
    noTests
    exit 1  # No tests found
else
    echo "Configured $count tests using \"$binary -test-tutorial\"" 1>&2
    exit 0  # A clean exit
fi

# -----------------------------------------------------------------------------
