#!/bin/sh
### 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"
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

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

start_ircd()
{
	[ -f "$IRCDPID" ] || ( touch "$IRCDPID" ; chown "$USER" "$IRCDPID" )
	[ -f "$IRCDLOG" ] || ( touch "$IRCDLOG" ; chown "$USER:adm" "$IRCDLOG" ; chmod 0640 "$IRCDLOG" )
        export LD_LIBRARY_PATH=/usr/lib/inspircd
	start-stop-daemon --start --quiet --oknodo --chuid "$USER" --pidfile "$IRCDPID" --exec "$IRCD" -- $IRCDARGS start > /dev/null
}

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

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."
        ;;
  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
        ;;
  cron)
        start_ircd || echo "Inspircd not running, starting it"
        ;;

  *)
        echo "Usage: $0 {start|stop|restart|reload|force-reload|cron}"
        exit 1
esac


