#!/bin/bash
#
# Startup script to configure system services on the appliance
#
# chkconfig: 345 01 99
# description: Script to configure system services
#
# processname:
#
# Copyright (C) 2004 Networks Associates Technology Inc.  All rights reserved.
#
# Handle Log Files
#
if [ -f $NETAWSS/.profile.vars ]; then
 . $NETAWSS/.profile.vars
else
 . /var/NAIENV/.profile.vars
fi
PATH=$wsPATH:$PATH
shopt -s extglob
shopt -s nullglob
networkconf=$XMLCONFDIR/network.xml
protodir=$NETAWSS/proto/xmlconfdir
RET=0

# we don't want stdin
exec </dev/null

# load in the system info functions
. sysinfo-functions

. message_functions.bash	# message localisation

configure()
{

    if [[ $1 == @(restart|reload) ]]; then
	export WS_RESTART_LIST=/tmp/${0##*/}.restart_list.$$
	: >$WS_RESTART_LIST
    fi
    for f in ${WSMGMT}/systemservices.d/*
    do
	if [ -x ${f} ]
	then
	    ReportProgress _TR_ "ws-sys-conf" $"service configuration %s %s" \
		"${f##*/}" "$1"
	    out=`${f} ${1} 2>&1`
	    if [ $? -ne 0 ]
	    then
		logger -t ws-appliance-sys-services \
		    error configuring service ${f##*/}: $out
		RET=1
	    fi
	    ${out:+printf '%s\n' "$f:" "$out"}
	fi
    done
    if [[ $1 == @(restart|reload) && -s $WS_RESTART_LIST ]]; then
	local -a list=( $(sort -u $WS_RESTART_LIST) )
	local -i nlist=${#list[@]}
	local f i
	# for the start scripts of the current runlevel...
	for f in /etc/rc$(runlevel | awk '{print $2}').d/S*; do
	    # ... if it's one of the ones to rerun
	    for (( i=0 ; i<nlist; i++ )); do
		[[ $f -ef /etc/init.d/${list[i]} ]] || continue
		local cmd=$1
		[[ $cmd == reload ]] && cmd=restart
		if [[ ${list[i]} == httpd && -f $WS_RESTART_LATER ]]; then
		    # deferred restart for httpd
		    echo $f >>$WS_RESTART_LATER
		else
		    ReportProgress _TR_ "ws-sys-run" $"service %s %s" \
			"${f##*/}" "$cmd"
		    (
			[[ -w /proc/self/fd/3 ]] && exec >&3 2>&3
			exec $f $cmd	# run it
		    )
		fi
		list[i]=${list[--nlist]}	# drop from rerun list
		break
	    done
	    (( nlist > 0 )) || break
	done
    fi
    [[ -f $WS_RESTART_LIST ]] && rm -f "$WS_RESTART_LIST"
}

# See how we were called.
case "$1" in
    (start)
        configure start
	;;
    (stop)
        configure stop
	;;
    (restart)
	configure stop
	configure start
	;;
    (reload)
	configure reload
	;;
    (*)
	echo "Usage: $0 {start|stop|restart|reload}"
	exit 1
	;;
esac

exit $RET
