#!/bin/bash

# Using sha256 further below means that any duplicates in a mailbox are not exported more than once...
# Should provide more than DATE and IMAP_PATH as available variables, e.g., sender name/address.

DATE=`LANG=en_US date -j -f "%Y-%m-%d %H:%M:%S" "${DATE}" "+%Y-%m-%d"`

EXPORT_PATH=`defaults read com.freron.MailMate MmExportPath 2>/dev/null`
if [ -z "${EXPORT_PATH}" ]; then
	EXPORT_PATH=`"${MM_BUNDLE_SUPPORT}/bin/select_export_folder"`
fi

EXPORT_PATTERN=`defaults read com.freron.MailMate MmExportPattern 2>/dev/null`
if [ -z "${EXPORT_PATTERN}" ]; then
	EXPORT_PATTERN="\${IMAP_PATH}/\${DATE}-\${SHA}.eml"
fi

# Hack to avoid evil use of the pattern within Bash:
# Note: It would be much better if MailMate allowed the path to be provided using the MailMate format strings. That would provide access to all MailMate variables. A SHA variable could be introduced to help with this.
export EXPORT_PATTERN
export SHA
function expand_user_path {
	USER_PATH=$(printf 'print ENV["EXPORT_PATTERN"].gsub(/\$\{([^}]+)\}/) { ENV[$1] }' | ruby)
}

if [ -n "${EXPORT_PATH}" ]; then
	TMPFILE=$(mktemp -t export_eml) || exit 1
	cat > ${TMPFILE}
	SHA256=`cat "${TMPFILE}" | shasum -a 256`
	# We shorten it to 16 chars so not really SHA256 here.
	SHA=${SHA256:0:16}
	expand_user_path
	MM_FILE_PATH="${EXPORT_PATH:-${HOME}/Desktop/MailMate Export}/${USER_PATH}"
	MM_FOLDER_PATH=$(dirname "${MM_FILE_PATH}")
	mkdir -p "${MM_FOLDER_PATH}"
	if [ ! -f "${MM_FILE_PATH}" ]; then
		mv "${TMPFILE}" "${MM_FILE_PATH}"
	elif ! cmp "${TMPFILE}" "${MM_FILE_PATH}" >/dev/null 2>&1; then
		# If a non-identical file exists then save another copy with a full SHA256.
		# This should really never happen, but it might help catch bugs.
		SHA=${SHA256:0:64}
		expand_user_path
		MM_FILE_PATH="${EXPORT_PATH:-${HOME}/Desktop/MailMate Export}/${USER_PATH}"
		mv "${TMPFILE}" "${MM_FILE_PATH}"
	else
		rm "${TMPFILE}"
	fi
fi
