#! /bin/bash

[ -f /etc/afrihostsendspamdisable ] && exit 

PIDS=`pidof $0`
case "$PIDS" in
    *" "*) echo "Already running - PID $PIDS  Exiting now" ; exit;;
esac

if `tty -s` ; then INTERACTIVE=1 ; else INTERACTIVE= ; fi
NICE="nice ionice -c 2 -n 7"
type -p ionice 2>/dev/null ||
NICE="nice "
COUNT=
LOOP=
SENDOUT=
LOAD=30
LOCALONLY=-ql

while getopts "aqrliIc:L:" OPTION ; do
    case $OPTION in
          L)  LOAD=$OPTARG ;;
          q)  SENDOUT=1 ;;
          a)  COUNT=300; LOOP=120 ;;
          c)  COUNT=$OPTARG ;;
          r)  LOCALONLY='' ;;
          l)  LOOP=60 ;;
          i)  INTERACTIVE=1 ;;
          I)  INTERACTIVE=  ;;
          *)  echo "Usage: $0 [-iIl] [-c count]";
              echo "    -i    interactive"
              echo "    -I    non-interactive"
              echo "    -l    loop forever"
              echo "    -r    remote only - don't suppress remote"
              echo "    -L 40 Allow load of 40 before croaking exim .."
              echo "    -c n  spam when the count is over n"
              exit 1 ;;
    esac
done

if [ "$SENDOUT" ] ; then
    #SPOOL="-DSPOOL=/var/spool/exim"
    SPOOL=""
    ARGS=-q
    ARG4=-q
    PROMPT="Press RETURN to flush out mail in the queue"
elif [ -d /var/spool/exim.in ] ; then
    # spambox:
    SPOOL="-DSPOOL=/var/spool/exim.in"
    ARGS=-q
    ARG4=-q
    PROMPT="Press RETURN to flush out mail in the input queue WITHOUT spam scaning"
    NOREVERT=1
else
    # cpanel box:
    #SPOOL="-DSPOOL=/var/spool/exim"
    SPOOL=""
    ARGS=$LOCALONLY
    ARG4=-q
    PROMPT="Press RETURN to do local mail delivery now"

fi

# Check -i
[[ "$INTERACTIVE" ]] && {
    read -t 5 -p "$PROMPT"  || echo -ne '\nGot tired of waiting ...\n' # last chance to abort ...
}

while true; do
    SPAM=1
    # Check -c
    if [ "$COUNT" ] ; then
        QUEUED=`exim $SPOOL -bpc`
        if [ "$QUEUED" -lt "$COUNT" ] ; then 
            echo "$QUEUED messages in $SPOOL, less than -c $COUNT. Not spamming"
            SPAM=
        fi
    fi

    if [ "$SPAM" ] ; then
        echo "`date`: `exim $SPOOL -bpc` messages"
        echo "Starting 3 threads to send mail, 1 remote, max load $LOAD"
        sed -i 's/\(queue_only_load.*=\).*/\1 '$LOAD'.5/;
                s/\(deliver_queue_load_max.*=\).*/\1 '$LOAD'.5/
            ' /etc/exim.conf
        $NICE sendmail $SPOOL $ARGS -v &
        $NICE sendmail $SPOOL $ARGS    2>/dev/null &
        $NICE sendmail $SPOOL $ARGS    2>/dev/null &
        $NICE sendmail $SPOOL $ARG4    2>/dev/null &
        sleep 5
        # Revert to defaults ... kinda -- was 6 and 3
        [ "$NOREVERT" ] || 
        sed -i 's/\(queue_only_load.*=\).*/\1 27.5/;
                s/\(deliver_queue_load_max.*=\).*/\1 23.5/
            ' /etc/exim.conf
        true
        wait
        # Defaults:
        # queue_only_load = 6.5
        # deliver_queue_load_max = 3

        echo "`date`: `exim $SPOOL -bpc` messages"
    fi

    if ! [ $LOOP ] ; then
        break;
    fi
    sleep $LOOP
done

