#!/bin/sh

. /usr/share/alterator/build/backend3.sh

SPAMD_CONF="/var/lib/spamd/.spamassassin/user_prefs"
FILTER_CONF="/etc/sa-content-filter/system"

_()
{
LANG=${in_language%%;*}.utf8 gettext "alterator-spamassassin" "$1"
}

service postfix start >&2 ||:
service spamd start >&2 ||:

read_required_score()
{
    sed -nr '/^required_score/ {s,^required_score[[:space:]]([0-9]+).*,\1,;p}' "$SPAMD_CONF"
}

write_required_score()
{
    sed -r "s,^required_score[[:space:]]+.*,required_score $1," -i "$SPAMD_CONF"
    service spamd reload >&2
}

read_filter_mode()
{
    sed -nr '/^FILTER_MODE=/ {s,^FILTER_MODE=([^[:space:]]+).*,\1,;p}' "$FILTER_CONF"
}

write_filter_mode()
{
    sed -r "s,^FILTER_MODE=.*,FILTER_MODE=$1," -i "$FILTER_CONF"
}

on_message()
{
	case "$in_action" in
		constraints)
			echo '('
			if [ "$in__objects" == "/" ] ; then
			    printf 'smtp_mode (label "%s")' "`_ "SMTP transport status"`"
			    printf 'filter_mode (label "%s")' "`_ "Spam filter mode"`"
			    printf 'required_score (label "%s" match ("[0-9]+" "%s"))' \
				"`_ "Required score"`" \
				"`_ "should be number"`"
			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" == "filter_modes" ];then
			    printf '("pass" label "%s")' "`_ "Mark only"`"
			    printf '("drop" label"%s")' "`_ "Drop mail"`"
			fi
			echo ')'
			;;
		read)
			echo '('
			printf ' smtp_mode "%s"' "$(control postfix)"
			printf ' filter_mode "%s"' "$(read_filter_mode)"
			printf ' required_score "%s"' "$(read_required_score)"
			echo ')'
			;;
		write)
			[ -n "$in_smtp_mode" ] && control postfix "$in_smtp_mode" >&2
			[ -n "$in_required_score" ] && write_required_score "$in_required_score"
			[ -n "$in_filter_mode" ] && write_filter_mode "$in_filter_mode"
			echo '()'
			;;
		*)
			echo '#f'
			;;
	esac
}


message_loop

