#!/bin/bash
#
# test_postfix
#
# postfix monitoring
# 
###################################################
#
unset MULTIFLAG CONFIG
while getopts c:m? op
 do
  case "$op" in
   c) CONFIG="$OPTARG";;
   m) MULTIFLAG=1;;
   *) echo "usage: `basename $0` [-c config] [-m]"
      exit 1;;
  esac
done
shift $(( $OPTIND -1))
#
if [[ -n "$CONFIG" ]]
 then
  if [[ -f "$CONFIG" ]]
   then
    INSTANCES=`grep '^/' "$CONFIG" | while read f d
      do
       [[ -f $f/main.cf ]] && echo $f
     done`
    if [[ -z "$INSTANCES" ]]
     then
      echo "no instances in $CONFIG configured"
      exit 1
    fi
  else
    echo "config file $CONFIG not found"
    exit 1
  fi
fi
#
if [[ -z "$INSTANCES" ]]
 then
  if [[ -n "$MULTIFLAG" ]]
   then
    INSTANCES="/etc/postfix `postconf | sed -n 's/multi_instance_directories.*= *//p'`"
    if [[ -z "$INSTANCES" ]]
     then
      echo "no instances found"
      exit 1
    fi
  elif [[ ! -d /etc/postfix ]]
   then
    echo "postfix not found"
    exit 0
  else
    INSTANCES='/etc/postfix'
  fi
fi
#
. `dirname $0`/uls_header
#
TMPERR=/dev/shm/postqueue_test_err.$$
#
export PATH=$PATH:/usr/sbin
#
( echo "D;$DT;$ULSHOSTNAME;"
  for i in $INSTANCES
   do
    if [[ $i == /etc/postfix-* ]]
     then
      echo "D;;;Postfix [${i#/etc/postfix-}];Status"
    else
      echo "D;;;Postfix;Status;"
    fi
    if postqueue -c $i -p 2>$TMPERR | awk '
        /^[0-9A-F]/ { if( $1 ~ "[0-9A-F][*]" )
                        active++
                      else
                        deferred++
                    }
        END { print "V;;;;;Active;" active+0 ";#"
              print "V;;;;;Deferred;" deferred+0 ";#"
            }
      '
     then
      if [[ -s "$TMPERR" ]]
       then
        echo "V;;;;;Warning;\"`cat $TMPERR`\";"
      fi
    else
      echo "V;;;;;Error;\"Can't call postqueue
  `cat $TMPERR`\";;"
    fi
    if postfix -c $i status >/dev/null 2>&1
     then
      echo "V;;;;;Status;Running;"
    else
      echo "V;;;;;Status;Not running;"
    fi
  done
) | send_test_tab
rm $TMPERR
