#!/bin/sh

# RETURN CODES
# 111 = temporary failure
# 1   = permanent failure
# 0   = okay

LOG="$0.log"
ME=`basename $0`
SQLITE=`which sqlite3`
TAI=`echo|tai64n`

# read configuration
. $0.conf

exec 2>&1
exec 1>>$LOG

# should not happen!
test -z $SQLITE && exit 0

function out_okay() {
  echo "${TAI}$ME: pid $$ [OK] $TCPREMOTEIP|$SENDER|$RECIPIENT"
  $SQLITE $DB << EOF
UPDATE greylist set "ts_mtime" = "$ctime","ts_expires" = "$expire_good",
"recipient" = "good","sender" = "good" WHERE ("id" = "$1");
EOF
  exit 0
}

function out_wlist() {
  echo "${TAI}$ME: pid $$ [WL] $TCPREMOTEIP|$SENDER|$RECIPIENT"
  exit 0
}

function out_fail() {
  echo "${TAI}$ME: pid $$ [??] $TCPREMOTEIP|$SENDER|$RECIPIENT"
  exit $1
}

# create database, if not there
if [ ! -f $DB ]; then
  $SQLITE $DB << EOF
CREATE TABLE greylist
(
 id              INTEGER PRIMARY KEY AUTOINCREMENT,
 ip              TEXT,     -- ip of remote mailserver
 sender          TEXT,     -- mail address of sender
 recipient       TEXT,     -- mail address of recipient 
 ts_ctime        INTEGER,  -- timestamp of record creation
 ts_mtime        INTEGER,  -- last record update
 ts_expires      INTEGER,  -- the date after which this record is ignored
 count_passed    INTEGER   -- num of passed attempts we have allowed
);
EOF
fi

# these have to be set!
test -z $RECIPIENT   && out_fail 1
test -z $TCPREMOTEIP && out_fail 1
# $SENDER can be empty!

# check SENDER @ goodmailfrom list
if [ -s $GMF ]; then
  for email in `cat $GMF`; do
    test "x$email" = "x$SENDER" && out_wlist
  done
fi

# generate times for now()
ctime=`date "+%s"`
expire_good=$((ctime+(60*60*24*EXPIRE_GOOD)))
expire_block=$((ctime+(60*EXPIRE_BLOCK)))

# 1. look for whitelisted ip
id=`$SQLITE $DB << EOF
SELECT ts_expires FROM greylist
 WHERE ("ip" = "$TCPREMOTEIP" )
 AND ("recipient" = "good")
 AND ("sender" = "good");
EOF`
[ "x$id" != "x" ] && out_okay $id

# 2. look for some old ip,mailfrom,rcptto tupel
id=`$SQLITE $DB << EOF
SELECT id FROM greylist
 WHERE ("ip" = "$TCPREMOTEIP" )
 AND ("recipient" = "$RECIPIENT")
 AND ("sender" = "$SENDER")
 AND ("ts_expires" > "$ctime");
EOF`
[ "x$id" != "x" ] && out_okay $id

# 3. insert new ip,mailfrom,rcptto tupel
$SQLITE $DB << EOF
INSERT INTO greylist ("ip", "sender", "recipient", "ts_ctime", "ts_mtime", "ts_expires")
VALUES ("$TCPREMOTEIP", "$SENDER", "$RECIPIENT", "$ctime", "$ctime", "$expire_block");
EOF

# temorary failure
out_fail 111
