#!/bin/sh
set -eu

OUTBOX=~/.maildir/.outgoing
DEFAULT_RECORD=~/.maildir/.store
DISCARD_RECORD=~/.maildir/.discard

DONT_STORE=1

LOCKFILE="$OUTBOX/.sendmail.lock"
trap "rm -f $LOCKFILE" 1 2 3 4 5 6 7 8 10 11 12 13 14 15
if ! lockfile -0 -r0 -l 3600 "$LOCKFILE" 2>/dev/null; then
  echo "E: another sendmail process is already running over that Maildir." >&2
  exit 1
fi

find $OUTBOX/cur $OUTBOX/new -type f | while read msg; do
  RECORD="$(sed -rne 's,^X-Record: ,,p' < $msg)"
  case "$RECORD" in [Dd]iscard|[Nn]o|[Nn]one|[Nn]ull) RECORD=$DISCARD_RECORD;; esac
  [ ! -d $RECORD/cur ] && RECORD=$DEFAULT_RECORD
  if sed -e '/^X-Record: /d' $msg | /usr/lib/sendmail -oem -oi -t; then
    if [ ${DONT_STORE:-0} -eq 1 ]; then
      rm "$msg"
    else
      #TODO this is not okay to deliver to Maildirs, really.
      mv "$msg" ${RECORD:-$DEFAULT_RECORD}/cur
    fi
  fi
done

rm -f "$LOCKFILE"
trap - 1 2 3 4 5 6 7 8 10 11 12 13 14 15

exit 0