#!/usr/bin/env bash

FROM=$1
TO=$2
SUBJECT=$3
USER=$4
MSG=$5

# do not send for next 24 hours
TIMELIMIT=$[24*60*60]
SENDDB=${TMP:-/tmp}/zarafa-vacation-$USER.db
SENDDBTMP=${TMP:-/tmp}/zarafa-vacation-$USER.tmp

# Subject is required
if [ -z "$SUBJECT" ]; then
    SUBJECT="Autoreply";
fi
# not enough parameters
if [ -z "$FROM" -o -z "$TO" -o -z "$USER" -o -z "$MSG" ]; then
    exit 0;
fi
if [ ! -f "$MSG" ]; then
    exit 0;
fi

# Loop prevention tests
if [ "$FROM" == "$TO" ]; then
    exit 0;
fi
shortto=`echo "$TO" | sed -e 's/\(.*\)@.*/\1/' | tr '[A-Z]' '[a-z]'`
if [ "$shortto" == "mailer-daemon" -o "$shortto" == "postmaster" -o "$shortto" == "root" ]; then
    exit 0;
fi
shortfrom=`echo "$FROM" | sed -e 's/\(.*\)@.*/\1/' | tr '[A-Z]' '[a-z]'`
if [ "$shortfrom" == "mailer-daemon" -o "$shortfrom" == "postmaster" -o "$shortfrom" == "root" ]; then
    exit 0;
fi

# Check if mail was send in last $TIMELIMIT timeframe
TIMESTAMP=`date +%s`
if [ -f "$SENDDB" ]; then
    while read last to; do
	if [ "$TO" != "$to" ]; then
	    continue
	fi
	if [ $[$last+$TIMELIMIT] -ge $TIMESTAMP ]; then
	    exit 0;
	fi
    done < "$SENDDB"
fi

umask 066
grep -v "$TO" "$SENDDB" > "$SENDDBTMP" 2>/dev/null
mv "$SENDDBTMP" "$SENDDB" 2>/dev/null
echo $TIMESTAMP "$TO" >> "$SENDDB" 2>/dev/null

/usr/sbin/sendmail -t -f "$FROM" < "$MSG"
