#!/bin/bash [ ! -z "${DEBUG}" ] && set -x USER=${1:-$( id -un )} HOME="$( getent passwd $USER | cut -d ':' -f 6 )" BASE="${HOME}"/Maildir INOTIFY='/usr/bin/inotifywait' INOTIFY_EVENTS='moved_to,moved_from' INOTIFY_OPTIONS='--monitor --recursive --event'" ${INOTIFY_EVENTS}" SPAMC='/usr/bin/spamc' JUNK="${BASE}/Junk" NONJUNK="${BASE}/Junk" TRASH="${BASE}/Trash" SENT="${BASE}/Sent" DRAFTS="${BASE}/Drafts" if [[ -f "${HOME}/.junkerrc" && -r "${HOME}/.junkerrc" ]] then . "${HOME}/.junkerrc" fi function Log { echo -e "$( date +'%Y%m%d %H:%M:%S' )\t$@" } function Cleanup { Log "Exiting" exit 0 } function Learn { [[ "$1" != "ham" && "$1" != "spam" ]] && return 3 [[ ! -f "$2" || ! -r "$2" ]] && return 4 Log "Learning $2 as $1" exec 9<"$2" ${SPAMC} --learntype $1 <&9 ret=$? case $ret in 0) Log "Done" ;; 5) Log "Learned" ;; 6) Log "Already known" ;; *) Log "Error occured, code $ret" ;; esac exec 9<&- } if [ ! -d "${BASE}" ] then echo "Error: Mail directory not found at ${BASE}, exiting" >&2 exit 1 fi if [ ! -x ${INOTIFY} ] then echo "Error: inotifywait not found, check path" >&2 exit 1 fi if [ ! -x ${SPAMC} ] then echo "Error: spamc not found, check path" >&2 exit 1 fi checkfile=$( mktemp ) echo ${RANDOM} >${checkfile} ${SPAMC} --learntype forget <${checkfile} >/dev/null 2>&1 if [ $? -eq 74 ] then echo "Error: spamd doesn't allow connections, needs --allow-tell" >&2 rm -f ${checkfile} exit 1 fi rm -f ${checkfile} trap "Cleanup" EXIT SIGINT SIGTERM trap "Reload" SIGHUP while IFS=' ' read -r dir event file do if [[ "${dir}" != */cur/ && "${dir}" != */new/ ]] then continue fi case "${dir}" in ${TRASH}/*) ;& ${SENT}/*) ;& ${DRAFTS}/*) continue esac if [[ "${event}" == *MOVED_TO* && "${dir}" == "${JUNK}"/cur/ ]] then Learn "spam" "${dir}/${file}" elif [[ "${event}" == *MOVED_TO* && "${dir}" == "${JUNK}"/new/ ]] then Learn "spam" "${dir}/${file}" elif [[ "${event}" == *MOVED_TO* && "${dir}" == "${NONJUNK}"/cur/ ]] then Learn "ham" "${dir}/${file}" elif [[ "${event}" == *MOVED_FROM* && "${dir}" == "${JUNK}"/cur/ ]] then Learn "ham" "${dir}/${file}" elif [[ "${event}" == *MOVED_TO* && "${dir}" == ${BASE}/*/new/ ]] then Learn "ham" "${dir}/${file}" fi done < <( ${INOTIFY} ${INOTIFY_OPTIONS} --format '%w %e %f' ${BASE} )