#!/bin/bash
if [ "$1" == 'debug' ]; then set -x; shift; fi
#------------------------
REALPATH=`realpath $0`
WHERE=`dirname $REALPATH`
ME=`basename $REALPATH`
cd $WHERE
. ../../system.conf
. ../../common.conf
. ../../common.bashlib
#------------------------
. WatchMX.conf

trap cleanup 0 1 2 9 15

cleanup() {
:	echo "Cleaning up ..."
}

if [ -z "$1" ]
then	EXPIRE=$EXPIRATIONDAYS
else	EXPIRE=$1
fi

#echo "Expiring mailhogs older than $EXPIRE days ..."
logger "$ME[$$] Automatic expiration of mail hogs in class NXDOMAIN older than $EXPIRE days"

CANDIDATES=`$SQL "select count(IP) from mailhogs 
		where	(julianday('now') - julianday(date_event)) > $EXPIRE";`

if [ $CANDIDATES -eq 0 ]
then
	logger "$ME[$$] No candidates for expiration"
	exit
fi

echo "Candidates ....: $CANDIDATES"
echo "Expiration days: $EXPIRE"
logger $ME[$$] Candidates: $CANDIDATES for expiration

DBHOGS=`$SQL "select IP from mailhogs 
		where (julianday('now') - julianday(date_event)) > $EXPIRE";`

# First strip database ...
$SQL "delete from mailhogs 
	where (julianday('now') - julianday(date_event)) > $EXPIRE;"

$SQL "delete from affairs_by_ip
	where (julianday('now') - julianday(event_date)) > $EXPIRE;"

$SQL "Vacuum main;"	

# Cleanup in ipset ...
counter=0
for h in `echo "$DBHOGS"`
do
	((counter++))
	$IPSET -exist del $MYSET $h
	$IPSET -exist del custody $h
done

if [ ! -z "$PUB_PATH" ] 
then 
        cp $DB $PUB_PATH 
fi       

logger "$ME[$$]: Expired $counter mail hogs older than $EXPIRE days"
