#!/bin/sh


#
#  Nicolas Rachinsky <nr@rachinsky.de> 
#
#   BSD-style copyright and standard disclaimer applies.
#
#
#   first param is an mbox (optionally gzipped) 
#   second param is an mbox (optionally gzipped)
#        if one of them is gzipped the name must end with .gz, if not it must not end with .gz
#   third param is time offset for date (without leading "-")
#   e.g. 2w or 3m
#
#   minimal errorchecking

if [ $# != 3 ]; then
        echo "wrong parameters"
        exit 1
fi


if [ -e $1.tmp ];then
	echo $1.tmp already exists
	exit 1
fi

case $1 in
*.gz)
	in_filter="gzip -9"
;;
*.bz2)
	in_filter="bzip2"
;;
*)
	in_filter="cat"
;;
esac

case $2 in
*.gz)
	out_filter="gzip -9"
;;
*.bz2)
	out_filter="bzip2"
;;
*)
	out_filter="cat"
;;
esac

switchdate="`date -v -$3 '+%Y-%m-%d'`"
if [ $? != 0 ]; then
	echo "Wrong third paramter"
	exit 1
fi

if [ $2 != /dev/null ]; then
	touch $2 || { echo "couldn't touch $2";exit 1; }
	mutt_dotlock $2 || { echo "couldn't lock $2";exit 1; }
fi

mutt_dotlock $1 || { echo "couldn't lock $1";exit 1; }

if [ $2 != /dev/null ]; then
	(grepmail -a -d "before $switchdate" $1 | $out_filter >>$2) || { echo "error appending to $2";exit 2;}
fi


(grepmail -a -v -d "before $switchdate" $1 | $in_filter >$1.tmp) || { echo "error appending to $1.tmp";exit 3;}

mv -f $1.tmp $1||{ echo "error renaming $1.tmp to $1";exit 4;}

if [ $2 != /dev/null ]; then
	mutt_dotlock -u $2 ||  { echo "couldn't unlock $2";exit 1;}
fi
mutt_dotlock -u $1 || { echo "couldn't unlock $1";exit 1;}

