#!/bin/sh

## SPDX-FileCopyrightText: 2023 - 2024 Benjamin Grande M. S. <ben.grande.b@gmail.com>
##
## SPDX-License-Identifier: AGPL-3.0-or-later

## Save mail to msmtp queue directory and copy it to sender queue directory.

set -eu

MSMTP_Q="${MSMTP_Q:-"${Q:-"${HOME}/.msmtp.queue"}"}"
if test -z "${MSMTP_Q}" || test ! -d "${MSMTP_Q}"; then
  echo "Queue dir '${MSMTP_Q}' not found" >&2
  exit 1
fi

cd "${MSMTP_Q}" || exit 1

for mail in *; do
  if ! test -e "${mail}"; then
    echo "Mail queue '${MSMTP_Q}' is empty" >&2
    exit 1
  fi
  if ! test -f "${mail}"; then
    echo "Mail '${mail}' is not a regular file" >&2
    exit 1
  fi
done

qrexec-client-vm --filter-escape-chars-stderr -- @default qusal.MailEnqueue \
  /usr/lib/qubes/qfile-agent *

find "${MSMTP_Q}" -type f -delete
