#!/bin/sh

# Script to start a Squeak Image which runs Kom HTTP Server in headless mode.
# Because main purpos is to run as service from /etc/init.d/squeak_http,
# this can be started by root, but runs uder user mzimmermann

START_CMD="/usr/local/bin/squeak -vm-display-X11 -headless Squeak3.8-seaside-my.image"
echo before running $START_CMD

SQUEAK_HTTP_PID=`ps -eo pid,command | grep "$START_CMD" | grep -v grep | awk '{ print $1 }'`
echo SQUEAK_HTTP_PID=$SQUEAK_HTTP_PID

# Now when we used START_CMD to query for PID, we add nice to it to run nicely
START_CMD="nice $START_CMD"

# And check and run what user asked for.

case "$1" in
    start)
        # echo -n "Starting SQUEAK_HTTP "
	if [ "$SQUEAK_HTTP_PID" != "" ]; then
	   echo "SQUEAK_HTTP Already running, exiting"
	   # exit 1
	else

	   # su to mzimmermann to ensure image owned by me
	   # su - mzimmermann

	   # Change directory and run Squeak headless
	   cd /home/mzimmermann/dev/smalltalk/squeak/3.8/http
	   $START_CMD &
	fi
        ;;
    stop)
        # echo -n "Shutting down SQUEAK_HTTP "
	if [ "$SQUEAK_HTTP_PID" = "" ]; then
	   echo "SQUEAK_HTTP Not running!"
	else
	   #kill -SIGINT $SQUEAK_HTTP_PID
	   kill -HUP $SQUEAK_HTTP_PID
	fi
        ;;
    pid)
	echo "You asked for PID: here:"
	echo $SQUEAK_HTTP_PID	
	;;
    *)
        echo "Usage: $0 {start|stop}"
        exit 1
        ;;
esac

#####################################################################
# NOTE ONLY: 
# Following is needed to start/stop Kom HTTP Server:
#####################################################################

# " ############### vvvvv Kom HttpService Start vvvvv ########################"
# " ##### The code below will start Squeak-based HTTP server. It is ONLY necessary to start once, because at some point in the code below, the 'ApplicationService/HttpService initialize' is send and the initialize method makes service start on Smalltalk startup. To remove HttpServices from Smalltalk startup, run in this order:
# 	- HttpService class initialize
# 		- TcpService class initialize
# 	- ApplicationService class initialize
# 		- ApplicationService class shutDown
# "
# |ma|
# ma := ModuleAssembly core.
# ma serverRoot: FileDirectory default fullName.
# ma documentRoot: FileDirectory default fullName.
# ma directoryIndex: 'index.html index.htm'.
# ma serveFiles.
# service := (HttpService startOn: 9090 named: 'httpd') plug: ma rootModule.
# " ############### ^^^^^ KomHttpService Start ^^^^^ ########################"
# 
# " ############### vvvvv KomHttpService Stop vvvvv ########################"
# 	service stop.
# 	service initialize.
# 	HttpService initialize.
# 	     TcpService initialize.
# 		ApplicationService initialize.
# 		ApplicationService shutDown.
# " ############### ^^^^^ KomHttpService Stop ^^^^^ ########################"
# 
