#!/bin/sh
#
# This program is free software. It comes without any warranty, to
# the extent permitted by applicable law. You can redistribute it
# and/or modify it under the terms of the Do What The Fuck You Want
# To Public License, Version 2, as published by Sam Hocevar. See
# http://sam.zoy.org/wtfpl/COPYING for more details.
#
# Meant to be run as the `debian-spamd` user.

set -e

MAILDIR=/srv/rtmailarchive/Maildir

trap 'rm -f "$SA_LEARN_FOLDERLIST"' EXIT
SA_LEARN_FOLDERLIST=$(mktemp --tmpdir train-rtmailarchive-spams.XXXXXX)

for learntype in spam ham; do
	find "$MAILDIR/.$learntype-tolearn/new" "$MAILDIR/.$learntype-tolearn/cur" \
		-type f -printf "$learntype:file:%p\n" >> "$SA_LEARN_FOLDERLIST"
done

sa-learn --folders="$SA_LEARN_FOLDERLIST"

OLD_IFS="$IFS"
IFS=:
while read learntype foldertype path; do
	mv "$path" "$MAILDIR/.$learntype-learned/cur"
done < "$SA_LEARN_FOLDERLIST"
IFS="$OLD_IFS"

for learntype in spam ham; do
	find "$MAILDIR/.$learntype-learned/cur" -mtime +30 -delete
done
