#! /bin/sh -e
### BEGIN INIT INFO
# Short-Description: Courier POP3 server
# Provides:          courier-pop
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
### END INIT INFO

prefix="/usr"
exec_prefix=${prefix}
sysconfdir="/etc/courier"
sbindir="${exec_prefix}/sbin"
libexecdir="${prefix}/lib/courier"
TCPD="${sbindir}/couriertcpd"
DAEMON=${sbindir}/pop3d
PROGRAM="Courier POP3 server"
PROG="pop3d"
SSLCONFIG=

test -f $DAEMON || exit 0

# load LSB functions
. /lib/lsb/init-functions

if ! [ -x $TCPD ]; then
  echo "ERR: $TCPD missing"
  exit 1
fi

if ! [ -f ${sysconfdir}/pop3d ]; then
  echo "ERR: config file missing"
  exit 1
fi

# ensure that maildirpath is set
if [ -z "$MAILDIRPATH" ]; then
	MAILDIRPATH=Maildir
fi

if [ -f "${sysconfdir}/pop3d-ssl" ]; then
	. "${sysconfdir}/pop3d-ssl"
	SSLCONFIG=1
fi
. ${sysconfdir}/pop3d

START=no
case "$POP3DSTART" in
  [yY]*)START=yes;;
esac

case "$1" in
start)
  if [ "$START" = "yes" ]; then
    echo -n "Starting $PROGRAM:"

    /usr/bin/env - /bin/sh -c " set -a; \
		. ${sysconfdir}/pop3d; \
		if [ "$SSLCONFIG" ]; then . ${sysconfdir}/pop3d-ssl; fi; \
		POP3_STARTTLS=$POP3_STARTTLS; export POP3_STARTTLS; \
		TLS_PROTOCOL=$TLS_STARTTLS_PROTOCOL; \
		/usr/sbin/courierlogger -pid=$PIDFILE -start $LOGGEROPTS \
	    $TCPD \
		-maxprocs=$MAXDAEMONS -maxperip=$MAXPERIP \
		$TCPDOPTS -address=$ADDRESS $PORT \
		${libexecdir}/courier/courierpop3login $AUTHMODULELIST \
		${libexecdir}/courier/courierpop3d $MAILDIRPATH"
    echo " $PROG."
  fi
    ;;
stop)
  echo -n "Stopping $PROGRAM:"
  $TCPD -pid=$PIDFILE -stop
  echo " $PROG."
    ;;
restart | force-reload)
  $0 stop
  $0 start
    ;;
status)
  status_of_proc -p $PIDFILE $DAEMON "$PROGRAM" && exit 0 || exit $?
	;;
*)
  echo "Usage: $0 {start|stop|restart|force-reload}" >&2
  exit 1
  ;;
esac

exit 0
