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


prefix=/usr/pkg
exec_prefix=/usr/pkg
bindir=${exec_prefix}/bin
libexecdir=/usr/pkg/libexec/courier
sbindir=${exec_prefix}/sbin

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

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

TLS_CACHEFILE=""
. /usr/pkg/etc/courier/imapd
. /usr/pkg/etc/courier/imapd-ssl

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

	umask ${IMAP_UMASK:=022}
	if test ! -f "${IMAPACCESSFILE}.dat"
	then
		if test -e "${IMAPACCESSFILE}"
		then
			${exec_prefix}/bin/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/pkg ;
		exec_prefix=/usr/pkg ;
		bindir=${exec_prefix}/bin ;
		libexecdir=/usr/pkg/libexec/courier ;
		sbindir=${exec_prefix}/sbin ;
		. /usr/pkg/etc/courier/imapd ; \
		. /usr/pkg/etc/courier/imapd-ssl ; \
		PROXY_HOSTNAME=$PROXY_HOSTNAME ; \
		IMAP_TLS=1; \
		./install-sh -c -d `dirname $SSLPIDFILE` ; \
		/usr/pkg/sbin/courierlogger -pid=$SSLPIDFILE -start $SSLLOGGEROPTS \
		${exec_prefix}/sbin/couriertcpd -address=$SSLADDRESS \
			-maxprocs=$MAXDAEMONS -maxperip=$MAXPERIP \
			-access=$IMAPACCESSFILE.dat \
			$TCPDOPTS \
			$SSLPORT $COURIERTLS -server -tcpd \
				-user=courier \
				/usr/pkg/libexec/courier/imaplogin \
				${exec_prefix}/bin/imapd ${MAILDIRPATH}"
	;;
stop)
	/usr/pkg/sbin/courierlogger -pid=$SSLPIDFILE -stop
	;;
restart)
	/usr/pkg/sbin/courierlogger -pid=$SSLPIDFILE -restart
	;;
esac
exit 0
