#!/bin/zsh
#
# Start and Stop WebObjects Services
#

. /etc/rc.common


WOSERVICE="/System/Library/WebObjects/JavaApplications/wotaskd.woa/Contents/Resources/javawoservice.sh"

WOTASKD="/System/Library/WebObjects/JavaApplications/wotaskd.woa/wotaskd"
WOJAVAMONITOR="/System/Library/WebObjects/JavaApplications/JavaMonitor.woa/JavaMonitor"

GREP=/usr/bin/grep
AWK=/usr/bin/awk
PS=/bin/ps

PRINTSTARTSTOPMESSAGES="YES"

##
# Start WebObjects services
#	(Services to be stopped by this script must use "javawoservice.sh".)
##
StartService ()
{
    if [ -x "$WOSERVICE" ]; then
	
    	if [ "$PRINTSTARTSTOPMESSAGES" = "YES" ]; then
	    ConsoleMessage "Starting WebObjects services"
	fi
	
    	if [ -e /var/log/webobjects.log ]; then
	    mv /var/log/webobjects.log /var/log/webobjects.log.1
    	fi
	
	####
	# This set of invocations will launch wotaskd and
	# (optionally) Monitor as root
	
	"$WOSERVICE" -appPath "$WOTASKD"  >/var/log/webobjects.log 2>&1 & 
	
	# Uncomment the next line to start Monitor as root at boot time
	#"$WOSERVICE" -appPath "$WOJAVAMONITOR" -WOPort 56789 -WOAutoOpenInBrowser NO >>/var/log/webobjects.log 2>&1 & 
	####	
	
	####
	# This set of invocations will launch wotaskd and
	# (optionally) Monitor as 'nonrootuser'
	# Change 'nonrootuser' to whatever account you want wotaskd to run as.
	#
	#/usr/bin/su nonrootuser -c "$WOSERVICE" -appPath "$WOTASKD" >/var/log/webobjects.log 2>&1 & 
	#
	#/usr/bin/su nonrootuser -c "$WOSERVICE" -appPath "$WOJAVAMONITOR" -WOPort 56789 -WOAutoOpenInBrowser NO >> /var/log/webobjects.log 2>&1 & 
	#
	####
	
    fi
}

##
# Stop WebObjects Services
#  	(Stop all services run by "javawoservice.sh".)
##
StopService ()
{
    if [ "$PRINTSTARTSTOPMESSAGES" = "YES" ]; then
	ConsoleMessage "Stopping WebObjects services"
    fi
    
    local PSCOMMAND="$PS -jaxwwwww"
    WOSERVICEPIDS=`eval $PSCOMMAND | $GREP "$WOSERVICE" | $GREP -v grep | $AWK '{print $2}'`
    
    for parent in ${=WOSERVICEPIDS}
    {
	WOSERVICECHILDPIDS=`eval $PSCOMMAND | $AWK 'NF>3 {if ( $3 =='"$parent"' ) print $2}'` 
	
	StopPID $parent
	
	for child in ${=WOSERVICECHILDPIDS}
	{
	    StopPID $child  
	}
	
    }
    
}

##
# Restart WebObjects Services
##
RestartService ()
{
    ConsoleMessage "Restarting WebObjects services"
    
    PRINTSTARTSTOPMESSAGES="NO"
    
    StopService
    StartService
}

##
# Stop Process by PID
##
StopPID ()
{
    `kill "$1"`
}

RunService "$1"
