#! /bin/sh
#
# sysv-rc prerm
#

set -e

revert_to_legacy_ordering() {
    # First, check that we have all the needed actions recorded
    present=""
    missing=""
    for script in /etc/init.d/* ; do
	name=$(basename $script)
	case $name in
	    *.dpkg*)
		continue;
		;;
	esac
	enabled=""
	for f in $(ls /etc/rc?.d/[KS][0-9][0-9]$name 2> /dev/null) ; do
	    if [ -e $f ] ; then
		if [ ! -f /var/lib/update-rc.d/$name ] ; then
		    missing="$missing $script"
		else
		    present="$present $name"
		fi
		break;
	    fi
	done
    done

    if [ "$missing" ] ; then
	# Not using debconf, as might not be available when the
	# package is removed.
	cat <<EOF

Unable to revert to legacy boot ordering and remove sysv-rc.  Missing
update-rc.d information for the following packages:

EOF
	# Map from script to packages
	for pkg in $(dpkg -S $missing | cut -d: -f1 | sort -u) ; do
	    if dpkg -l $pkg | grep -q ^ii ; then
		echo "  $pkg"
		reconf="$reconf $pkg"
	    else
		echo "  $pkg (removed but not purged)"
	    fi
	done
	cat <<EOF

This is due to earlier issues with sysv-rc and insserv.  To work
around this issue, the packages listed need to register the
update-rc.d call again, for example using

  dpkg-reconfigure $reconf

before trying again to migrate to legacy boot ordering.  The removed
packages might need to be purged.  For some packages, purging and
reinstalling might be needed to record the update-rc.d call.

Aborting package removal until this is done, to avoid leaving the boot
system in a non-functioning state.  The insserv package needs to be
installed to be able to reconfigure the packages.

EOF
	return 1
    fi

    # Enable legacy boot ordering, remove all start and stop symlinks,
    # and register all scripts again.
    echo "warning: reverting to legacy boot ordering"
    touch /etc/init.d/.legacy-bootordering
    for script in $present ; do
	rm /etc/rc?.d/[KS][0-9][0-9]$script
	sh /var/lib/update-rc.d/$script > /dev/null
    done

    # Remove files generated by insserv to disable concurrent booting
    rm -f /etc/init.d/.depend.boot
    rm -f /etc/init.d/.depend.start
    rm -f /etc/init.d/.depend.stop

    return 0
}

case "$1" in
	remove)
            # Refuse to be uninstalled unless all the needed
            # update-rc.d calls are recorded already.
	    if [ ! -f /etc/init.d/.legacy-bootordering ] ; then
		revert_to_legacy_ordering
		exit $?
	    fi
	    ;;
	*) : ;;
esac



exit 0
