#!/bin/bash
# Suggestions/corrections please mail to dayid@dayid.org
# An exim "cheater" script
#
# This script simply checks for how many messages are in exim's queue.
# If there are too many (as defined by "$reasonable"),
# AND if load is high (as defined by "$load")  when checked,
# then all queue mail are cleared.
#
# Otherwise, only frozen messages are cleared.
#
# Set reasonable to whatever you think a reasonable queue is for your server.
reasonable="1000"
#
# This script will only clear non-frozen messages if your load is higher than
# this setting, so set it wisely so you don't let exim runaway, but also so
# that it is not too high to still "save" your machine from freezing.
load="4"
#
# Grab numerics
# Amount of mail in queue
bling=`exim -bpc`
# Server load
bam=`cat /proc/loadavg | cut -d "." -f 1`
#
# Now let's do the work!
#
# Make sure there are too many messages first
if [ "$bling" -gt "$reasonable" ]
 then
# If there are too many messages, check the load.
  echo "There are more than $reasonable messages in queue..."
# If load is too high, clear, otherwise, move on.
  if [ "$bam" -gt "$load" ]
   then
    echo "...and load is $bam which is too much over $load - CLEARING QUEUE"
    exiqgrep -i | xargs exim -Mrm
  fi
 else
# If there are not too many messages - or load is not high enough
# clear only frozen messages.
  echo "There are a reasonable amount of messages..."
  echo "Checking for frozen messages..."
# Make sure there are frozen messages before we try to delete them.
  frozen=`exiqgrep -iz | wc | awk {' print $1 '}`
  if [ "$frozen" -gt 0 ]
   then
# If so, attempt a thaw first:
    echo "Attempting to thaw frozen messages..."
    exiqgrep -iz | xargs exim -M
    frozen=`exiqgrep -iz | wc | awk {' print $1 '}`
    if [ "$frozen" -gt 0 ]
     then
      echo "$frozen frozen messages, clearing..."
      exiqgrep -iz | xargs exim -Mrm
     else
      echo "No remaining frozen messages, continuing..."
    fi  
   else
# If not, finish.
    echo "No frozen messages."
  fi
fi
echo "DONE"
echo -n "Eximhelp script last run on: " > /var/log/eximhelp.log
date >> /var/log/eximhelp.log

