#! /bin/sh
#
# sysvinit postinst
#

set -e

# Restart init, and migrate to /run/initctl if needed.
do_restart() {
	INITCTL=/run/initctl
	case "$(uname -s)" in
	  *FreeBSD)
		OLDINITCTL=/etc/.initctl
		;;
	  *)
		OLDINITCTL=/dev/initctl
		;;
	esac

	# PID of init; may not always be 1.  Use for sending signals
	# and checking if init is running.
	PID="$(pidof /sbin/init || true)"

	# Create /run/initctl if not present, and also create compatibility
	# symlinks
	if [ "$INITCTL" ] && [ ! -p "$INITCTL" ]
	then
		# Create new control channel
		echo "sysvinit: creating $INITCTL"
		rm -f $INITCTL
		mkfifo -m 600 $INITCTL

		# Replace old control channel (if present) with symlink
		if [ -e "$OLDINITCTL" ]; then
			ln -s "$INITCTL" "$OLDINITCTL.new"
			mv "$OLDINITCTL.new" "$OLDINITCTL"
		fi

		# Reopen control channel (uses new channel).
		if ! ischroot && [ -n "$PID" ]
		then
			kill -s USR1 "$PID"
		fi
	fi
	rm -f /etc/ioctl.save

	if [ ! -f /etc/inittab ]
	then
		cp -p /usr/share/sysvinit/inittab /etc/inittab
	fi

	# Tell init to re-exec itself.  We loop on failure because to reduce
	# the chance of a race before the new control channel is opened.
	if ! ischroot && [ -n "$PID" ]
	then
		echo -n "sysvinit: restarting..."
		for delay in 0 1 2 3 4 5 6 fail;
		do
			if init u
			then
				echo " done."
				break
			else
				if [ "$delay" = "fail" ]
				then
					echo " failed."
				else
					echo -n "."
					sleep "$delay"
				fi
			fi
		done
	else
		if [ -n "$PID" ]
		then
			echo "Not restarting sysvinit: chroot detected"
		else
			echo "Not restarting sysvinit: init not running"
		fi
	fi

	# Remove old pipe if present.  No longer in use after re-exec.
	if [ "$OLDINITCTL" ] && [ -p "$OLDINITCTL" ]
	then
	        rm -f "$OLDINITCTL"
	fi
}

case "$1" in
  configure)
	oldver=$2
	;;
  abort-upgrade|abort-remove|abort-deconfigure)
	exit 0
	;;
esac

umask 022

# If systemd is running, don't restart init or doing any initctl
# migration.
if [ ! -e /sys/fs/cgroup/systemd ] ; then
	do_restart
fi

#DEBHELPER#

exit 0
