#!/bin/sh
set -e

rc=0
is_init=
isrunit=/usr/sbin/runit-init
issystemd=/usr/lib/systemd/systemd

print_init_link_target () {
	echo "detecting testbed init target:"
	echo "/usr/sbin/init link points to"
	readlink -f /usr/sbin/init
	echo ""; echo "";
	#pstree
}

echo "Starting test: apt-init-switch:"

print_init_link_target #systemd expected
is_init=$(readlink -f /usr/sbin/init)
if [ "$is_init" != "$issystemd" ]; then
	echo "WARN: init is not systemd"
	echo "WARN: test results are not reliable"
	rc=$((rc+1))
fi

## list of changes that caused breaks on this test far.. ##
# * (2019) #initial version: use apt's -y --allow-remove-essential (with the "Yes, do as I say")
# * (2021/2022) #2 steps because of changes in apt(2.3.12) #1005881
      # apt is no loger able to remove the init metabpackage and install runit-init
      # in one command; needs to first remove the init metapackage, then
      # with another command install runit-init
# * (2023) #apt-get remove -y -allow-remove-essential init # no longer works:
         # use 'dpkg -r --force-remove-essential' instead  (it has a way more stable interface)
# * (2024) # use the right --force dpkg option, due to i-s-h gaining protected:yes
         # now use --force-remove-protected
# * (2025) # use the --allow-remove-essential to remove system-sysv (-->gains protected yes)
# * (2026) somewhere in between apt(2.3.12) and apt(3.20) apt start to consider installing
      # runit X on top of the same runit version a downgrade (why it needs to reinstall it
      # in the first place?) and fails with
      # "E: Packages were downgraded and -y was used without --allow-downgrades"
      # adding --allow-downgrades to work around this

echo "(dpkg) remove init metapackage:"
dpkg -r --force-remove-protected init
echo "done"
echo ""; echo "";

echo "test 1: try to install runit-init.."
apt-get  install -y --allow-remove-essential --allow-downgrades systemd-sysv-  runit-init

is_init=$(readlink -f /usr/sbin/init) #runit-init expected
if [ "$is_init" != "$isrunit" ]; then
	echo "FATAL: init does not point to runit-init"
	rc=$((rc+1))
else
	echo "OK: init points to runit-init"
fi
echo ""; echo "";

echo "test 2: going back to systemd.."
apt-get  install -y --allow-remove-essential --allow-downgrades  runit-init- systemd-sysv

is_init=$(readlink -f /usr/sbin/init) #systemd expected
if [ "$is_init" != "$issystemd" ]; then
	echo "FATAL: init does not point to runit-init"
	rc=$((rc+1))
else
	echo "OK: init points to systemd"
fi

echo "done"
exit $rc
