#!/bin/sh
# XXX: This does not handle encryption

# ensure the script ends whenever a command exits with non-zero status
set -e

EMAIL=$(mktemp --suffix=.eml /tmp/XXXXXX)
clean_up() {
    rm -f "$EMAIL"
}

# The account to be used is given as the first argument of this script
account=$1
shift

# ensure clean_up() is called when we exit abnormally
trap 'clean_up' 0 1 2 3 15

# <stdin> of script gets the email, we save temporarily for using it twice
cat >"$EMAIL"

# First try to send the email, as it can cause more problems (i.e., connection)
# `set -e` prevents the mail from entering the database in case this fails.
# msmtp could be called with args from aerc, but --read-recipients already does the job
msmtp --account="$account" --read-recipients --read-envelope-from <"$EMAIL"

# assumes all maildir accounts are configured with a 'sent' directory
# also make sure to tag it correctly
notmuch insert --folder=Sent -inbox -unread +sent <"$EMAIL"