#! /bin/sh
#
# Copyright 1998 - 2015 S. Varshavchik.
# See COPYING for distribution information.


prefix=/usr/local
exec_prefix=/usr/local
bindir=${exec_prefix}/bin
libexecdir=/usr/local/libexec/courier-imap

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

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

TLS_CACHEFILE=""
. /usr/local/etc/courier-imap/imapd-ssl
. /usr/local/etc/courier-imap/imapd

case $1 in
start)
	if test "$TLS_CACHEFILE" != ""
	then
		rm -f "$TLS_CACHEFILE"
		touch "$TLS_CACHEFILE"
		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
			${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/local ;
			exec_prefix=/usr/local ;
			bindir=${exec_prefix}/bin ;
			libexecdir=/usr/local/libexec/courier-imap ;
				. /usr/local/etc/courier-imap/imapd-ssl ; \
				. /usr/local/etc/courier-imap/imapd ; \
		IMAP_STARTTLS=$IMAPDSTARTTLS ; \
		PROXY_HOSTNAME=$PROXY_HOSTNAME ; \
		TLS_PROTOCOL=$TLS_STARTTLS_PROTOCOL ; \
		/bin/mkdir -p `dirname $PIDFILE` ; \
		/usr/local/sbin/courierlogger -pid=$PIDFILE -start $LOGGEROPTS \
		/usr/local/libexec/courier-imap/couriertcpd -address=$ADDRESS \
			-maxprocs=$MAXDAEMONS -maxperip=$MAXPERIP \
			-access=$IMAPACCESSFILE.dat \
			$TCPDOPTS \
			$PORT ${exec_prefix}/sbin/imaplogin ${exec_prefix}/bin/imapd ${MAILDIRPATH}"
	;;
stop)
	/usr/local/sbin/courierlogger -pid=$PIDFILE -stop
	;;
restart)
	/usr/local/sbin/courierlogger -pid=$PIDFILE -restart
	;;
esac
exit 0
