#! /bin/sh
set -e

# Make sure sshd is on $PATH.
export PATH="/usr/sbin:$PATH"

CREATED_RUN_SSHD=false
STARTED_HAVEGED=false
ADDED_HOST=false

cleanup () {
	if $ADDED_HOST; then
		sudo sed -i '/[[:space:]]UNKNOWN$/d' /etc/hosts
	fi

	if $STARTED_HAVEGED; then
		if [ -d /run/systemd/system ] && \
		   which systemctl >/dev/null 2>&1; then
			sudo systemctl disable haveged || true
			sudo systemctl stop haveged || true
		else
			sudo start-stop-daemon --stop --quiet --oknodo \
				--retry=TERM/30/KILL/5 \
				--pidfile "$AUTOPKGTEST_TMP/haveged.pid" \
				--name haveged
		fi
	fi

	if $CREATED_RUN_SSHD; then
		sudo rm -rf /run/sshd
	fi
}
trap cleanup EXIT

sudo chsh -s /bin/bash "$(id -un)"

# Depending on how the environment is configured, our test dependency on
# openssh-server may not actually started sshd and thus may not have caused
# /run/sshd to be created.
if [ ! -d /run/sshd ]; then
	sudo mkdir -m755 /run/sshd
	CREATED_RUN_SSHD=:
fi

# If we're running in a container, haveged may not have started
# automatically.
if [ -d /run/systemd/system ] && which systemctl >/dev/null 2>&1; then
	sudo systemctl enable haveged || true
	sudo systemctl start haveged || true
	STARTED_HAVEGED=:
elif ! pidof haveged >/dev/null; then
	sudo start-stop-daemon --start --quiet \
		--pidfile "$AUTOPKGTEST_TMP/haveged.pid" \
		--exec /usr/sbin/haveged -- \
		-p "$AUTOPKGTEST_TMP/haveged.pid"
	STARTED_HAVEGED=:
fi

# ssh ends up setting PAM_RHOST to "UNKNOWN" during a number of regression
# tests, which causes DNS resolution delays, slowing down the test suite
# substantially and causing the connection-timeout tests to fail.  The only
# way to work around this while running tests with "UsePAM yes" appears to
# be to make "UNKNOWN" resolvable.
if ! grep -q '[[:space:]]UNKNOWN$' /etc/hosts; then
	echo '127.0.0.2 UNKNOWN' | sudo tee -a /etc/hosts >/dev/null
	ADDED_HOST=:
fi

annotate-output +%H:%M:%S.%N \
	/usr/lib/openssh/regress/run-tests "$AUTOPKGTEST_TMP" "$@"
