#! /bin/sh
#
# mono-xsp Start the XSP WebServer, that works just for ASP.NET scripts.
#
#		Written by Pablo Fischer <pablo@pablo.com.mx>.
#		Modified for Debian GNU/Linux
#
# Version:	@(#)mono-xsp pablo@pablo.com.mx
#

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/bin/xsp
NAME=mono-xsp
DESC="XSP WebServer"
DEFAULT=/etc/default/$NAME
CFGDIR=/etc/xsp
VIRTUALFILE=$CFGDIR/debian.webapp
MONO_SHARED_DIR=/var/run/$NAME

test -x $DAEMON || exit 0
test -f $DEFAULT && . $DEFAULT	

should_start() {
    if [ ! -e $VIRTUALFILE -o `cat $VIRTUALFILE | wc -l` = "2" ]; then
	echo "You have an incomplete $VIRTUALFILE"
	echo "To fix it, you need to install at least one package for xsp (like asp.net-examples)"	
	return 1
    fi 
    
    if [ -f /var/run/$NAME.pid ]; then
	# Are we really running xsp?
	xsp_pid=`cat /var/run/$NAME.pid`
	xsp_ps=`ps -p $xsp_pid | wc -l`
	if [ "$xsp_ps" != "1" ]; then
	    echo "Sorry, there is already a xsp running, stop it first"
	    return 1		
	fi
    fi
    
    if [ $start_boot != true ]; then
       echo "Set start_boot=true in /etc/default/mono-xsp to enable mono-xsp."
       return 1
    fi
    
    return 0
	
}

should_stop() {
    if [ -f /var/run/$NAME.pid ]; then
	# Are we really running xsp?
	xsp_pid=`cat /var/run/$NAME.pid`
	xsp_ps=`ps -p $xsp_pid | wc -l`
	# Are there any process running by that pid?
	if [ "$xsp_ps" = "2" ]; then
	    return 0
	else
	    return 1
	fi
    else
	return 0
    fi
}

case "$1" in
    start)
	if should_start ; then
	    echo -n "Starting $DESC: $NAME"
	    export MONO_SHARED_DIR
	    start-stop-daemon --start --background --make-pidfile \
		--quiet --pidfile /var/run/$NAME.pid \
		--user $user --group $group --chuid $user \
		--exec $DAEMON -- \
		--port $port --appconfigdir $CFGDIR --nonstop
	    echo "."
	fi
	;;
    stop)
	if should_stop ; then
	    echo -n "Stopping $DESC: $NAME "
	    start-stop-daemon --stop --quiet --pidfile /var/run/$NAME.pid
	    echo "."
	fi
	;;
    restart|force-reload)
	#
	#	If the "reload" option is implemented, move the "force-reload"
	#	option to the "reload" entry above. If not, "force-reload" is
	#	just the same as "restart".
	#
	
	if should_stop ; then
	    echo "Restarting $DESC: $NAME"	
	    start-stop-daemon --stop --quiet --pidfile /var/run/$NAME.pid
	    sleep 1
	fi
	
	if should_start ; then
	    . $DEFAULT	
	    echo "Starting $DESC: $NAME"
	    export MONO_SHARED_DIR
	    start-stop-daemon --start --background --make-pidfile \
		--quiet --pidfile /var/run/$NAME.pid \
		--user $user --group $group --chuid $user \
		--exec $DAEMON -- \
		--port $port --appconfigdir $CFGDIR --nonstop
	    echo "."
	fi
	;;
    *)
	N=/etc/init.d/$NAME
	echo "Usage: $N {start|stop|restart|force-reload}" >&2
	exit 1
	;;
esac

exit 0
