#!/bin/bash
#
# (c) 31.7.2018, Dr. Nikolaus Klepp - dr.klepp@gmx.at / office@klepp.biz
#

case "$1" in
	-?|-h|--help)
		echo "Decrypts and sanitizes email comming from stdin."
		echo "usage: $(basename $0) FILENAME"
		exit 1
	;;
esac


INCOMMING=$(mktemp)
TMP=$(mktemp)

cat > $INCOMMING


cat "$INCOMMING" | awk '
BEGIN {
	header=1
	clear=0
	binary=0
	encrypted=0
	subject=""
}

/^[^ ].*/	{
	if (header==1) {
		clear=0
	}
}

/^[sS][uU][bB][jJ][eE][cC][tT]:/ {
	if (header==1) {
		subject=$0
		clear=1
	}
}


# Alle unerwünschten Headereinträge
#/^(X-GMX-Antivirus:|X-GMX-Antispam:|[xX]-[mM][sS]-|x-exchange-|x-forefront-|x-microsoft-|spamdiagnostic)/ {
#	if (header==1) {
#		clear=1
#	}
#}
#/^(X-SG-EID:|X-SG-ID:|X-UI-Filterresults:|X-CNFS-Analysis:|DKIM-Signature:)/ {
#	if (header==1) {
#		clear=1
#	}
#}

		

# Ende des Headers
/^$/ { 
	if (header) {
		header=0
		clear=0
		if (encrypted) {
			print subject " *DECRYPTED*"
			if (0!=system("gpg2 -d \"'$INCOMMING'\" 2>/dev/null")) {
				system("rm \"'$TMP'\"")
			}
			exit 1
		} else {
			print subject
		}
	}
}

/^Content-Type: multipart\/encrypted;$/	{
	if (header) {
		clear=1
		encrypted=1
	}
}



{	
	if (header==1) {
		if (clear==0) {
			print $0
		}
	} else {
		print $0
	}
}

' > $TMP



if [ -f $TMP ]; then
	mv $TMP $INCOMMING
fi

cat $INCOMMING
rm $INCOMMING

