#!/bin/bash
CUR_PATH=$(dirname $(realpath $0))
source "$CUR_PATH/../test_utils/test_utils.sh"

app_name="waitall"
np="4"

APP_DIR="."
[ -n "$BUILD_DIR" ] && APP_DIR="$BUILD_DIR"
APP_PATH="${APP_DIR}/$app_name"
TRACE_DIRNAME="${APP_PATH}_trace"
trace_filename="${TRACE_DIRNAME}/eztrace_log.otf2"

EZTRACE_TEST_OPTION="$EZTRACE_TEST_OPTION -o ${TRACE_DIRNAME}"
[ -n "$EZTRACE_PATH" ] || EZTRACE_PATH=eztrace

[ -n "$MPI_MODULE_NAME" ] || MPI_MODULE_NAME=mpi
EZTRACE_TEST_OPTION="$EZTRACE_TEST_OPTION -t ${MPI_MODULE_NAME}"

run_and_check_command "$MPIRUN_PATH" $MPIRUN_CLI_OPTION -np $np "$EZTRACE_PATH" $EZTRACE_TEST_OPTION "${APP_PATH}"

if ! "$OTF2_PRINT_PATH" "$trace_filename" 2>&1 > /dev/null ; then
    print_error "Cannot parse trace '$trace_filename'"
    exit 1
fi

trace_check_enter_leave_parity  "$trace_filename"
# 2 processes: 100 warmup + 10000 iterations = 2*(100+10000) = 20200 sends and recvs

trace_check_event_type "$trace_filename" "MPI_ISEND" 3
trace_check_event_type "$trace_filename" "MPI_ISEND_COMPLETE" 3
trace_check_event_type "$trace_filename" "MPI_IRECV" 3
trace_check_event_type "$trace_filename" "MPI_IRECV_REQUEST" 3

trace_check_nb_enter "$trace_filename" "MPI_Isend" 3 
trace_check_nb_leave "$trace_filename" "MPI_Isend" 3
trace_check_nb_enter "$trace_filename" "MPI_Irecv" 3 
trace_check_nb_leave "$trace_filename" "MPI_Irecv" 3 

trace_check_nb_enter "$trace_filename" "MPI_Waitall" 4 
trace_check_nb_leave "$trace_filename" "MPI_Waitall" 4 

echo PASS: $nb_pass, FAILED:$nb_failed, TOTAL: $nb_test

exit $nb_failed
