#!/bin/sh

set -e

cleanup()
{
	mount -o remount /
}

prepare()
{
	if ! test -w /; then
		if [ "$(id -u)" -ne "0" ]; then
			printf "$0: must be root\n" >&2
			exit 1
		fi
		mount -o remount -w /
		trap cleanup 0
	fi

	if [ ! -L /sbin/init ]; then
		mv /sbin/init /sbin/init.sysvinit
		ln -sf init.wrapper /sbin/init
	fi
	if [ ! -L /etc/dbus-1/system.conf ]; then
		mv /etc/dbus-1/system.conf /etc/dbus-1/system.conf.sysvinit
		ln -sf system.conf.sysvinit /etc/dbus-1/system.conf
	fi
}


case "$1" in
	sysvinit)
	prepare
	echo 'INIT=/sbin/init.sysvinit' > /etc/switch-init.conf
	ln -sf system.conf.sysvinit /etc/dbus-1/system.conf
	;;

	systemd)
	prepare
	echo 'INIT=/usr/lib/systemd/systemd' > /etc/switch-init.conf
	ln -sf system.conf.systemd /etc/dbus-1/system.conf
	;;

	*)
	printf "Usage: $0 {sysvinit|systemd}\nSet default init system to either sysvinit or systemd\n" >&2
	exit 1
	;;
esac

exit 0
