#! /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 but this code isn't run in
	# these cases (Hurd).  Use for sending signals and checking if
	# init is running.
	PID=1

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

	# Replace old control channel with symlink
	ln -s "$INITCTL" "$OLDINITCTL.new"
	mv "$OLDINITCTL.new" "$OLDINITCTL"

	# Reopen control channel (uses new channel).
	kill -s USR1 "$PID"

	# Tell init to re-exec itself.  We loop on failure to reduce
	# the chance of a race before the new control channel is
	# opened.
	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

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

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

umask 022

rm -f /etc/ioctl.save

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

restart=yes

chroot=0
ischroot || chroot="$?"

if [ "$chroot" != "1" ]; then
	restart=no
fi

# If systemd is running, don't restart init or doing any initctl
# migration.
if [ -e /sys/fs/cgroup/systemd ]; then
	restart=no
fi
if [ "$(uname -s)" = "GNU" ]; then
	restart=no
fi

if [ "$restart" = "yes" ]; then
	do_restart
else
	echo "Not restarting sysvinit"
fi

#DEBHELPER#

exit 0
