# -*- sh -*-
# vim:ft=sh:ts=8:sw=4:noet

AddConfigHandler ServicesOptions
AddConfigHelp "StopServices <service name> [...]" "The services listed are stopped prior to suspending. The service name must correspond to the name of an init.d script that is active in the current runlevel."
AddConfigHelp "StartServices <service name> [...]" "The services listed are started after resuming. The service name must correspond to the name of an init.d script that is active in the current runlevel."
AddConfigHelp "RestartServices <service name> [...]" "The services listed are stopped before suspending and started after resuming. The service name must correspond to the name of an init.d script that is active in the current runlevel."

# ExecuteServices <action> <services ...>
ExecuteServices() {
    local action
    local services
    local service
    action=$1
    shift
    services=$@
    ret=0
    for service in $services ; do
	[ -x "$INITDIR/$service" ] || continue
	CMD="$INITDIR/$service $action"
	vecho 2 "Executing $CMD"
	$CMD || ret=1
	RESTARTED_SERVICES="$service $RESTARTED_SERVICES"
    done
    return $ret
}

ServicesStop() {
    [ -z "$SERVICES_HOOKED" ] && return 0
    ExecuteServices stop $SERVICES_STOP
    RESTARTED_SERVICES=
    ExecuteServices stop $SERVICES_RESTART
    return 0 # Don't abort just because a service failed to stop, right?
}

ServicesStart() {
    [ -z "$SERVICES_HOOKED" ] && return 0
    ExecuteServices start $RESTARTED_SERVICES
    ExecuteServices start $SERVICES_START
    # preserve exit code
}

ServicesOptions() {
    case $1 in
	stopservices)
	    shift
	    SERVICES_STOP="$@"
	    ;;
	startservices)
	    shift
	    SERVICES_START="$@"
	    ;;
	restartservices)
	    shift
	    SERVICES_RESTART="$@"
	    ;;
	*)
	    return 1
    esac
    if [ -z "$SERVICES_HOOKED" ] ; then
	AddSuspendHook 30 ServicesStop
	AddResumeHook 30 ServicesStart
	SERVICES_HOOKED=1
	ServicesDetectDistro
    fi
    return 0
}

ServicesDetectDistro() {
    # Use either a given $DISTRIBUTION or autodetect one.
    case "$DISTRIBUTION" in
	gentoo)
	    INITDIR=/etc/init.d
	    ;;
	suse|mandrake)
	    INITDIR=/etc/init.d
	    ;;
	debian|slackware|redhat|fedora)
	    INITDIR=/etc/init.d
	    ;;
    	*)
	    # Auto-detect
	    if [ -d "/etc/init.d/" ] ; then
	    	INITDIR=/etc/init.d
	    elif [ -d "/etc/rc.d/init.d" ] ; then
	    	INITDIR=/etc/rc.d/init.d
	    else
		vecho 0 "Can not determine init.d directory. Services will not be suspended!"
		SERVICES_HOOKED=""
	    fi
    esac
    vecho 3 "Using '$INITDIR' as init.d directory."
    return 0
}

# $Id: services 623 2005-01-04 16:58:41Z dagobah $
