#! /bin/sh -e

prefix="/usr"
exec_prefix=${prefix}
sysconfdir="/etc/courier"
sbindir="${exec_prefix}/sbin"
bindir="${exec_prefix}/bin"
libexecdir="${prefix}/lib/courier"
TCPD=${sbindir}/couriertcpd
DAEMONPROG=${sbindir}/pop3d
DAEMON=pop3d-ssl
PROGRAM="Courier POP3-SSL server"

test -f $DAEMONPROG || exit 0

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

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

# read/set defaults
if [ -f /etc/default/courier ]; then
	. /etc/default/courier
fi
if [ -z "$MAILDIR" ]; then
	MAILDIR=Maildir
fi

. ${sysconfdir}/pop3d
. ${sysconfdir}/pop3d-ssl

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

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

if [ "$START" = "no" ]; then
	exit 0
fi

case "$1" in
start)
    echo -n "Starting $PROGRAM:"

    /usr/bin/env - PATH="$PATH" SHELL="$SHELL" \
		/bin/sh -c " . ${sysconfdir}/pop3d ; \
		. ${sysconfdir}/pop3d-ssl ; \
		POP3_TLS=1 ; export POP3_TLS ; \
		`sed -n '/^#/d;/=/p' <${sysconfdir}/pop3d | \
			sed 's/=.*//;s/^/export /;s/$/;/'`
		`sed -n '/^#/d;/=/p' <${sysconfdir}/pop3d-ssl | \
			sed 's/=.*//;s/^/export /;s/$/;/'`
	  PROXY_HOSTNAME=$PROXY_HOSTNAME; \
      /usr/sbin/courierlogger -pid=$SSLPIDFILE -start $SSLLOGGEROPTS \
	  $TCPD -address=$SSLADDRESS \
      -maxprocs=$MAXDAEMONS -maxperip=$MAXPERIP \
      $TCPDOPTS \
	  $SSLPORT $COURIERTLS -server -tcpd \
      ${libexecdir}/courier/courierpop3login \
      ${libexecdir}/courier/courierpop3d $MAILDIR"
    echo " $DAEMON."
	;;
stop)
  echo -n "Stopping $PROGRAM:"
  /usr/sbin/courierlogger -pid=$SSLPIDFILE -stop
  echo " $DAEMON."
	;;
restart | reload | force-reload)
  $0 stop
  $0 start
	;;
*)
  echo "Usage: $0 {start|stop|restart|reload|force-reload}" >&2
  exit 1
  ;;
esac
exit 0
