#!/bin/sh
#
# invokes an editor on a temporary file and then immediately executes it

set -o errexit
set -o nounset

EDITOR="${1:-${EDITOR}}"
if [ -z "${EDITOR}" ]; then
  echo "Either pass an editor as an argument or set the EDITOR environment variable" >&2
  exit 1
fi

# trap various signals to remove temporary files on exit.
abort() {
  : "${EXIT_STATUS:=${?}}"
  command -p -- rm -f -r -- "${tmpfile}"*
  trap - EXIT
  exit "${EXIT_STATUS:?}"
}

# tmpfile="$(mktemp "${TMPDIR:-/tmp}"/"$(basename "$0")".XXXXXX)" || tmpfile=/tmp/test$$
tmpfile=$(mktemp)
chmod +x "${tmpfile}"
echo "#!/usr/bin/env sh" >"${tmpfile}"
${EDITOR} "${tmpfile}"
"${tmpfile}"
#rm "${tmpfile}"
{
  trap abort EXIT || :
  trap abort TERM || :
  trap abort INT || :
  trap abort HUP || :
} 2>/dev/null
