#!/bin/sh
# rmoldmail Ver1.1 : Script to remove old mails in Maildir of a user.
# Written by T.Nonogaki Stray-Penguin <http://www.asahi-net.or.jp/~aa4t-nngk/>
#
PATH="/bin:/usr/bin:$PATH"
ME=$(basename $0)

## Customizeable variables.
# If you are utilizing virtual mail users using qmail-vida or some,
# consider these.
#
# If set to 1, virtual user Maildir detection is ALWAYS enabled.
# However, you may leave this being 0 and specify -V on each call to
# enable this function.
VMAIL=0
# Directory origin where virtual mail user directories reside.
# Dont put trailing slash.
VMDIR=/home/popusers

function show_help() {
    cat <<EOM
USAGE:
 $ME [-V] HOW_DAYS_OLD [OWNER]
 EXAMPLE1: \`$ME 7' removes 7 or more day-old mails of script runner.
 EXAPMLE2: \`$ME 14 hoge' removes 14 or more day-old mails of user hoge.
 EXAMPLE3: \`$ME -V 14 hoge' same as above except hoge is a virtual mail
  user (refer to the comments in the script itself).
 EXAPMLE4: \`$ME 14 /home/hoge' if OWNER section begins with a slash,
  $ME assumes that it is a directory name and scans OWNER/Maildir. It
  should be an absolute directory path and you should NOT append /Maildir.
EOM
exit 1
}

[ $# -lt 1 ] && show_help

for i; do
    if [ "${i: 0: 1}" = "-" ]; then
	case $i in
	--help|-h)
		show_help
		;;
	-V)
		VMAIL=1
		;;
	esac
    else
	if [ -z "$DAYS" ]; then
	    DAYS=$i
	elif [ -z "$OWNER" ]; then
	    OWNER=$i
	fi
    fi
    shift
done

[ -z "$DAYS" ] && show_help
if [ -z $(echo $DAYS | grep -E '^[1-9][0-9]*$') ]; then
	show_help
fi

DIR=~/Maildir
if [ -n "$OWNER" ]; then
    if [ "${OWNER: 0: 1}" = "/" ]; then
	eval DIR=${OWNER%/}/Maildir
    elif [ "$VMAIL" = "1" -a -n "$VMDIR" ]; then
	eval DIR=${VMDIR%/}/${OWNER}/Maildir
    else
	eval DIR=~${OWNER}/Maildir
    fi
fi
if [ ! -d $DIR ]; then
	echo "no such Maildir \`${DIR}'." >&2
	exit 1
fi

find ${DIR}/ -type f -mtime +$DAYS -exec rm -f '{}' ';' &>/dev/null
exit $?
