#!/bin/sh

set -e

for dir in \
	/srv/mail/$LOGNAME-d/ \
	$HOME/Maildir \
	; do

	MAILDIR="$dir"
	if [ -d "$MAILDIR/.spam.learn" ] ; then
		break
	fi
done

if [ -d "$MAILDIR/.spam.learn" ] ; then
	cd "$MAILDIR/.spam.learn"
	files=$(find -type f)
	if [ -n "$files" ] ; then
		sa-learn --spam $files > /dev/null 2>&1
		if [ -d "$HOME/.bogofilter" ]; then
			bogofilter --register-spam -B $files
		fi
		for file in $files ;do
			mv $file $MAILDIR/.spam.learned/$file
		done
	fi
fi