#!/bin/sh
#
# abmails-* - do something only non-abmail files in spam folders
#
# Copyright (C) 2006-2008 Taiji Yamada <taiji@aihara.co.jp>
#
# This program is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Affero General Public License for more details.
#
#
# usage:
#   $ abmails-* -b -g -d -r
#   $ env MAILDIR=/var/spool/abmail/root abmails-* -b -g -d -r
#
dirranges(){ # -d=nday -p=prefix
  perl -s -e 'use POSIX; $tm=time(); for ($i=$d; $i>0; $i--) { print strftime("$p%Y%m%d\n",localtime($tm-$i*60*60*24)); }' -- "$@"
}
ABMAILFLAGS=""
while true; do
  case "$1" in
  -?*) ABMAILFLAGS="${ABMAILFLAGS} $1";;
  *) break;;
  esac
  shift
done
ABMAIL=`echo "$0" | sed 's|\(abmail\)s\([^/][^/]*\)$|\1\2|'`
case "$ABMAIL" in
*./*) ABMAIL_ROOT="`pwd`/"; export ABMAIL_ROOT; ABMAIL="`basename \"$ABMAIL\"`";;
esac
{ [ "${MAILDIR}" != "" ] && echo "${MAILDIR}" || cat <<EOF
$HOME/Mail
$HOME/Maildir
EOF
} | while read mailpath; do
if [ -d "${mailpath}" ] && cd "${mailpath}"; then
ANTISPAMDIRS="`dirranges -d=1 -p=\"spam-\"`"
"${ABMAIL_ROOT:-./}${ABMAIL}" ${ABMAILFLAGS} ${DEFAULT_ANTISPAMDIRS:-${ANTISPAMDIRS}} .${DEFAULT_ANTISPAMDIRS:-${ANTISPAMDIRS}}
fi
done
