#!/sbin/sh
#
# rc		This file is responsible for starting/stopping
#		services when the runlevel changes. It is also
#		responsible for the very first setup of basic
#		things, such as setting the hostname.
#
# Version:	@(#) /sbin/rc 1.01 26-Oct-1993
#
# Author:	Miquel van Smoorenburg, <miquels@drinkel.nl.mugnet.org>
#

  # Don't allow a SIGINT to kill this shell-script,
  # just the executing child
  trap "echo" SIGINT
  export HOME=/

  # Note the first argument
  argv1="$1"

  # See how we were called.
  case "$argv1" in
    bcheckrc)
	# All output to /dev/console
	exec > /dev/tty0 2>&1

	# Set path and home
	export PATH=/sbin:/bin

	# Execute system init
	echo "Bcheckrc: Doing system initiation..."
	if [ -d /sbin/bcheckrc/ ]; then
	    for i in /sbin/bcheckrc/S*
	    do
		[ -f $i ] && $i bcheckrc
	    done
	fi
	;;
    [0-6])
	# Using first line
	exec 0<> /dev/tty1 1>&0 2>&0
	stty sane cr0 tab3 pass8 ek > /dev/null

	# Runlevel 0: halt mode
	# Runlevel 1: single mode
	# Runlevel 6: reboot mode

	# Set path and home
	export PATH=/sbin:/bin:/usr/sbin:/usr/bin

        # Now find out what the current and what
        # the previous runlevel are.
	set `runlevel`
	export runlevel=$2
	export previous=$1
	echo -n "Previous runlevel $previous, "
	echo    "Current runlevel $runlevel"

	# Get first argument.
	# Set new runlevel to this argument.
	[ "$1" != "" ] && runlevel="$argv1"
	currentS=/sbin/rc$runlevel.d/S
	previouK=/sbin/rc$previous.d/K
	previouS=/sbin/rc$previous.d/S

	# Is there an rc directory for this new runlevel?
	if [ -d /sbin/rc$runlevel.d/ ]; then
	   # First, run the KILL scripts.
	   if [ "$previous" != "N" ]; then
		#
		# First run the STOP scripts of the previous runlevel.
		#
		for i in ${previouK}*
		do
		   # Check if the script is there.
		   [ ! -f $i ] && continue

		   # See if there is a start script
		   # in current  runlevel.
		   start=${i##*/K*[0-9]}
		   [ -f ${currentS}*${start} ] && continue

		   # No current startup script
		   # so kill the previous.
		   [ -f $i ] && { $i stop ; sleep 1 }
		done
		#
		# Now  run the START scripts of the current  runlevel.
		#
		for i in ${currentS}*
		do
		   # Check if the script is there.
		   [ ! -f $i ] && continue

		   # See if there is a start script
		   # in previous runlevel.
		   start=${i##*/S*[0-9]}
		   [ -f ${previouS}*${start} ] && continue

		   # No current startup script
		   # so start the current.
		   [ -f $i ] && $i start
		done
	   else
		for i in ${currentS}*
		do
		   [ -f $i ] && $i start
		done
	   fi
	fi
	;;
    *)
	# Oops someone made a typo.
	echo "Usage: /sbin/rc {bcheckrc|[0-6]}"
	exit 1
  esac

exit 0
