#!/bin/sh
#
# $FreeBSD: src/etc/rc.d/localdaemons,v 1.2 2003/05/05 15:38:41 mtm Exp $
#

# PROVIDE: localdaemons
# BEFORE:  securelevel
# KEYWORD: shutdown

. /etc/rc.subr

name="localdaemons"
start_cmd="locald_start"
stop_cmd="locald_stop"

# Returns true (0) if the passed argument is a valid name
# for a script, false (1) otherwise.
#
valid_scriptname()
{
	case ${1##*.} in
	orig)
		return 1
		;;
	sample)
		return 1
		;;
	dist)
		return 1
		;;
	esac
	return 0
}

locald_start()
{
	# For each dir in $local_startup, search for init scripts matching *
	#
	case ${local_startup} in
	[Nn][Oo] | '')
		;;
	*)
		echo -n 'Local package initialization:'
		slist=""
		if [ -z "${script_name_sep}" ]; then
			script_name_sep=" "
		fi
		for dir in ${local_startup}; do
			if [ -d "${dir}" ]; then
				for script in ${dir}/*; do
					if valid_scriptname ${script}; then
						slist="${slist}${script_name_sep}${script}"
					fi
				done
			fi
		done

		# If the firstboot sentinel doesn't exist, we want to
		# skip firstboot scripts.
		#
		if ! [ -e /firstboot ]; then
			skip_firstboot="-s firstboot"
		fi

		script_save_sep="$IFS"
		IFS="${script_name_sep}"
		sortedslist=`rcorder -s nostart ${skip_firstboot} /etc/rc.d/* ${slist} 2>/dev/null | grep -v "^/etc/rc.d/" | tr '\n' "$IFS"`;
		for script in ${sortedslist}; do
			if [ -x "${script}" ]; then
				(set -T
				trap 'exit 1' 2
				${script} start)
			elif [ -f "${script}" -o -L "${script}" ]; then
				echo -n " (skipping ${script##*/}, not executable)"
			fi
		done
		IFS="${script_save_sep}"
		echo '.'
		;;
	esac
}

locald_stop()
{
	echo -n 'Shutting down daemon processes:'

	# For each dir in $local_startup, search for init scripts matching *
	case ${local_startup} in
	[Nn][Oo] | '')
		;;
	*)
		slist=""
		if [ -z "${script_name_sep}" ]; then
			script_name_sep=" "
		fi
		for dir in ${local_startup}; do
			if [ -d "${dir}" ]; then
				for script in ${dir}/*; do
					if valid_scriptname ${script}; then
						slist="${slist}${script_name_sep}${script}"
					fi
				done
			fi
		done

		# If the firstboot sentinel doesn't exist, we want to
		# skip firstboot scripts.
		#
		if ! [ -e /firstboot ]; then
			skip_firstboot="-s firstboot"
		fi

		script_save_sep="$IFS"
		IFS="${script_name_sep}"
		sortedslist=`rcorder -s nostart ${skip_firstboot} /etc/rc.d/* ${slist} 2>/dev/null | grep -v "^/etc/rc.d/" | tr '\n' "$IFS"`;
		for script in `reverse_list ${sortedslist}`; do
			if [ -x "${script}" ]; then
				(set -T
				trap 'exit 1' 2
				${script} stop)
			fi
		done
		IFS="${script_save_sep}"
		echo '.'
		;;
	esac
}

load_rc_config $name
run_rc_command "$1"
