#!/bin/bash

# Takes three arguments:
# 1. Filename of an email.
# 2. Filename of an information file.
# 3. Filename of a content file.
# 4. Attachment internal date file to write to.
# Email must be of type message/rfc822 or application/vnd.ms-outlook

INPUT="$1"
INFO="$2"
CONTENT="$3"
AIDATE="$4"
TEMPCONTENT=$(mktemp)
TEMPINFO=$(mktemp)
TEMPEML=$(mktemp)

rm -f "${INFO}" "${CONTENT}"

# Are we working on a suitable message?
MIMETYPE=$(file --brief --mime-type "$INPUT")

if test Q"${MIMETYPE}" = Qapplication/vnd.ms-outlook; then
    msgconvert --outfile "${TEMPEML}" "${INPUT}" 2> /dev/null
    if test $? -ne 0; then
	rm -f "${TEMPCONTENT}" "${TEMPINFO}" "${TEMPEML}"
	extract_msg --dump-stdout "${INPUT}"  > "${CONTENT}"
	TEMPEMDIR=$(mktemp -d)
	extract_msg --out "${TEMPEMDIR}" "${INPUT}"
	ls "${TEMPEMDIR}" >> "${INFO}"
	find "${TEMPEMDIR}" -type f | while read n; do
	    bn=$(basename "${n}")
	    if test Q"${bn}" = Qmessage.txt; then
		:
	    else
		file -ib "${n}" | tr -d '\n' >> "${INFO}"
		echo " ${bn}" >> "${INFO}"
	    fi
	done
	rm -rf "${TEMPEMDIR}"
	exit 0
    fi
elif test Q"${MIMETYPE}" = Qmessage/rfc822; then
    cp "${INPUT}" "${TEMPEML}"
else
    echo "Not an email I can process, stopping." >/dev/stderr
fi
EMAIL="${TEMPEML}"
fromdos "${EMAIL}"

# Get the headers.
formail -c -X From: -X Date: -X To: -X Cc: -X Subject: -X Message-ID:  < "${EMAIL}" > "${CONTENT}"
echo "== == == ==" >> "${CONTENT}"

# Write the time in seconds into the data file.
h=$(formail -c -x "Date:" < "${EMAIL}")
date --date="${h}" '+%Y-%m-%d %H:%M:%S'  > "${AIDATE}"

# Get each section and then it's content type.
reformime -i < "${EMAIL}" | grep -F "section: 
content-type: " | while read SNUM; do
    read SCT
    SNUM=$(echo "${SNUM}" | sed 's/^.* //')
    SCT=$(echo "${SCT}" | sed 's/^.* //')
    #echo "got section ${SNUM} with c-t ${SCT}"
    if test Q"${SCT}" = "Qtext/plain"; then
	# We append an echo to the end, knowing that we'll remove all
	# trailing lines.  So this means that if we're missing a final
	# newline, it's restored.
	# Then:
	#   expand tabs
	#   remove trailing whitespace from lines
	#   remove leading and trailing blank lines
	#   remove repeated blanks
	(reformime -e -s "${SNUM}" < "${EMAIL}"; echo) \
	    | fromdos \
	    | expand \
	    | sed 's/  *$//' \
	    | sed -e '/./,$!d' -e :a -e '/^\n*$/{$d;N;ba' -e '}' \
	    | cat --squeeze-blank \
	    > "${TEMPCONTENT}"
	if test -s "${TEMPCONTENT}"; then
	    echo "${SNUM}: text/plain, shown" >> "${INFO}"
	    echo "== ${SNUM} ${SCT} ==" >> "${CONTENT}"
	    cat "${TEMPCONTENT}" >> "${CONTENT}"
	    echo "== == == ==" >> "${CONTENT}"
	else
	    echo "${SNUM}: text/plain, empty" >> "${INFO}"
	fi
    else
	reformime -i -s "${SNUM}" < "${EMAIL}" > "${TEMPINFO}"
	SCN=$(grep content-name "${TEMPINFO}" | sed 's/^content-name: //') 
	echo "${SNUM}: ${SCT} ${SCN}" >> "${INFO}"
    fi
done


rm -f "${TEMPCONTENT}" "${TEMPINFO}" "${TEMPEML}"
exit 0


