#!/bin/bash
# Written by NONO. http://www.asahi-net.or.jp/~aa4t-nngk/
#
PATH="$PATH:/var/qmail/bin"

# Change these for your environment!
# If you need multiple steps to stop or start qmail,
# you can add STOPCMD[1],[2]...and STARTCMD[1],[2]....
QUEDIR="/var/qmail/queue"
STOPCMD[0]='monit stop qmaild'
STARTCMD[0]='monit start qmaild'
#
#
RMOPT="-iv"

usage() {
  echo "qqclean is a qmail queue manipulation shell-script. It can be 
used to print queued queue number and delete one. It stops 
and restarts qmail deamon for safe queue removal on deletion 
of queues."
  cat <<HELP_MSG
Usage: qqclean -LRBh [-lD] [queue_number]
1st OPTIONs are:
  -h: help (show this message)
  -L: Local queue
  -R: Remote queue
  -B: Bounce queue
2nd OPTIONs are:
  -l: list all (without '-l', only the first found queue will 
      be printed)
  -D: delete a queue (see also 3rd OPTION)
3rd OPTION:
  QUEUE_NUMBER: delete the queue specified by it (should be used 
with '-D'). Without QUEUE_NUMBER, '-D' will delete only the first 
found queue.
example:
  qqclean -R -D 112233
   (this will delete a remote queue whose number is 112233)
  qqclean -L -l (this will print all numbers of local queues)
HELP_MSG
}

case "$1" in
  -L)
    OPT="local"
    ;;
  -R)
    OPT="remote"
    ;;
  -B)
    OPT="bounce"
    ;;
   *)
    usage
    exit 1
esac

if [ `id -u` != 0 ]; then
  echo 'only root can do this !'
  exit 1
fi

MORE=$2
NUM=$3

detect_qnum() {
  qmail-qread | \
    awk -v opt=$OPT -v more=$MORE -v num=$NUM '
      {
        if ( NR%2==1 ) QNUM=$6
        if ( NR%2==0 && $1==opt ) {
          sub(/#/,"",QNUM)
          if ( more == "-D" ) {
            if ( num != "" && num != QNUM ) next
          }
          print QNUM
          if ( more != "-l" ) exit 0
        }
      }
    '
}

QN=`detect_qnum`
if [ -z "${QN}" ]; then
  echo "no queue found"
  exit 1
fi
case $MORE in
  -D)
    COUNT=${#STOPCMD[@]}
    I=0
    while [ ${I} -lt $COUNT ]
    do
      ${STOPCMD[$I]}
      if [ $? != 0 ]; then
        echo "could not stop qmail!"
        exit 1
      fi
      I=`expr $I + 1`
      sleep 1
    done
    QN=${QUEDIR}'/*/*/'${QN}
    rm $RMOPT $QN
    COUNT=${#STARTCMD[@]}
    I=0
    while [ ${I} -lt $COUNT ]
    do
      ${STARTCMD[$I]}
      if [ $? != 0 ]; then
        echo "could not start qmail! You may have to start them manually."
        exit 1
      fi
      I=`expr $I + 1`
      sleep 1
    done
    ;;
   *)
    echo $QN
    ;;
esac

exit 0
