#! @SHELL@
#
# Copyright 1998 - 2015 S. Varshavchik.
# See COPYING for distribution information.


prefix=@prefix@
exec_prefix=@exec_prefix@
sbindir=@sbindir@
bindir=@bindir@
sysconfdir=@sysconfdir@

if test ! -f @sysconfdir@/imapd
then
	echo "@sysconfdir@/imapd does not exist, forgot make install-configure?"
	exit 1
fi

if test ! -f @sysconfdir@/imapd-ssl
then
	echo "@sysconfdir@/imapd-ssl does not exist, forgot make install-configure?"
	exit 1
fi

. @sysconfdir@/imapd
. @sysconfdir@/imapd-ssl

case $1 in
start)
	if test "$TLS_CACHEFILE" != ""
	then
		rm -f "$TLS_CACHEFILE"
		touch "$TLS_CACHEFILE"
		chown @mailuser@ "$TLS_CACHEFILE"
		chgrp @mailgroup@  "$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@ $IMAP_ULIMITD
	fi
	@SETENV@ -i @SHELL@ -c " set -a ;
		prefix=@prefix@ ; \
		exec_prefix=@exec_prefix@ ; \
		sbindir=@sbindir@ ; \
		bindir=@bindir@ ; \
		. @sysconfdir@/imapd ; \
		. @sysconfdir@/imapd-ssl ; \
		PROXY_HOSTNAME=$PROXY_HOSTNAME ; \
		IMAP_TLS=1; \
		@MKDIR_P@ `dirname $SSLPIDFILE` ; \
		@courierlogger@ -pid=$SSLPIDFILE -start $SSLLOGGEROPTS \
		@sbindir@/couriertcpd -address=$SSLADDRESS \
			-maxprocs=$MAXDAEMONS -maxperip=$MAXPERIP \
			-access=$IMAPACCESSFILE.dat \
			$TCPDOPTS \
			$SSLPORT $COURIERTLS -server -tcpd \
			        -user=@mailuser@ \
				@libexecdir@/courier/imaplogin \
				@bindir@/imapd ${MAILDIRPATH}"
	;;
stop)
	@courierlogger@ -pid=$SSLPIDFILE -stop
	;;
restart)
	@courierlogger@ -pid=$SSLPIDFILE -restart
	;;
esac
exit 0
