# 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 ===="

# first check unit tests still pass

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

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

# generate form files
cd $UNITTEST_DIR
python3 -B -u ${DOLFINX_SOURCE_DIR}/cpp/cmake/scripts/generate-form-files.py ${DOLFINX_SOURCE_DIR}/$UNITTEST_DIR

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

echo "== run C++ unit tests == "
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-real $DEMO_DIR

cd $DEMO_DIR

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

cd ${DOLFINX_SOURCE_DIR}
