#!/bin/sh
#
# $NetBSD: cyrus.sh,v 1.1.1.1 2010/10/30 12:12:35 obache Exp $
#
# PROVIDE: cyrus
# REQUIRE: DAEMON
# BEFORE: mail
# KEYWORD: shutdown
#
# To start cyrus-imapd at startup, copy this script to /etc/rc.d and set
# cyrus=YES in /etc/rc.conf.

if [ -f /etc/rc.subr ]; then
	. /etc/rc.subr
fi

rcd_dir=`/usr/bin/dirname $0`

name="cyrus"
rcvar=$name
command="/usr/pkg/cyrus/bin/master"
command_args="-d"
pidfile="/var/run/cyrus-master.pid"
sig_stop=QUIT
required_files="/usr/pkg/etc/cyrus.conf /usr/pkg/etc/imapd.conf"
extra_commands="mkimap reload"

mkimap_cmd="cyrus_mkimap"
start_precmd="cyrus_prestart"

cyrus_prestart()
{
	# Check to see if "configdirectory" is present before we start
	# the Cyrus IMAP server.  Otherwise, we run mkimap to generate
	# the necessary directories.
	#
	if [ -f /usr/pkg/etc/imapd.conf ]; then
		configdir=`						\
			/usr/bin/awk '/^configdirectory:/ { print $2; exit };'	\
			      /usr/pkg/etc/imapd.conf				\
		`
		if [ -z "$configdir" ]; then
			echo "/usr/pkg/etc/imapd.conf missing 'configdirectory' setting"
			exit 1
		fi
		if [ ! -d "$configdir" ]; then
			$rcd_dir/cyrus mkimap
		fi
	fi
}

cyrus_mkimap()
{
	# Generate the prerequisite directory structure for Cyrus IMAP.
	if [ -f /usr/pkg/etc/imapd.conf ]; then
		/usr/bin/awk '/^configdirectory:/	{ print $2 };		\
		       /^partition-.*:/		{ print $2 };		\
		       /^sievedir:/		{ print $2 }'		\
		      /usr/pkg/etc/imapd.conf |					\
		while read dir; do
			if [ ! -d "$dir" ]; then
				/bin/mkdir -p "$dir"
				/bin/chmod 750 "$dir"
				/usr/sbin/chown cyrus "$dir"
				/usr/bin/chgrp mail "$dir"
			fi
		done
		/usr/bin/su -m cyrus -c "/usr/pkg/cyrus/bin/mkimap"
	fi
}

if [ -f /etc/rc.subr -a -f /etc/rc.conf \
     -a -d /etc/rc.d -a -f /etc/rc.d/DAEMON ]; then
	load_rc_config $name
	run_rc_command "$1"
else
	echo -n " ${name}"
	eval ${start_precmd}
	${command} ${cyrus_flags} ${command_args}
fi
