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

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

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

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

@test "[Compilers] compiler module loaded (${LMOD_FAMILY_COMPILER})" {
	module list "${LMOD_FAMILY_COMPILER}" &>"${OUTPUT}" || exit 1
	run grep "${LMOD_FAMILY_COMPILER}" "${OUTPUT}"
	assert_success
}

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

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

@test "[Compilers] C, C++, and Fortran versions match module (${LMOD_FAMILY_COMPILER})" {
	local my_family
	if [[ "${LMOD_FAMILY_COMPILER}" =~ "acfl" ]]; then
		# The arm compiler package set "acfl".
		# OpenHPC expects "arm1".
		my_family="arm1"
	else
		my_family="${LMOD_FAMILY_COMPILER}"
	fi
	module list "${my_family}" &>"${OUTPUT}" || exit 1
	local my_mod_version
	my_mod_version=$(sed '/^\s*$/d' "${OUTPUT}" | sed 's/^[ \t]*//' | tail -1 | awk -F "${my_family}/" '{print $2}')

	if [[ "${my_family}" = "intel" ]]; then
		local version
		version=$(icx --version | awk 'sub(/^.* 202/,"202",$0){print $1;exit}')
		assert_equal "${my_mod_version}" "${version}"
	elif [[ "${my_family}" =~ "arm1" ]]; then
		assert_equal "${my_mod_version}" "compat"
	elif [[ "${my_family}" =~ "gnu" ]]; then
		local version
		version=$(gcc --version | head -1 | awk '{print $3}')
		assert_equal "${my_mod_version}" "${version}"
		version=$(g++ --version | head -1 | awk '{print $3}')
		assert_equal "${my_mod_version}" "${version}"
		version=$(gfortran --version | head -1 | awk '{print $4}')
		assert_equal "${my_mod_version}" "${version}"
	elif [[ "${my_family}" =~ "llvm" ]]; then
		local version
		version=$(clang --version | head -1 | awk '{print $3}')
		assert_equal "${my_mod_version}" "${version}"
		version=$(clang++ --version | head -1 | awk '{print $3}')
		assert_equal "${my_mod_version}" "${version}"
		version=$(flang --version | head -1 | awk '{print $3}')
		assert_equal "${my_mod_version}" "${version}"
	else
		flunk "Unsupported compiler toolchain"
	fi
}
