#!/bin/sh
#
# unrealircd      This shell script takes care of starting and stopping
#                 uircd (Unreal Internet Relay Chat server).
#
# chkconfig: - 90 20
# description: uircd is a Internet Relay Chat Server

# Source function library.
. /etc/init.d/functions
. cert-sh-functions

# Source networking configuration.
SourceIfNotEmpty /etc/sysconfig/network && [ "$NETWORKING" != no ] || exit

UIRCD_BIN=uircd
UIRCD_ROOT="/var/lib/unreal"
UIRCD_CONF="/etc/unrealircd/unrealircd.conf"
UIRCD_SSL_CONFDIR="/etc/unrealircd/ssl"

SourceIfNotEmpty /etc/sysconfig/unreal

LOCKFILE=/var/lock/subsys/uircd
RETVAL=0

cert()
{
	need_generate=0
	[ -s "$UIRCD_SSL_CONFDIR"/unreal.cert ] || need_generate=1
	[ -s "$UIRCD_SSL_CONFDIR"/unreal.csr ] || need_generate=1
	[ -s "$UIRCD_SSL_CONFDIR"/unreal.key ] || need_generate=1
	if [ $need_generate -eq 1 ]; then
			ssl_generate "unreal"
			mv -f "$SSL_CERTDIR"/unreal.cert "$UIRCD_SSL_CONFDIR"
			mv -f "$SSL_CERTDIR"/unreal.csr "$UIRCD_SSL_CONFDIR"
			mv -f "$SSL_KEYDIR"/unreal.key "$UIRCD_SSL_CONFDIR"
			chmod 640 "$UIRCD_SSL_CONFDIR"/*
			chown root:uircd "$UIRCD_SSL_CONFDIR"/*
	fi
}

adjust()
{
	action "Adjusting environment for UnrealIRCd server:" /etc/chroot.d/unreal.all
	RETVAL=$?
        return $RETVAL
}

rehash()
{
    if [ -e "$LOCKFILE" ]; then
	action "Rehashing UnrealIRCd:" kill -1 `cat $UIRCD_ROOT/ircd.pid`
    fi
}

start()
{
	cert
	adjust || return
	start_daemon --lockfile "$LOCKFILE" --user root -- $UIRCD_BIN "$OPTIONS"
	RETVAL=$?
	[ $RETVAL -eq 0 ] && touch "$LOCKFILE"
	return $RETVAL
}

mkpasswd()
{
	$UIRCD_BIN -P $2 $3
}

stop()
{
	stop_daemon --lockfile "$LOCKFILE" -- "$UIRCD_BIN"
	RETVAL=$?
	[ $RETVAL -eq 0 ] && rm -f "$LOCKFILE"
	return $RETVAL
}

# See how we were called.
case "$1" in
        start)
                start
                ;;
        stop)
                stop
                ;;
        reload)
                adjust
                rehash
                ;;
        rehash)
                rehash
                ;;
        restart)
                stop
		start
                ;;
        status)
                status uircd
                RETVAL=$?
                ;;
        adjust)
                adjust
                ;;
		mkpasswd)
			mkpasswd
				;;
		cert)
			cert
				;;
        condstop)
                if [ -e "$LOCKFILE" ]; then
                        stop
                fi
                ;;
        condrestart)
                if [ -e "$LOCKFILE" ]; then
                        stop
			start
                fi
                ;;
        *)
                echo "Usage: ${0##*/} {start|stop|restart|reload|rehash|status|adjust|mkpasswd|cert|condstop|condrestart}"
                RETVAL=1
esac

exit $RETVAL
