#!/sbin/sh

# Start/Stop Dovecot IMAP/POP server

. /lib/svc/share/smf_include.sh
CONF_FILE=/etc/dovecot.conf
BASEDIR=@CLIENT_BASEDIR@


getRunDir() {
	RUNDIR=`egrep '^base_dir' ${CONF_FILE} 2>/dev/null | awk '{ print $3 }'`
	if [ -z "$RUNDIR" ]; then
		echo "No base_dir property set in ${CONF_FILE} - exiting."
		exit $SMF_EXIT_ERR_CONFIG
	fi
}

ZN=`/sbin/zonename`
if [ "$ZN" = "global" ]; then
    ZPPID=1
else
    ZPPID=`pgrep -x zsched 2>/dev/null`
fi

case "$1" in
'start')
	if [ ! -x $BASEDIR/sbin/dovecot ]; then
		echo "$BASEDIR/sbin/dovecot is not executable"
		exit $SMF_EXIT_ERR_FATAL
	fi
	if [ ! -f ${CONF_FILE} ]; then
		echo "Missing config file ${CONF_FILE}"
		exit $SMF_EXIT_ERR_CONFIG
	fi
	getRunDir
	if [ ! -d "$RUNDIR" ]; then
		mkdir -p $RUNDIR
		if [ $? -ne 0 ]; then
			echo "Unable to create directory $RUNDIR"
			exit $SMF_EXIT_ERR_CONFIG
		fi
	fi
	chmod 0755 $RUNDIR
	PID=`pgrep -u 0 -P $ZPPID ${BASEDIR}/dovecot 2>/dev/null`
	if [ -n "$PID" ]; then
		echo "$BASEDIR/sbin/dovecot is already running"
		exit $SMF_EXIT_OK
	fi
	$BASEDIR/sbin/dovecot
	if [ $? -ne 0 ]; then
		exit $SMF_EXIT_ERR_FATAL
	fi
	;;
'refresh')
	pkill -HUP -u 0 -P $ZPPID ${BASEDIR}/dovecot
	;;
'stop')
	getRunDir
	if [ -f "${RUNDIR}/master.pid" ]; then
		kill -INT `cat ${RUNDIR}/master.pid`
	fi
	PID=`pgrep -u 0 -P $ZPPID ${BASEDIR}/dovecot 2>/dev/null`
	if [ -n "$PID" ]; then
		pkill -INT -u 0 -P $ZPPID ${BASEDIR}/dovecot
	fi
	;;
'dump')
	# dump config
	[ -x $BASEDIR/sbin/dovecot ] && $BASEDIR/sbin/dovecot -a
	;;
'dumpnd')
	# dump non-default config values
	[ -x $BASEDIR/sbin/dovecot ] && $BASEDIR/sbin/dovecot -n
	;;
'buildopts')
	# dump build options
	[ -x $BASEDIR/sbin/dovecot ] && $BASEDIR/sbin/dovecot --build-options
	;;
*)
	echo "Usage: $0 { start | stop | refresh | dump | dumpnd | buildopts }"
	exit 1
	;;
esac
exit $SMF_EXIT_OK
