#!/bin/sh
#
# Saves an incoming email as plain text file (or .eml)
# somewhere in the webservers directories
# Author: Dominic Reich <quick.hat4396@qtztsjosmprqmgtunjyf.com>
# License: MIT

#umask 133

date=`date +%Y%m%d-%H%M%S`
tmpf="/tmp/mail-$(echo ${date} | sha1).tmp"
folder="/var/www/htdocs/emails"

#cat $* > ${FILE}

while read line; do
  case "$line" in
    From:*|To:*|C[Cc]:*|Delivered-To:*|Date:*|Subject:*|Received:*|Message-ID:*|User-Agent:*) echo $line >> ${tmpf};;
    "") (echo && cat $*) >> ${tmpf};;
    *) ;;
  esac
done

#SUBJECT="$(grep -i Subject ${TMPF} | awk -F': ' '{ print $2 }' | tr -cs "[:alnum:]" "-" | tr "äöüÄÖÜ" "aouAOU" | sed "s/-$//")"
#SUBJECT="$(grep -i "^Subject:" ${TMPF} | cut -d: -f2- | sed "s/^\ //" | tr -cs "[a-zA-z0-9äöüÄÖÜ]" "-" | tr "äöüÄÖÜ" "aouAOU" | sed "s/-$//" | qprint -d)"

# last sed: remove all "-" not only the last one, shrinks the name, but is not very readable...
# subject="$(grep -i "^Subject:" ${tmpf} | cut -d: -f2- | sed "s/^\ //" | tr -Cs "[:alnum:]" "-" | sed "s/-//g" | qprint -d)"
subject="$(grep -i "^Subject:" ${tmpf} | cut -d: -f2- | sed "s/^\ //" | tr -Cs "[:alnum:]" "-" | sed "s/-$//" | qprint -d)"
to="$(grep -i "^Delivered-To:" ${tmpf} | cut -d: -f2- | cut -d@ -f1 | xargs)"

#: "${VARIABLE:=DEFAULT_VALUE}"

: "${subject:=NoSubjectGiven}"
: "${to:=unknown}"

filename="${date}_${subject}.txt"

file="${folder}/${to}/${filename}"
link="http://bor.oe7drt.com/mailarchive/${to}/${filename}"

mv "${tmpf}" "${file}"

echo -e "New mail in archives: ${subject}\n\n<${link}>\n\n-- \nMail sorting script \`${0}\` to your service.\n" | \
mail -s "New mail in archives: ${to}" -- recipient@localhost.localdomain