#!/bin/sh
#
# mim - open up Mutt to a new message starting with input
#
# Usage:
#      mim file1 [file2 ...]
#      curl http://example.net/ | mim
#
# Note: the author wrote it so that he could use ! and :! commands in Vim with
# it, to email sections of buffers to people conveniently.

self=mim

# create a temporary directory with name in $td,
# and handle POSIX-ish traps to remove it when the script exits.
td=
cleanup() {
  [ -n "${td}" ] && rm -fr -- "${td}"
  if [ "$1" != EXIT ]; then
    trap - "$1"
    kill "-$1" "$$"
  fi
}
for sig in EXIT HUP INT TERM; do
  # shellcheck disable=SC2064
  trap "cleanup $sig" "$sig"
done
td=$(mktd "${self}") || exit

# Direct all input (stdin and files) into a tempfile
tf=$td/out
cat -- "${@:--}" > "$tf" || exit

# Run Mutt on the tempfile, showing it the TTY for its input
mutt -i "$tf" < /dev/tty
