#!/bin/sh
#
# Author: Petter Reinholdtsen
# Date: 2005-09-03
#
# Update the boot order based on init.d script dependency info

set -e

now=`date +%Y%m%dT%H%M`
logdir=/var/lib/insserv
backupfile="$logdir/bootscripts-$now.tar.gz"
listfile="$logdir/bootscripts-$now-after.list"
logfile="$logdir/run-$now.log"
flagfile="$logdir/using-insserv"

# Make sure insserv is in path
PATH=/sbin:$PATH

convert_rc_s_to_k() {
  runlevel=$1
  for link in $(cd $target/etc/rc$runlevel.d; ls S* || true); do
      set `echo $link|sed "s%S\(..\)\(.*\)%\1 \2%"`
      seq=$1
      service=$2
      mv $target/etc/rc$runlevel.d/$link $target/etc/rc$runlevel.d/K$seq$service
  done
}

if [ restore = "$1" ] ; then
    if [ ! -f $flagfile ] ; then
	echo "error: The boot system is not currently converted to insserv."
	echo "error: Flag file $flagfile is missing."
	echo "error: Unable to remove the use of insserv."
	exit 1
    fi

    # Check if there has been changes, or if it is safe to restore
    # from backup

    # Pick the last list of symlinks.
    for file in $logdir/bootscripts-*-after.list ; do
	listfile=$file
    done
    ls /etc/init.d /etc/rc*.d > "$logdir/current.list"

    # If the rc.d scripts order look like it did when we converted, it
    # is safe to restore.
    if [ -f $listfile ] && cmp $logdir/current.list $listfile ; then
	rm "$logdir/current.list"
	echo "info: Restoring using backed up copy of init.d/ and rc*.d/."
	for backup in $logdir/bootscripts-*.tar.gz ; do
	    backupfile=$backup
	done
	if [ -f "$backupfile" ] ; then
	    (cd /etc; rm -rf init.d rc*.d; tar zxf $backupfile)
	    echo "info: successfully restored backup of init.d scripts"
	    rm $flagfile
	else
	    echo "error: Unable to locate backup file"
	    exit 1
	fi
    else
	rm "$logdir/current.list"
	echo "error: Unable to restore the boot sequence.  Invalid backup."
	exit 1
    fi
else
    insserv -nv > $logfile 2>&1
    if grep -q 'There is a loop between' $logfile ; then
	echo "error: Problems running insserv:"
	grep 'There is a loop between' $logfile | sed 's/^/  /'
	echo "info: Please check out this manually."
	echo "info: Refusing to convert boot sequence until this is fixed"
	rm $logfile
	exit 1
    fi

    echo "info: Backing up existing boot scripts in $backupfile"
    (cd /etc; tar zcf $backupfile init.d rc*.d)

    echo "info: Reordering boot system, log to $logfile"
    (
	echo "info: Converting rc0.d/S* and rc6.d/S* to K*."
	convert_rc_s_to_k 0
	convert_rc_s_to_k 6
	echo "info: running insserv"
	insserv -v
    ) > $logfile 2>&1

    echo "info: Recording new boot sequence in $listfile"
    ls /etc/init.d /etc/rc*.d > $listfile

    echo "info: Use '$0 restore' to restore the old boot sequence."
    touch $flagfile
fi

exit 0
