#!/bin/sh

### BEGIN INIT INFO
# Provides:          gozerbot
# 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: Gozerbot IRC and Jabber bot
# Description:       Gozerbot is an IRC and Jabber bot written in Python.
### END INIT INFO

NAME=gozerbot
DESC="Gozerbot IRC robot"
DATADIR=/var/lib/gozerbot
PIDFILE=$DATADIR/gozerbot.pid
LOGFILE=/var/log/gozerbot.log

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

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

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

if [ -z "$RUNUSER" ] ; then
    RUNUSER=gozerbot
fi

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

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

start()
{
	status && exit 1 # already running
        if [ -e $DATADIR ]
        then
          cd $DATADIR
        else
          mkdir -p $DATADIR
          cd $DATADIR
        fi
        if [ -e gozerdata/mainconfig ]
        then
           su $RUNUSER -c "$NAME >> /var/log/gozerbot.log 2>&1 &"
        else
           su $RUNUSER -c gozerbot-init
           rm -rf /etc/gozerbot
           ln -s /var/lib/gozerbot/gozerdata /etc/gozerbot
           echo ""
           echo "A default config file /etc/gozerbot/mainconfig has been created."
           echo "irc and jabber bot example files are installed in /etc/gozerbot/fleet."
           echo "Please edit those files and then run this script again to start gozerbot."
        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/gozerbot {start|stop|reload|force-reload|restart|status}" >&2
	exit 1
	;;
esac

*t
