#!/usr/bin/env -S bats --report-formatter junit --formatter tap
# -*-sh-*-

load ../../common/test_helper_functions || exit 1
source ../../common/functions || exit 1

if [ -s ../../common/TEST_ENV ]; then
	source ../../common/TEST_ENV
fi

setup() {
	OUTPUT="$(mktemp)"

	export OUTPUT
}

teardown() {
	rm -f "${OUTPUT}"
}

@test "[MPI] MPI module loaded (${LMOD_FAMILY_COMPILER}/${LMOD_FAMILY_MPI})" {
	module list "${LMOD_FAMILY_MPI}" &>"${OUTPUT}" || exit 1
	local my_module
	my_module=$(sed '/^\s*$/d' "${OUTPUT}" | sed 's/^[ \t]*//' | tail -1)
	echo "${my_module}" | grep -q "1) ${LMOD_FAMILY_MPI}/"
	assert_success
}

@test "[MPI] MPI module version available (${LMOD_FAMILY_COMPILER}/${LMOD_FAMILY_MPI})" {
	module list "${LMOD_FAMILY_MPI}" &>"${OUTPUT}" || exit 1
	local my_version
	my_version=$(sed '/^\s*$/d' "${OUTPUT}" | sed 's/^[ \t]*//' | tail -1 | awk -F "${LMOD_FAMILY_MPI}/" '{print $2}')

	if [ -z "${my_version}" ]; then
		flunk "ERROR: unable to ascertain module version (${my_version})"
	fi
}

@test "[MPI] mpicc, mpicxx, and mpif90 versions match module (${LMOD_FAMILY_COMPILER}/${LMOD_FAMILY_MPI})" {
	module list "${LMOD_FAMILY_MPI}" &>"${OUTPUT}" || exit 1
	local my_mod_version
	my_mod_version=$(sed '/^\s*$/d' "${OUTPUT}" | sed 's/^[ \t]*//' | tail -1 | awk -F "${LMOD_FAMILY_MPI}/" '{print $2}')

	# strip off ucx|ofi if present in module version string (e.g. for mpich variants)
	if [[ "${my_mod_version}" =~ "-ucx" ]]; then
		my_mod_version=$(echo "${my_mod_version}" | awk -F '-ucx' '{print $1}')
	fi

	if [[ "${my_mod_version}" =~ "-ofi" ]]; then
		my_mod_version=$(echo "${my_mod_version}" | awk -F '-ofi' '{print $1}')
	fi

	local mpi_version=""

	if [[ "${LMOD_FAMILY_MPI}" =~ "openmpi" ]]; then
		run which ompi_info
		assert_success

		mpi_version=$(ompi_info -V | head -1 | awk -F v '{print $2}')
	elif [ "${LMOD_FAMILY_MPI}" == "mvapich2" ]; then
		run which mpichversion
		assert_success

		mpi_version=$(mpichversion | grep "MVAPICH Version" | awk '{print $3}')
	elif [ "${LMOD_FAMILY_MPI}" == "mpich" ]; then
		run which mpichversion
		assert_success

		mpi_version=$(mpichversion | grep "MPICH Version" | awk '{print $3}')
	elif [ "${LMOD_FAMILY_MPI}" == "impi" ]; then
		run which mpicc
		assert_success

		mpi_version=$(mpicc -v 2>&1 | head -1 | awk '{print $7}')
	else
		ERROR "Unsupported or unknown MPI family"
	fi

	# Verify runtime version matches module declaration. openmpi and
	# mvapich2 provide very specific version designations via runtime
	# queries. impi is less specific so the queries below differ
	# slightly

	if [ "${LMOD_FAMILY_MPI}" == "impi" ]; then
		run "${BASH}" -c "echo ${my_mod_version} | grep ${mpi_version}"
		assert_success
	else
		assert_equal "${my_mod_version}" "${mpi_version}"
	fi
}
