#!/bin/ash
# (C) jamesbond 2015
# MIT license
#
# simple services starter, startup service in alphabetical order
# 
# startup: only executable files will be started
# shutdown: all running service will be shutdown, in reverse
#           alphabetical order
#
# if you need something more sophisticated, use runit, pmtr, or daemon-proxy
#
# why this file is here and not merged with rc.sysinit/rc.shutdown?
# - needed by both 
# - must run async in rc.sysinit, to speed-up boot process
# - service dependency: later service won't start until earlier service is up
#
# $1 - start/stop

SERVICE_DIR=/etc/init.d
RESERVED=":S01logging:S40network:README.md:"
[ -e /etc/servicemanager ] && . /etc/servicemanager	# override default settings

# $1-service file
is_reserved() {
	local p=${1##*/}
	case "$RESERVED" in 
		*:$p:*) return 0
	esac
	return 1
}

start_all() {
	for service in $(ls $SERVICE_DIR/*); do
		! is_reserved $service &&
		[ -x $service ] && $service start
	done	
}

stop_all() {
	for service in $(ls -r $SERVICE_DIR/*); do
		! is_reserved $service &&
		if [ -x $service ] || sh $service status | grep -q "running"; then
			sh $service stop
		fi
	done		
}

### main ###
case $1 in
	start) start_all ;;
	stop)  stop_all ;;
esac
[ "$RC_SERVICES_PID" ] && rm $RC_SERVICES_PID # mark job done
