#! /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
# Description:       courier-pop is an POP3 Mail Delivery Agent.
### END INIT INFO

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

test -f $DAEMON || exit 0

. /lib/lsb/init-functions

if [ ! -d ${run_dir} ]; then
        mkdir -p ${run_dir}
        chown daemon:daemon ${run_dir}
fi

if [ ! -d ${calendar_dir} ]; then
        mkdir -p ${calendar_dir}
        chown daemon:daemon ${calendar_dir}
fi



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

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

# read/set defaults
if [ -f /etc/default/courier ]; then
	. /etc/default/courier
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
    log_begin_msg "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"
    log_end_msg 0
  fi
    ;;
stop)
  log_begin_msg "Stopping $PROGRAM..."
  $TCPD -pid=$PIDFILE -stop || log_end_msg 1
  log_end_msg 0
    ;;
restart | force-reload)
  $0 stop
  $0 start
    ;;
status)
  status_of_proc -p $PIDFILE $DAEMON "$PROGRAM" && exit 0 || exit $?
	;;
*)
  log_success_msg "Usage: $0 {start|stop|restart|reload|force-reload}" >&2
  exit 1
  ;;
esac

exit 0
