#!/bin/bash
#< Remove double-bounces from sendmails mailq

AWK="/bin/awk"
BASENAME="/bin/basename"
ECHO="/bin/echo"
ID="/usr/bin/id"
MAILQ="/usr/bin/mailq"
QTOOL="/root/qtool/qtool.pl"
RM="/bin/rm"
SED="/bin/sed"

DBL_BOUNCES=0
NUM_REQUESTS=0
VERBOSE=0

THISPROG=$( ${BASENAME} $0 )

QDIR="/var/spool/mqueue"
TMPDIR="/var/tmp"
TMPFILE="/var/tmp/mailq.out.$$"

function print_error {
   ${ECHO} "Error: $@" >&2
}

function print_usage {
   {
      ${ECHO} "${THISPROG} [-dhnv]"
      ${ECHO} "       -d   Remove double bounces"
      ${ECHO} "       -h   Display this help message"
      ${ECHO} "       -n   Display number of requests in queue"
      ${ECHO} "       -v   Display verbose output"
   } >&2
}

function cleanup {
   (( VERBOSE )) && ${ECHO} "--> Removing temporary file [${TMPFILE}]"
   ${RM} -f ${TMPFILE}
}

trap 'cleanup; exit 1' 1 2 3 15

function check_root {
   MYUID=$( ${ID} -un )
   if [ "${MYUID}" = "root" ]; then
      return 0
   else
      return 1
   fi
}

function create_tmp_file {
   (( VERBOSE )) && ${ECHO} "--> Creating temporary file [${TMPFILE}]"
   ${MAILQ} > ${TMPFILE}
}

function remove_dbl_bounces {
   ${AWK} '$7 ~ /MAILER-DAEMON/ {
      sub( /\*/, "", $1 )
      print $1
   }' ${TMPFILE} | while read MAILQ_ID; do
      (( VERBOSE )) && ${ECHO} "--> Deleting message ID [${MAILQ_ID}] from [${QDIR}]"
      (( VERBOSE )) && {
         ${QTOOL} -d ${QDIR}/${MAILQ_ID}
      } || {
         ${QTOOL} -d ${QDIR}/${MAILQ_ID} >/dev/null 2>&1
      }
   done
}

function show_num_requests {
   NUM=$( sed -n '1p' ${TMPFILE} | ${SED} 's/.*(\([0-9][0-9]*\) requests.*/\1/' )
   ${ECHO} "--> There are [${NUM}] requests in [${QDIR}]"
}

check_root
if [ "$?" -ne "0" ]; then
   print_error "You must be root to run this script"
   exit 1
fi

OPT_USED=0

while getopts ":hdnv" OPTION; do
   case ${OPTION} in
      "h") print_usage && exit 0 ;;
      "d") DBL_BOUNCES=1         
           (( OPT_USED = OPT_USED + 1 ))
                                 ;;
      "n") NUM_REQUESTS=1       
           (( OPT_USED = OPT_USED + 1 ))
                                 ;;
      "v") VERBOSE=1             ;;
      *  ) print_usage && exit 1 ;;
   esac
done

shift $(( ${OPTIND} -1 ))

if [ "${OPT_USED}" -eq "0" ]; then
   print_error "At least one option should be specified"
   exit 1
fi

create_tmp_file

if [ "${NUM_REQUESTS}" -ne "0" ]; then
   show_num_requests
fi
if [ "${DBL_BOUNCES}" -ne "0" ]; then
   remove_dbl_bounces
fi

cleanup

exit 0