#!/bin/bash
#
# vmail-stack
# https://git.stack-source.com/msb/vmail-stack
# MIT License Copyright (c) 2021 Matthew Saunders Brown

# load include file
source $(dirname $0)/vmail.sh

help()
{
  thisfilename=$(basename -- "$0")
  echo "$thisfilename"
  echo "Purge exim (SMTP) mail spool."
  echo ""
  echo "usage: $thisfilename [<regex>] [-h]"
  echo ""
  echo "  -h          Print this help."
  echo "  <regex>     Search term to grep through email headers."
  echo "              Any matches will result in that email being purged from the spool."
  echo "              Run without specifying any regex to list out the Subject of all"
  echo "              emails in the spool."
  echo "              Useful to purge spam or undeliverable bounce or other error messages."
  echo ""
  echo "              This script must be run as root or Debian-exim, or a user that can"
  echo "              sudo to the Debian-exim user."
}

vmail:getoptions "$@"

cd /var/spool/exim4/input
# check for regex
if [ -n "$1" ]; then
  # purge email(s)
  grep "$1" *-H |cut -d : -f 1 |sed '/-H$/s/-H$//g' |xargs exim -Mrm
else
  # get list of email Subjects
  grep Subject *-H
  echo
  echo "usage:"
  echo "    $0 \"regex\""
fi