#!/bin/sh
### BEGIN INIT INFO
# Provides:          inspircd
# Required-Start:    $remote_fs $network $syslog $time
# Required-Stop:     $remote_fs $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

NAME="inspircd"
IRCD="/usr/sbin/inspircd"
IRCDPID="/var/run/inspircd/inspircd.pid"
IRCDLOG="/var/log/inspircd.log"
IRCDCONF="/etc/inspircd/inspircd.conf"
IRCDARGS="--logfile $IRCDLOG --config $IRCDCONF"
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

. /lib/lsb/init-functions

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

if [ -f "$IRCDPID" ]; then
    IRCDPIDN="$(cat "$IRCDPID")"
fi

start_ircd()
{
    if [ ! -f "$IRCDPID" ] ; then
        DIR="$(dirname "$IRCDPID")"
        mkdir -p "$DIR"
        chown "$USER" "$DIR"
        touch "$IRCDPID"
        chown "$USER" "$IRCDPID"
    fi
    if [ ! -f "$IRCDLOG" ] ; then
        touch "$IRCDLOG"
        chown "$USER:adm" "$IRCDLOG"
        chmod 0640 "$IRCDLOG"
    fi
    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 \
        --exec "$IRCD" \
        --pidfile "$IRCDPID" >/dev/null 2>&1
    rm -f "$IRCDPID"
    return 0
}

reload_ircd()
{
    if [ "$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)
    echo -n "Starting Inspircd... "
    start_ircd && echo "done."
    ;;
stop)
    echo -n "Stopping Inspircd... "
    stop_ircd && echo "done."
    ;;
status)
    status_of_proc "$IRCD" "$NAME" && exit 0 || exit $?
    ;;
force-reload|reload)
    echo -n "Reloading Inspircd... "
    reload_ircd && echo "done."
    ;;
restart)
    $0 stop
    sleep 2
    $0 start
    ;;
cron)
    start_ircd || echo "Inspircd not running, starting it"
    ;;
*)
    echo "Usage: $0 {start|stop|status|restart|reload|force-reload|cron}"
    exit 1
esac
