#!/bin/sh -e

###############################################################################
# dspam retrain script by IOnut	<itetcu@people.tecnik93.com>                  #
# provided "as it is, no gurantees" under BSD license                         #
# v1.3 2005-04-19 00:54:46                                                    #
###############################################################################

#
# I'm runned by local(8) as destination user or nobody if he is root 
# remember that dspam and/or dpamc should be runnable as this user
# and dspamc should be able to read and write to dspam.sock which has srwxrwx--x 
# and this user should be able to write to the LOG_FILE.
#

#
# $2 is SENDER in master.cf for transport dspam-retrain
# the rest 3 are env variable (available from Postfix 2.2)
#
MAIL_INFO="sender: ${SENDER}, ${CLIENT_ADDRESS}, ${CLIENT_HELO}, ${CLIENT_HOSTNAME}"
EX_NOUSER="Can't determine user for ${MAIL_INFO}"
EX_DATAERR="Can't determine signature for ${MAIL_INFO}"

# $1 is ${nexthop} in master.cf for trasport dspam-retrain 
# as defined in dspam_retrain_transport (on right of ``:'')
# should be ``spam'' for spam@ and ``innocent'' for fp@
#
CLASS="$1"

#
# LOG_EN=true if you want to log all commands sent to dspam
# else only errors are logged to $LOG_FILE (see below) and maillog
#
LOG_EN=true
LOG_FILE=/var/log/dspam/dspam.missed_${CLASS}

#
# The actual stuff
#

IN=`cat - |  egrep 'X-DSPAM-User|X-DSPAM-Signature'`
SP_USER=`echo ${IN} | cut -d ' ' -f 2`
SP_SIG=`echo ${IN} | cut -d ' ' -f 4`
if [ -n "${SP_USER}" ]; then
	logger -i -p mail.warn -t $0 ${EX_NOUSER}
	echo ${EX_NOUSER}
	exit 67
fi
if [ -n "${SP_SIG}" ]; then
	logger -i -p mail.warn -t $0 ${EX_DATAERR}
	echo ${EX_DATAERR}
        exit 65
fi

RETRAIN_CMD="/usr/local/bin/dspam --user ${SP_USER} --class=${CLASS} \
--source=error --process --signature=${SP_SIG}"
RET_CODE= ${RETRAIN_CMD}
if ${LOG_EN}; then
	echo "For ${MAIL_INFO command ${RETRAIN_CMD} exited with ${RET_CODE}" >> \
		${LOG_FILE}
fi
exit ${RET_CODE}
