#!/bin/bash

# Based on the script by Kelly French
# http://marc.info/?l=qmail&m=105641953707239&w=2

TEMPFAILDELAY="5min"
BASE="/var/qmail/tempfail"

Success=0
InvalidAddress=100
TemporaryVerificationFailure=111
TemporaryExecutionFailure=120

if [ -z "$RECIPIENT" ] ; then
	echo RECIPIENT not set
	exit $TemporaryVerificationFailure
fi
if [ -z "$TCPREMOTEIP" ] ; then
	echo TCPREMOTEIP not set
	exit $TemporaryVerificationFailure
fi

# Lowercase everything
SENDER=$( tr '[:upper:]' '[:lower:]' <<<"$SENDER" )
RECIPIENT=$( tr '[:upper:]' '[:lower:]' <<<"$RECIPIENT" )

# NOTE: before you go any further, you should probably ensure that
# the RECIPIENT is valid

# Create one directory per recipient
mkdir -p "$BASE/$RECIPIENT"

testwhitelist="$BASE/$RECIPIENT/$SENDER"
if [ -f "$testwhitelist" ] ; then
	# this recipient/sender is whitelisted
	exit $Success
fi

testtuple="$BASE/$RECIPIENT/$TCPREMOTEIP/$SENDER"
if [ ! -f "$testtuple" ] ; then
	# never seen 'em before
	mkdir -p "$BASE/$RECIPIENT/$TCPREMOTEIP"
	touch -d "now+$TEMPFAILDELAY" "$testtuple"
	exit $TemporaryVerificationFailure
fi

now=$(mktemp -t greylist.now.XXXXXXXXXX)
if [ "$now" -nt "$testtuple" ] ; then
	# retried too soon
	rm "$now"
	exit $TemporaryVerificationFailure
fi

# If we get this far, we're good to go
rm "$now"
# mark it as confirmed
if [ ! -s "$testtuple" ] ; then
	# This way we can have a cron job remove all old empty files (i.e. things
	# that were blocked and never retried)
	# The command to clean this up would be:
	# find /var/qmail/tempfail -empty ! -ctime +1 -delete
	echo "1" > "$testtuple"
fi
exit $Success
