#!/bin/bash
#
# rc		This file is responsible for starting/stopping
#		services when the runlevel changes.
#
#		Temporary feature:
#		If the action for a particular feature in the new run-level
#		is the same as the action in the previous run-level, this
#		script will neither start nor start that feature, since that
#		would have no effect except to thrash the system for no reason.
#		Once all scripts are converted to use start-stop-daemon
#		to _start_ their daemons (most of them only use it to kill
#		them), this feature can be removed.
#
# Author:	Miquel van Smoorenburg, <miquels@drinkel.ow.org>
#		Hacked to bits by Bruce Perens <Bruce@Pixar.com>
#

# Un-comment the following for debugging.
# debug=echo

  # Set onlcr to avoid staircase effect.
  stty onlcr 0>&1

  # Now find out what the current and what the previous runlevel are.

  runlevel=$RUNLEVEL
  # Get first argument. Set new runlevel to this argument.
  [ "$1" != "" ] && runlevel=$1

  previous=$PREVLEVEL

  export runlevel previous


  # Is there an rc directory for this new runlevel?
  if [ -d /etc/rc$runlevel.d ]
  then
	avoid=""	# A list of start scripts I don't have to run.

	# First, run the KILL scripts.
	if [ $previous != N ]
	then
		for i in /etc/rc$runlevel.d/K[0-9][0-9]*
		do
			# Check if the script is there.
			[ ! -f $i ] && continue

			suffix=${i#/etc/rc$runlevel.d/K[0-9][0-9]}

			# Generate the name of the start script corresponding
			# to this stop script, the start script in the previous
			# level, and the stop script in the previous level.
			# Check these files, and see if the previous level's
			# files are links to the ones for this level.
			# If they are, this level treats this feature the same
			# as the previous level, and I don't have to run these
			# files.
			identical=0
			start=/etc/rc$runlevel.d/S[0-9][0-9]$suffix
			previous_start=/etc/rc$previous.d/S[0-9][0-9]$suffix
			previous_stop=/etc/rc$previous.d/K[0-9][0-9]$suffix

			if [ -f $previous_stop ] && [ $i -ef $previous_stop ]
			then
				identical=1
				if [ -f $start ] || [ -f $previous_start ]
				then
					if [ ! -f $start ] \
					 || [ ! -f $previous_start ] \
					 || [ ! $start -ef $previous_start ]
					then
						identical=0
					else
						avoid=$avoid" "$start
					fi
				fi
			fi

			# Kill it.
			[ $identical = 0 ] && $debug $i stop
		done
	fi
	# Now run the START scripts for this runlevel.
	for i in /etc/rc$runlevel.d/S*
	do
		identical=0
		for j in $avoid
		do
			if [ $i = $j ]
			then
				identical=1
				break
			fi
		done
		if [ $identical = 0 ]
		then
			suffix=${i#/etc/rc$runlevel.d/S[0-9][0-9]}
			previous_start=/etc/rc$previous.d/S[0-9][0-9]$suffix
			stop=/etc/rc$runlevel.d/K[0-9][0-9]$suffix
			if [ -f $previous_start ] \
			 && [ $i -ef $previous_start ] \
			 && [ ! -f $stop ]
			then
				identical=1
			fi

		fi

		[ $identical = 0 ] && [ -f $i ] && $debug $i start
	done
  fi
# eof /etc/init.d/rc
