#!/bin/bash
#
# from: http://www.linuxquestions.org/questions/linux-newbie-8/foo-769222/
# see also: https://github.com/brightcode/smtpd/blob/master/c/smtpd.c
# github: search smtpd
#
# This is a personal MDA that I am using to parse mail to SNMP traps. 
# Do NOT ever use this for anything important! It is a toy! (but a kinda cool one)
# This script has no safety! Only use in on Local LAN's.
# remember anything less than port 1024 needs root to run.
#
#
# TODO:
# - check: http://mxtoolbox.com/SuperTool.aspx?action=smtp%3a4.v.weimarnetz.de&run=toolpage

export PORT
[ "$1" ] && PORT=$1	# e.g. 25
[ ! "$PORT" ] && exit

echo "-l -p $PORT -e $0" | nc 2>/dev/null &
[ "$1" ] && exit

MYSERVER='4.v.weimarnetz.de'
FILE="$( mktemp /tmp/mail_$(date +%s)_XXXXXXXXXX )"
LOG='/tmp/mail.log'

answer()
{
	logger -s "answer: $1"
	echo "$1"
}

write()
{
	logger -s "write: $1"
	echo "$1" >>"$FILE"
}

log()
{
	echo "$(date) $0: $1" >>"$LOG"
}

sleep 1
echo "220 $MYSERVER ESMTP smtpd.sh_MTA"

while read LINE; do
	case "$LINE" in		# TODO: 'HELP' and 'STARTTLS' (or TLS only on port 465?)
		'QUIT'*)
			answer "221 $MYSERVER doing something"
		;;
		'HELO'*)
			# hello message and server ID.
			answer "250 $MYSERVER"
			write "$LINE"
		;;
		'DATA'*)
			answer "354"
			write "$LINE"
		;;
		'.'|'quit'|*)
			answer "250 ok"
			write "$LINE"
		;;
	esac
done

# remove bullshit or sort in folders:
if [ -s "$FILE" ]; then
	if grep ^'MAIL From:<root@server1.domain.com>' "$FILE"; then
		log "[MYSELF] moved to /tmp/mail-from-myself"
		mkdir -p /tmp/mail-from-myself
		mv "$FILE" /tmp/mail-from-myself
	else
		if grep -q ^'Subject: ' "$FILE"; then
			log "[OK]"
		else
			log "[CRAP] removed"
			rm "$FILE"
		fi
	fi
else
	log "[ZERO] removed"
	rm "$FILE"
fi
