#!/bin/bash
### BEGIN INIT INFO
# Provides:          inspircd
# Required-Start:    $network $syslog $time
# Required-Stop:     $syslog
# Should-Start:      $local_fs
# Should-Stop:       $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start inspircd
# Description:       Starts the inspircd irc server                    
### END INIT INFO
# GPL Licensed

IRCD="/usr/sbin/inspircd"
IRCDPID="/var/run/inspircd.pid"
IRCDLOG="/var/log/inspircd.log"
IRCDARGS="--logfile $IRCDLOG"
USER="irc"

if [ -f "/etc/default/inspircd" ]; then
	. /etc/default/inspircd
fi

if [ ! -x "$IRCD" ]; then exit 0; fi

if [ -f "$IRCDPID" ]; then
        IRCDPIDN=`cat "$IRCDPID" 2> /dev/null`
fi

function start_ircd()
{
        touch "$IRCDPID"
        chown "$USER" "$IRCDPID"
        touch "$IRCDLOG"
        chown "$USER" "$IRCDLOG"
        export LD_LIBRARY_PATH=/usr/lib/inspircd
	start-stop-daemon --start --quiet --oknodo --chuid "$USER" --pidfile "$IRCDPID" --exec "$IRCD" -- $IRCDARGS start > /dev/null
}

function stop_ircd()
{
        start-stop-daemon --stop --quiet --pidfile "$IRCDPID" > /dev/null 2> /dev/null
        rm -f "$IRCDPID"
        return 0
}

function reload_ircd()
{
        if [ ! -z "$IRCDPIDN" ] && kill -0 $IRCDPIDN 2> /dev/null; then 
                kill -HUP $IRCDPIDN >/dev/null 2>&1 || return 1
                return 0
        else
                echo "Error: IRCD is not running."
                return 1
        fi
}

case "$1" in
  start)
	if [ "$INSPIRCD_ENABLED" != "1" ]; then
		echo -n "Please configure inspircd first and edit /etc/default/inspircd, otherwise inspircd won't start"
		exit 0
	fi
        echo -n "Starting Inspircd... "
        start_ircd && echo "done."
        sleep 1s
        ;;
  stop)
        echo -n "Stopping Inspircd... "
        stop_ircd && echo "done."
        ;;
  force-reload|reload)
        echo -n "Reloading Inspircd... "
        reload_ircd && echo "done."
        ;;
  restart)
        $0 stop
        sleep 2s
        $0 start
        ;;
  *)
        echo "Usage: $0 {start|stop|restart|reload|force-reload}"
        exit 1
esac

exit $RETVAL

