#!/bin/sh
#
# $NetBSD: greylisting-spp-wrapper.sh,v 1.2 2019/04/14 13:28:44 schmonz Exp $
#
# qmail-run-20240206 wrapper for greylisting-spp.
# Skips greylisting for configured recipient addresses and domains.
# Optionally assigns a fixed "ip" in (ip,sender,recipient).
#

EXEMPTRCPTS=/usr/pkg/etc/qmail/control/greylist/exemptrcpts
EXEMPTRCPTHOSTS=/usr/pkg/etc/qmail/control/greylist/exemptrcpthosts

is_exempt_recipient_address() {
	[ -f "$EXEMPTRCPTS" ] \
		&& /usr/bin/grep -qFxi -- "$1" "$EXEMPTRCPTS"
}

is_exempt_recipient_domain() {
	[ -f "$EXEMPTRCPTHOSTS" ] \
		&& /usr/bin/grep -qFxi -- "$1" "$EXEMPTRCPTHOSTS"
}

main() {
	[ -n "$SMTPRCPTTO" ] || return

	rcpt="$SMTPRCPTTO"
	rcpthost=$(echo "$rcpt" | /usr/bin/sed -e 's|.*@||')

	if is_exempt_recipient_address "$rcpt"; then
		echo >&2 "greylisting skipped for recipient address: $rcpt"
		GL_WHITELISTED="1"; export GL_WHITELISTED
	elif is_exempt_recipient_domain "$rcpthost"; then
		echo >&2 "greylisting skipped for recipient domain: $rcpthost"
		GL_WHITELISTED="1"; export GL_WHITELISTED
	fi

	if [ -n "$GL_WRAPPER_TCPREMOTEIP" ]; then
		TCPREMOTEIP="$GL_WRAPPER_TCPREMOTEIP"; export TCPREMOTEIP
	fi
}

main "$@"
exec /usr/pkg/bin/greylisting-spp
