#!/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
}

# Run pdsh with the given arguments on c1 and c2. With slurm, hold both
# nodes in a job while pdsh runs, as pam_slurm only allows ssh logins to
# nodes on which the user has a running job.
run_pdsh_on_computes() {
	if [[ "${RESOURCE_MANAGER}" != "slurm" ]]; then
		run pdsh "$@"
		return
	fi

	local jobid
	jobid=$(sbatch --parsable -N 2 -w "c[1-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 "$@"

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

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

	run_pdsh_on_computes -S -w "c[1-2]" 'grep . /proc/sys/kernel/ostype'
	assert_success
}

@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 -S -P normal -R exec grep . /proc/sys/kernel/ostype
	else
		# The partition can contain more nodes than c1 and c2; filter
		# its node list down to those two with a regex
		run_pdsh_on_computes -S -P normal -w '/^c[12]$/' 'grep . /proc/sys/kernel/ostype'
	fi
	assert_success
}
