#!/bin/sh

if [ $# -ne 5 ]; then
  echo "Usage: $0 <recipient> <sender> <subject> <description> <file name>"
  exit 1
fi

RECIPIENT="$1"
SENDER="$2"
SUBJECT="$3"
DESCRIPTION="$4"
FILENAME="$5"

if [ -n "$FILENAME" ] && [ ! -r "$FILENAME" -o ! -f "$FILENAME" ]; then
  echo "Error: '$FILENAME' does not exist or is not a regular file."
  exit 1
fi

UUENCODE="/usr/bin/uuencode"
GIBRALTAR_VERSION=`cat /system/etc-static/gibraltar/version`
HOSTNAME=`hostname`
DATE=`date`

# first try to create the temporary file - /tmp might not be writable now
if [ -e /tmp/mail.txt ]; then
  if ! rm -f /tmp/mail.txt; then
    echo "Error: could not remove /tmp/mail.txt - some attack may be happening. Exiting now."
    exit 1
  fi
fi
if ! touch /tmp/mail.txt; then
  echo "Error: Unable to create /tmp/mail.txt - /tmp might not be writable"
fi

echo -n "Preparing email to send ... "
echo "To: $RECIPIENT" >> /tmp/mail.txt
echo "From: $SENDER" >> /tmp/mail.txt
echo "Subject: [Gibraltar on host $HOSTNAME] $SUBJECT" >> /tmp/mail.txt
echo "" >> /tmp/mail.txt
echo "Created: $DATE" >> /tmp/mail.txt
echo "Host: $HOSTNAME" >> /tmp/mail.txt
echo "Gibraltar version: $GIBRALTAR_VERSION" >> /tmp/mail.txt
echo "" >> /tmp/mail.txt
echo "Error description:" >> /tmp/mail.txt
echo "$DESCRIPTION" >> /tmp/mail.txt
echo "" >> /tmp/mail.txt
if [ -n "$FILENAME" -a -r "$FILENAME" ]; then
    $UUENCODE $FILENAME `basename $FILENAME` >> /tmp/mail.txt
fi
echo -n "sending ... "
if /usr/lib/sendmail -t -f "$SENDER" < /tmp/mail.txt; then
  echo "done."
else
  echo "failed."
fi
rm /tmp/mail.txt

exit 0
