#!/bin/sh
#
# abmailrescue - rescue only abmail files
#
# 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.
#
ABMAILFLAGS=""
while true; do
  case "$1" in
  -?*) ABMAILFLAGS="${ABMAILFLAGS} $1";;
  *) break;;
  esac
  shift
done
if [ "$1" = "" ]; then
  cat <<EOF
usage:
  $ find ~/Mail/spam -name '[0-9]*' -exec abmailrescure -b -g -r {} \;
  $ abmailrescure -b -g -r ~/Mail/spam -name
EOF
  exit 1
fi
substmaildir() {
  echo "$1" | sed -e "s|/new/\([^/][^/]*\)|$2|"
}
ismaildir() {
  [ -d "$1/cur" -a -d "$1/tmp" -a -d "$1/new" ]
}
"${ABMAIL_ROOT:-./}abmail" ${ABMAILFLAGS} + "$@" | while read f; do
  cat "$f" | eval procmail -Yf- SW_ANTISPAM=off ${PROCMAILARGS} &&
  case "$f" in
  */new/*[!/]*)
    ismaildir "`substmaildir \"$f\"`" &&
    mv "$f" "`substmaildir \"$f\" \"/cur/\1\"`" ||
    mv "$f" "`dirname \"$f\"`/~`basename \"$f\"`"
    ;;
  *)
    mv "$f" "`dirname \"$f\"`/~`basename \"$f\"`"
    ;;
  esac
done
