#!/bin/sh

po_domain="alterator-postfix-sasl"
. alterator-sh-functions

######

read_auth_state()
{
    write_bool "$(postconf -h smtpd_sasl_auth_enable)"
}

check_restrictions()
{
    local param=smtpd_recipient_restrictions
    local rej=reject_unauth_destination
    local sasl=permit_sasl_authenticated
    local current="$(postconf -h "$param")"

    echo "$current"|grep -qs "$sasl" ||
	postconf -e "$param=$(echo $current| sed -r "s/,[[:space:]]*$rej/, $sasl , $rej/")"
}

write_auth_state()
{
    if test_bool "$1";then
	check_restrictions
	postconf -e smtpd_sasl_auth_enable=yes
    else
	postconf -e smtpd_sasl_auth_enable=no
    fi
}


read_sasl_mode()
{
    postconf -h smtpd_sasl_type
}

write_sasl_mode()
{
    if [ "$1" = "dovecot" ];then
	postconf -e smtpd_sasl_type=dovecot
	postconf -e smtpd_sasl_path=private/auth
    elif [ "$1" = "cyrus" ];then
	postconf -e smtpd_sasl_type=cyrus
	postconf -e smtpd_sasl_path=smtpd 
    fi
}

service postfix start >&2 ||:

on_message()
{
	case "$in_action" in
		constraints)
			echo '('
			if [ "$in__objects" == "/" ] ; then
			    printf ' smtp_mode  (label "%s")' "`_ "SMTP transport status"`"
			    printf ' auth_state (label "%s" default #f)' "`_ "SASL Authentication"`"
			    printf ' sasl_mode  (label "%s")' "`_ "Auth Server Type"`"
			fi
			echo ')'
			;;
		list)
			echo '('
			if [ "$in__objects" == "smtp_modes" ];then
			    printf '("local" label "%s")' "`_ "Off"`"
			    printf '("server" label "%s")' "`_ "On, without content filter"`"
			    printf '("filter" label "%s")' "`_ "On, with content filter"`"
			elif [ "$in__objects" == "sasl_modes" ];then
			    rpm -q postfix-cyrus &> /dev/null && printf '("cyrus" label "%s")' "`_ "Cyrus"`"
			    rpm -q postfix-dovecot &> /dev/null && printf '("dovecot" label"%s")' "`_ "Dovecot"`"
			fi
			echo ')'
			;;
		read)
			echo '('
			printf ' smtp_mode "%s"' "$(control postfix)"
			printf ' auth_state %s' "$(read_auth_state)"
			printf ' sasl_mode "%s"' "$(read_sasl_mode)"
			echo ')'
			;;
		write)
			[ -n "$in_smtp_mode" ] && control postfix "$in_smtp_mode" >&2
			[ -n "$in_auth_state" ] && write_auth_state "$in_auth_state"
			[ -n "$in_sasl_mode" ] && write_sasl_mode "$in_sasl_mode"
			
			service postfix reload >&2 ||:
			write_nop
			;;
		*)
			echo '#f'
			;;
	esac
}

message_loop
