#!/bin/bash
# vim: shiftwidth=4 tabstop=4 expandtab

LIB_DIR="$( realpath "$( dirname "$( realpath "$0" )" )/../lib/ee-postfix-tools" )"
if [[ -e "$LIB_DIR/common" ]]; then
    # shellcheck source=/dev/null
    source "$LIB_DIR/common"
else
    echo "Failed to load ee-postfix-tools common lib"
    exit 1
fi

# shellcheck disable=SC2034
EXTRA_SHORT_USAGE="[mail ID] [...]"

IDS=()
# shellcheck disable=SC2317,SC2329
function handle_extra_args() {
    IDS=( "$@" )
}
handle_args "$@"
[[ "${#IDS[@]}" -eq 0 ]] && usage

# Create temporary mbox file and make sure to clean it at exit time
TEMPFILE=$( mktemp "$TMP_DIRECTORY_PATH/$( basename "$0" ).XXXXXX" )
function clean_exit () {
	rm -f "$TEMPFILE"
}
trap clean_exit EXIT

# Add mmdh header so mutt understand the file as an mmdh mailbox
chmod 0600 "$TEMPFILE"
echo -e "\x01\x01\x01\x01" > "$TEMPFILE"

for ID in "${IDS[@]}"; do
	{
		JUST_TRY=0 run_postfix_command postcat -qbh "$ID";
		echo -e "\x01\x01\x01\x01";
		echo -e "\x01\x01\x01\x01";
	} >> "$TEMPFILE"
done

mutt -R -m mbox -f "$TEMPFILE"
