#!/bin/sh
set -e

check_init_is_runit () {
	echo "detecting runit-init"
	if [ -f /etc/runit/stopit ]; then
		echo "OK"
	else
		echo "init is not runit"
		exit 1
	fi
}

check_services_are_running () {
	echo "detecting gettys"
	if pidof getty; then
		echo "OK"
	elif pidof fgetty; then
		echo "OK"
	else
		echo " no getty to perform login with "
		exit 1
	fi
	echo "getting the runsvdir log:"
	ps aux | grep runsvdir
	echo "Detecting active services.."
	sv status /etc/service/*
	service udev status
#	service --status-all #not usable since hwclock.sh writes to stderr with [?]
	pstree
	echo "OK"
}


if [ -z "$AUTOPKGTEST_REBOOT_MARK" ]; then
	if [ -d /run/systemd/system ]; then
		init=systemd
	elif [ -e /run/initctl ]; then
		init=sysv
	else
		init=unknown-init
	fi
	echo "testbed is running with $init"

	# Installation runit-init must be done inside the test 
	# until it becomes a dependency of 'init' package

	echo "installing runit-init"
	#2 steps because of changes in apt(2.3.12) #1005881
	#apt-get remove -y -allow-remove-essential init # no longer works....use dpkg
	dpkg -r --force-remove-protected init
	apt-get  install -y --allow-remove-essential systemd-sysv-  runit-init
	ls -l /etc/service/
	update-service --remove  dbus.dep-fixer
	if [ -e /tmp/autopkgtest-reboot ]; then
		if [ ! -h /etc/service/getty-ttyS0 ]; then
			echo "WARNING: serial getty is disabled"
			ln -s /etc/sv/getty-ttyS0 /etc/service/
			echo "serial getty: enabled"
		fi
		echo "preparing for reboot"
		/tmp/autopkgtest-reboot-prepare runit1
		if [ "$init" = "systemd" ]; then
			systemctl reboot
		else
			reboot
		fi
	else
		echo "testbed does not support reboot"
		echo "can't perform this test"
		exit 1
	fi
elif [ "$AUTOPKGTEST_REBOOT_MARK" = runit1 ]; then
	check_init_is_runit
	check_services_are_running

	echo "Attempting a reboot with runit"
	/tmp/autopkgtest-reboot-prepare runit2
	reboot
else
	check_init_is_runit
	check_services_are_running
	echo "init-switch test completed"
	echo "OK: test done" && exit 0
fi

echo "FAIL: init-switch test failed" && exit 1
