# Run C++ tests and demos

set -e

# Tests real build by default.
# Access the complex build by setting env variable USE_DOLFINX_COMPLEX

if [ "x${USE_DOLFINX_COMPLEX}" != "x" ]; then
    TESTDIR_SUFFIX="-complex"
    TEST_DESCRIPTION="for complex build "
    export PETSC_DIR=/usr/lib/petscdir/petsc-complex
    export SLEPC_DIR=`grep wPETSC_DIR ${PETSC_DIR}/lib/petsc/conf/petscvariables | awk '{print $3}' | sed "s/petsc/slepc/g"`
    # process ufl forms for complex test: second argument 1 indicates complex
    UFL_TYPE=1
else
    TESTDIR_SUFFIX="-real"
fi

# allow parallel jobs, but don't load up more than 8
NPROC=$( nproc )
MAX_CPU=8
N_CPU=$(( NPROC > MAX_CPU ? MAX_CPU : NPROC ))

echo "nproc reports $NPROC processors are available"

# MPI tests are set up to run on 3 processes. Spread them leanly over the available processors (don't have more than 2 tests using one processor).
# e.g. run 1 MPI test at a time over 1-3 processors, or 2 tests at a time over 4-6 processors, or 3 tests over 7-9 processors, etc.
N_MPI=3
N_MPI_TESTS=$(( (N_CPU+N_MPI-1)/N_MPI ))

export OMPI_MCA_plm_rsh_agent=/bin/false
export OMPI_MCA_rmaps_base_oversubscribe=1

echo "==== running C++ tests ${TEST_DESCRIPTION}===="

# first check unit tests still pass

UNITTEST_SOURCE_DIR=./cpp/test
DOLFINX_SOURCE_DIR=$(pwd)

UNITTEST_DIR=./dolfinx-unittests${TESTDIR_SUFFIX}
rm -rf $UNITTEST_DIR
mkdir $UNITTEST_DIR
cp -r ${DOLFINX_SOURCE_DIR}/${UNITTEST_SOURCE_DIR} $UNITTEST_DIR

# build tests
cd $UNITTEST_DIR/test
cmake -DCMAKE_C_COMPILER=mpicc .
make -j${N_CPU} all VERBOSE=1

echo "== run C++ unit tests ${TEST_DESCRIPTION}== "
CTEST_OUTPUT_ON_FAILURE=1 make test VERBOSE=1
cd ${DOLFINX_SOURCE_DIR}


# then check demos run successfully

DEMO_DIR=./dolfinx-demo

rm -rf $DEMO_DIR
cp -rL /usr/share/dolfinx/demo-cpp $DEMO_DIR

cd $DEMO_DIR

if [ "x${SKIP_TEST_LIST}" != "x" ]; then
    echo "set(CTEST_CUSTOM_TESTS_IGNORE ${SKIP_TEST_LIST} )" >> CTestCustom.cmake
fi

cmake -DCMAKE_C_COMPILER=mpicc .
make -j${N_CPU} all VERBOSE=1
echo "== run C++ demos ${TEST_DESCRIPTION}=="
CTEST_OUTPUT_ON_FAILURE=1 make test VERBOSE=1

cd ${DOLFINX_SOURCE_DIR}
