#!/bin/bash

req_progs="tempfile formail unix2dos dos2unix file grep awk printline"
req_progs_explanation='
awk is needed to compute size difference between orig and new
printline is needed to count lines ending in LF and CRLF
file is used to detect mail files and whether or not it is LF or CRLF
unix2dos and dos2unix are used to convert back and forth so formail works as expected
'

for i in $req_progs; do
	if ! which $i 2>&1 >/dev/null; then
		echo "Missing required program $i"
		exit 1
	fi
done

if [[ "$1" == "" ]]; then
	echo "Usage: $0 email-folder"
	exit 1
fi

if ! [[ -f "$1" ]] || ! [[ -x "$1" ]]; then
	echo "$1 is not a regular file"
	exit 1
fi

if ! file "$1" | grep 'mail text' 2>&1 >/dev/null; then
	if ! grep -q '^From ' "$1" 2>&1 >/dev/null; then
		echo "$1 is not an email folder file"
		exit 1
	else
#		lfs_count=`printline -u -d '\n' < "$1"`
#		crlfs_count=`printline -u -d'\r\n' < "$1"`
		crlfs_count=`printline -d'\r' -p'\nFrom ' < "$1" | printline -u`
		if (( "$crlfs_count" > "1" )); then
			dos_file=true
		fi
#		if [[ "$lfs_count" == "$crlfs_count" ]] || (( $lfs_count - 1 == $crlfs_count )) ; then

#		fi
	fi
elif file "$1" | grep 'CRLF' 2>&1 >/dev/null; then
	dos_file=true
fi

tempfile1=`tempfile`
if [[ "$?" != "0" ]]; then
	echo "could not create tempfile"
	exit 1
fi
tempfile2=`tempfile`
if [[ "$?" != "0" ]]; then
	echo "could not create tempfile"
	rm "$tempfile1"
	exit 1
fi
tempfile3=`tempfile`
if [[ "$?" != "0" ]]; then
	echo "could not create tempfile"
	rm "$tempfile1"
	rm "$tempfile2"
	exit 1
fi

if [[ "$dos_file" == "true" ]]; then
	
	dos2unix < "$1" > "$tempfile3" 
	size_orig=`ls -la "$tempfile3" | awk '{ print $5 }'`
	formail -D 999999999 "$tempfile1" -s < "$tempfile3" > "$tempfile2"
else
	size_orig=`ls -la "$1" | awk '{ print $5 }'`
	formail -D 999999999 "$tempfile1" -s < "$1" > "$tempfile2"
fi

if [[ "$?" != "0" ]]; then
	echo "operation not successfull"
	rm "$tempfile1"
	rm "$tempfile2"
	exit 1
fi

size_new=`ls -la "$tempfile2" | awk '{ print $5 }'`

if [[ "$size_orig" -gt "$size_new" ]]; then 
	if [[ "$dos_file" == "true" ]]; then
		unix2dos "$tempfile2"
	fi
	mv "$tempfile2" "$1"
else
	rm "$tempfile2"
fi

rm "$tempfile1"
rm "$tempfile3"

