#!/bin/sh

### BEGIN INIT INFO
# Provides:          jsonbot
# Required-Start:    $local_fs $remote_fs $network $named
# Required-Stop:     $local_fs $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: JSONBOT IRC, XMPP and Web robot
# Description:       Framework for building bots for IRC, XMPP and the Web
### END INIT INFO

NAME=jsonbot
DESC="JSONBOT IRC, XMPP and Web robot"
DATADIR=/var/cache/jsb
PIDFILE=/var/run/jsonbot.pid

PID=`cat $PIDFILE` 2>/dev/null

# Include jsonbot defaults if available
if [ -f /etc/default/jsonbot ] ; then
    . /etc/default/jsonbot
fi

if [ "$RUN" != "yes" ] ; then
    echo "$NAME disabled; edit /etc/default/jsonbot"
    exit 0
fi

if [ -n "$RUNUSER" ] ; then
    RUNUSER=jsb
fi

status()
{
	test -n "$PID" && ps auxw | grep -v grep | grep jsb-fleet | grep -q -s " $PID " && return 0
        return 1
}

stop()
{
	if status
	then
		kill -KILL $PID
	fi
}

start()
{
	status && exit 1 # already running
        if [ -d $DATADIR ]; then 
          cd $DATADIR
        else
          mkdir -p $DATADIR
          cd $DATADIR
        fi
        if [ -f config/mainconfig ]; then
           su $RUNUSER -c "jsb-fleet -d $DATADIR $ARGSTRING 2>/dev/null &"
           echo ""
        else
	   export PYTHONPATH="$PYTHONPATH:/usr/share/pyshared"
           su $RUNUSER -c "jsb-init -d /var/cache/jsb"
	   if ! [ -f /etc/jsonbot/mainconfig ]; then
	     rm -rf /etc/jsonbot
	     mv /var/cache/jsb/config /etc/jsonbot
	     chmod go-rx /etc/jsonbot
	   fi
	   rm -rf /var/cache/jsb/config
	   ln -s /etc/jsonbot /var/cache/jsb/config 
           echo ""
           echo "jsonbot has not been configured.  Please edit /etc/jsonbot/mainconfig, and if"
           echo "applicable the irc and jabber bot files in /etc/jsonbot/fleet, then run this"
           echo "script again to start jsonbot."
        fi
}

case "$1" in
start)
	echo -n "Starting $DESC: $NAME"
	start
	case "$?" in
		0) echo "." ; exit 0 ;;
		1) echo " (already running)." ; exit 0 ;;
		*) echo " (failed)." ; exit 1 ;;
	esac
	;;
stop)
	echo -n "Stopping $DESC: $NAME"
	stop
	case "$?" in
		0) echo "." ; exit 0 ;;
		1) echo " (not running)." ; exit 0 ;;
		*) echo " (failed)." ; exit 1 ;;
	esac
	;;
restart|force-reload|reload)
	echo -n "Restarting $DESC: $NAME"
	stop
	start
	;;
status)
	echo -n "Status of $DESC service: "
	status
	case "$?" in
		0) echo "running." ; exit 0 ;;
		1) echo "not running." ; exit 3 ;;
	esac
	;;
*)
	echo "Usage: /etc/init.d/jsonbot {start|stop|reload|force-reload|restart|status}" >&2
	exit 1
	;;
esac

*t
