#!/bin/sh

# Init file for Courier-IMAP POP3 daemon
#
# chkconfig: 35 72 28
# description: Courier-IMAP POP3 daemon
#   This daemon is running via Courier own tcpd daemon - couriertcpd
#
# config: /etc/courier-imap/pop3d
# config: /etc/courier-imap/pop3d-ssl
# config: /etc/courier-imap/pop3d.cnf

# Source function library.
. /etc/init.d/functions
. /etc/sysconfig/network

. /etc/courier-imap/pop3d-ssl
. /etc/courier-imap/pop3d

. /etc/sysconfig/courier-imap

SBIN_DIR=/usr/sbin
LIBEXEC_DIR=/usr/lib/courier-imap

POP3D_BIN=$SBIN_DIR/pop3d
POP3LOGIN_BIN=$SBIN_DIR/pop3login
TCPD_BIN=$SBIN_DIR/couriertcpd
LOGGER_BIN=$SBIN_DIR/courierlogger
LCKFILE=`echo $PIDFILE".lock"|sed -e 's|/var/run|/var/lock/courier-imap|'`

[ "$POP3DSTART" != "NO" ] || exit;
[ -x $POP3D_BIN -a -x $POP3LOGIN_BIN ] || exit;
[ -x $TCPD_BIN -a -x $LOGGER_BIN ] || exit;

RETVAL=0
LOCKFILE=/var/lock/subsys/courier-pop3d

start()
{
	LIBAUTHMODULES=""
	for f in `echo $AUTHMODULES`
	do
		LIBAUTHMODULES="$LIBAUTHMODULES $LIBEXEC_DIR/authlib/$f"
	done

	echo -n "Starting Courier POP3 daemon: "
	
	/usr/bin/env - /bin/sh -c " set -a ; \
		. /etc/courier-imap/pop3d ; \
		. /etc/courier-imap/pop3d-ssl ; \
		TLS_PROTOCOL=$TLS_STARTTLS_PROTOCOL ; export TLS_PROTOCOL ; \
		$TCPD_BIN \
		    -address=$ADDRESS \
		    -stderrlogger=$LOGGER_BIN \
		    -stderrloggername=pop3d \
		    -maxprocs=$MAXDAEMONS \
		    -maxperip=$MAXPERIP \
		    -pid=$PIDFILE \
		    $TCPDOPTS $PORT \
		    $POP3LOGIN_BIN $LIBAUTHMODULES \
		    $POP3D_BIN Maildir"

	RETVAL=$?
	if [ $RETVAL -eq 0 ]; then
	    success "pop3d startup"
	    touch "$LOCKFILE"
	fi
	echo
	return $RETVAL
}	

stop()
{
	echo -n "Shutting down Courier POP3 daemon: "

	$TCPD_BIN -pid=$PIDFILE -stop

	RETVAL=$?
	if [ $RETVAL -eq 0 ]; then
	    success "pop3d shutdown"
	    rm -f "$LOCKFILE"
	    rm -f "$PIDFILE"
	    rm -f "$LCKFILE"
	fi
	echo
	return $RETVAL
}

reload()
{
	echo -n "Reloading Courier POP3 daemon: "

	$TCPD_BIN -pid=$PIDFILE -restart

	RETVAL=$?
	if [ $RETVAL -eq 0 ]; then
	    success "pop3d reloading"
	fi
	echo
	return $RETVAL
}

restart()
{
	stop
	start
}
# See how we were called.
case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	reload)
		reload
		;;
	restart)
		restart
		;;
	condstop)
		# Stop the servce if it is already running, for example:
		if [ -e "$LOCKFILE" ]; then
			stop
		fi
		;;
	condrestart)
		# Restart the servce if it is already running, for example:
		if [ -e "$LOCKFILE" ]; then
			restart
		fi
		;;
	status)
		# report the status of the daemons in free-form format,
		# perhaps with the status function, for example:
		status courier-pop3d
		RETVAL=$?
		;;
	*)
		echo "Usage: ${0##*/} {start|stop|reload|restart|condstop|condrestart|status}"
		RETVAL=1
esac

exit $RETVAL
