#!/bin/bash
# Begin $rc_base/init.d/rc - Main Run Level Control Script

# Based on rc script from LFS-3.1 and earlier.
# Rewritten by Gerard Beekmans  - gerard@linuxfromscratch.org

source /etc/sysconfig/rc
source $rc_functions

trap "" INT QUIT TSTP

[ "$1" != "" ] && runlevel=$1

if [ "$runlevel" = "" ]
then
	echo "Usage: $0 <runlevel>" >&2
	exit 1
fi

previous=$PREVLEVEL
[ "$previous" = "" ] && previous=N

if [ ! -d $rc_base/rc$runlevel.d ]
then
	echo "$rc_base/rc$runlevel.d does not exist"
	exit 1
fi

if [ "$previous" != "N" ]
then
	for i in $(ls -v $rc_base/rc$runlevel.d/K* 2> /dev/null)
	do

		check_script_status

		suffix=${i#$rc_base/rc$runlevel.d/K[0-9][0-9]}
		prev_start=$rc_base/rc$previous.d/S[0-9][0-9]$suffix
		sysinit_start=$rc_base/rcsysinit.d/S[0-9][0-9]$suffix

		if [ "$runlevel" != "0" ] && [ "$runlevel" != "6" ]
		then
			if [ ! -f $prev_start ] && [ ! -f $sysinit_start ]
			then
				$WARNING
				echo "$i can't be executed because it was"
				echo "not started in the previous runlevel ($previous)"
				$NORMAL
				continue
			fi
		fi

		$i stop
		error_value=$?

		if [ "$error_value" != "0" ]
		then
			print_error_msg
		fi
	done
fi

for i in $( ls -v $rc_base/rc$runlevel.d/S* 2> /dev/null)
do
	if [ "$previous" != "N" ]
	then
		suffix=${i#$rc_base/rc$runlevel.d/S[0-9][0-9]}
		stop=$rc_base/rc$runlevel.d/K[0-9][0-9]$suffix
		prev_start=$rc_base/rc$previous.d/S[0-9][0-9]$suffix

		[ -f $prev_start ] && [ ! -f $stop ] && continue
	fi

	check_script_status

	$i start
	error_value=$?

	if [ "$error_value" != "0" ]
	then
		print_error_msg
	fi
done

# End $rc_base/init.d/rc

