#!/bin/sh
#
# $NetBSD: courieresmtps.sh,v 1.6 2008/02/19 18:45:24 jlam Exp $
#
# Courier ESMTP/SSL services daemon
#
# PROVIDE: courieresmtps
# REQUIRE: authdaemond courierd
# KEYWORD: shutdown

. /etc/rc.subr

name="courieresmtps"
rcvar=${name}
command="/usr/pkg/sbin/couriertcpd"
ctl_command="/usr/pkg/sbin/esmtpd-ssl"
pidfile="/var/courier/tmp/esmtpd-ssl.pid"
required_files="/usr/pkg/etc/courier/esmtpd /usr/pkg/etc/courier/esmtpd-ssl"

start_precmd="${name}_prestart"
start_cmd="${name}_doit start"
stop_cmd="${name}_doit stop"

mkdir_perms()
{
	dir="$1"; user="$2"; group="$3"; mode="$4"
	test -d $dir || /bin/mkdir -p $dir
	/usr/sbin/chown $user $dir
	/usr/bin/chgrp $group $dir
	/bin/chmod $mode $dir
}

courieresmtps_prestart()
{
	mkdir_perms /var/courier/tmp \
		courier mail 0770
}

courieresmtps_doit()
{
	action=$1
	case $action in
	start)
		for f in $required_files; do
			if [ ! -r "$f" ]; then
				echo 1>&2 "$0: WARNING: $f is not readable"
				return 1
			fi
		done

		. /usr/pkg/etc/courier/esmtpd
		. /usr/pkg/etc/courier/esmtpd-ssl

		f="$TLS_CERTFILE"
		if [ -z "$f" ]; then
			echo 1>&2 "$0: WARNING: TLS_CERTFILE is empty"
			return 1
		fi
		if [ ! -f "$f" ] &&
		   [ "$f" = "/usr/pkg/etc/courier/esmtpd.pem" ]; then
			echo "Generating ESMTP SSL certificate in $f."
			/usr/pkg/sbin/mkesmtpdcert >/dev/null 2>&1
		fi
		if [ ! -r "$f" ]; then
			echo 1>&2 "$0: WARNING: $f is not readable"
			return 1
		fi

		case x$ESMTPDSSLSTART in
		x[yY]*)
			echo "Starting ${name}."
			test -f /usr/pkg/etc/courier/esmtpacceptmailfor.dat ||
				/usr/pkg/sbin/makeacceptmailfor
			test -f /usr/pkg/etc/courier/${ACCESSFILE}.dat ||
				/usr/pkg/sbin/makesmtpaccess
			${ctl_command} $action
               	;;
		esac
		;;
	stop)
		echo "Stopping ${name}."
		${ctl_command} $action
		;;
	esac
}

load_rc_config $name
run_rc_command "$1"
