#!/bin/bash

# mailage.sh - Process each message and keep it or discard it.

MAILDATE=/usr/local/bin/maildate.sh
function writerest () { # Write rest of message to output
		echo "$from $address $dayofweek $month $dayofmonth $time $timezone $year"
		cat -
	# If your cat is broken and doesn't echo lines faithfully then comment
	#   the _cat_ line above and uncomment the following four lines

	#	while read -r inputstring
	#	do
	#		echo $inputstring
	#	done
}

# keepdate = integer representation of date before which to discard

keepdate=$1
read -r from address dayofweek month dayofmonth time timezone year

# If formail had to fix the message date, there's no time zone in it.

if [ X"$year"X = XX ]
then
	year=$timezone
	timezone="GMT"
fi

msgdate=`$MAILDATE $month $dayofmonth $year`

if [ $? -le 1 ] # Parsing OK
then
	if [ $msgdate -gt $keepdate ] # Recent message
	then
		writerest
	fi
else # Error in date parsing; save message
	writerest
fi
