#!/usr/bin/env -S bats --report-formatter junit --formatter tap -j 4
# -*-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_file() {
	check_rms

	TESTNAME="pdsh"

	# Create SSH key pair if it does not exist and authorize it
	if [[ ! -f "${HOME}/.ssh/id_ed25519" ]]; then
		mkdir -p "${HOME}/.ssh"
		chmod 700 "${HOME}/.ssh"
		ssh-keygen -t ed25519 -N "" -f "${HOME}/.ssh/id_ed25519"
		cat "${HOME}/.ssh/id_ed25519.pub" >> "${HOME}/.ssh/authorized_keys"
		chmod 600 "${HOME}/.ssh/authorized_keys"
	fi

	export TESTNAME
}

@test "[${TESTNAME}] check for RPM (${RESOURCE_MANAGER})" {
	run check_if_rpm_installed "pdsh${DELIM}"
	assert_success
}

@test "[${TESTNAME}] run a shell command on c[1-2] (${RESOURCE_MANAGER})" {
	[[ -n "${SIMPLE_CI}" ]] && skip "SSH not available in SIMPLE_CI"

	if [[ "${RESOURCE_MANAGER}" == "slurm" ]]; then
		local jobid
		jobid=$(sbatch --parsable -N 2 --time=00:05:00 --wrap="sleep infinity")

		# Wait for the job to start running
		local i
		for i in $(seq 1 60); do
			if [[ "$(squeue -j "${jobid}" -h -o "%T")" == "RUNNING" ]]; then
				break
			fi
			sleep 1
		done

		# Run pdsh test and capture result
		run pdsh -S -w c[1-2] 'grep . /proc/sys/kernel/ostype'

		# Clean up the reservation
		scancel "${jobid}"

		assert_success
	else
		run pdsh -S -w c[1-2] 'grep . /proc/sys/kernel/ostype'
		assert_success
	fi
}

@test "[${TESTNAME}] check for pdsh-mod-slurm RPM (${RESOURCE_MANAGER})" {
	[[ "${RESOURCE_MANAGER}" != "slurm" ]] && skip "Only applicable for slurm"

	run check_if_rpm_installed "pdsh-mod-slurm${DELIM}"
	assert_success
}

@test "[${TESTNAME}] run a shell command on -P normal (${RESOURCE_MANAGER})" {
	[[ "${RESOURCE_MANAGER}" != "slurm" ]] && skip "Only applicable for slurm"

	if [[ -n "${SIMPLE_CI}" ]]; then
		run pdsh -P normal -R exec grep . /proc/sys/kernel/ostype
	else
		run pdsh -P normal 'grep . /proc/sys/kernel/ostype'
	fi
	assert_success
}
