#! /bin/sh
#
# Copyright 1998 - 2015 Double Precision, Inc.
# See COPYING for distribution information.


prefix=/usr/local
exec_prefix=/usr/local
sbindir=${exec_prefix}/sbin
sysconfdir=/usr/local/etc/courier

if test ! -f /usr/local/etc/courier/imapd
then
	echo "/usr/local/etc/courier/imapd does not exist, forgot make install-configure?"
	exit 1
fi

if test ! -f /usr/local/etc/courier/imapd-ssl
then
	echo "/usr/local/etc/courier/imapd-ssl does not exist, forgot make install-configure?"
	exit 1
fi

. /usr/local/etc/courier/imapd-ssl
. /usr/local/etc/courier/imapd

case $1 in
start)
	if test "$TLS_CACHEFILE" != ""
	then
		rm -f "$TLS_CACHEFILE"
		touch "$TLS_CACHEFILE"
		/usr/sbin/chown courier "$TLS_CACHEFILE"
		chgrp courier  "$TLS_CACHEFILE"
		chmod 600  "$TLS_CACHEFILE"
	fi

	umask ${IMAP_UMASK:=022}
	if test ! -f "${IMAPACCESSFILE}.dat"
	then
		if test -e "${IMAPACCESSFILE}"
		then
			$sbindir/makeimapaccess
		else
			echo "IMAPACCESSFILE is missing." >&2
			exit 1
		fi
	fi
	if test ! -z "$IMAP_ULIMITD"
	then
		ulimit -v $IMAP_ULIMITD
	fi
	/usr/bin/env -i /bin/sh -c " set -a ; \
				prefix=/usr/local ; \
				exec_prefix=/usr/local ; \
				sbindir=${exec_prefix}/sbin ; \
				bindir=/usr/local/bin ; \
				. /usr/local/etc/courier/imapd ; \
				. /usr/local/etc/courier/imapd-ssl ; \
		IMAP_STARTTLS=$IMAPDSTARTTLS ; \
		PROXY_HOSTNAME=$PROXY_HOSTNAME ; \
		/bin/mkdir -p `dirname $PIDFILE` ; \
		/usr/local/sbin/courierlogger -pid=$PIDFILE -start $LOGGEROPTS \
		${exec_prefix}/sbin/couriertcpd -address=$ADDRESS \
			-maxprocs=$MAXDAEMONS -maxperip=$MAXPERIP \
			-access=$IMAPACCESSFILE.dat \
			$TCPDOPTS \
			$PORT /usr/local/libexec/courier/imaplogin \
				/usr/local/bin/imapd ${MAILDIRPATH}"
	;;
stop)
	/usr/local/sbin/courierlogger -pid=$PIDFILE -stop
	;;
restart)
	/usr/local/sbin/courierlogger -pid=$PIDFILE -restart
	;;
esac
exit 0
