#!/bin/bash

show_help() {
cat << EOF
Usage: $0 [-v] [-c] [-a] \\
       [-s sender|-S sender_regex|-r recipient|-R recipient_regex] \\
       [-f show_contents_over_filter|quopri]

-v = verbose mode
-c = clear postfix queue
-a = show auth of sender
EOF
exit 0
}

export SENDER= R_SENDER= RECIPIENT= R_RECIPIENT= ADD_INFO= PIPETO=cat

show_auth_sender() {
  while read qid; do
    sender=`postcat -q $qid | grep "Authenticated sender:"`
    echo "$qid $sender"
  done
}

while [ "$1" ]; do
  if [ "$1" = "-S" ]; then
    shift
    export R_SENDER=$1
  elif [ "$1" = "-s" ]; then
    shift
    export SENDER=$1
  elif [ "$1" = "-r" ]; then
    shift
    export RECIPIENT=$1
  elif [ "$1" = "-R" ]; then
    shift
    export R_RECIPIENT=$1
  elif [ "$1" = "-v" ]; then
    export ADD_INFO=1
  elif [ "$1" = "-c" ]; then
    export PIPETO="postsuper -d -"
  elif [ "$1" = "-a" ]; then
    export PIPETO="show_auth_sender"
  elif [ "$1" = "-f" ]; then
    shift
    export PIPETO="foreachq"
    FILTER_CMD="$1"
  elif [ "$1" = "-h" ]; then
    show_help
  fi
  shift
done

if [ "$PIPETO" != "cat" ]; then
  # do not use verbose mode for pipes and filters
  export ADD_INFO=
fi

# quoted-printable decoder
quopri() {
  if [ -x /usr/bin/python3 ]; then
    python3 -S -c "import sys,codecs;sys.stdout.buffer.write(codecs.decode(sys.stdin.buffer.read(),'quopri'))"
  else
    python2 -S -c "import sys;print sys.stdin.read().decode('quopri')"
  fi
}

foreachq() {
  while read qid; do
    echo "QUEUE ID: $qid"
    postcat -q $qid | $FILTER_CMD
  done
}

mailq | gawk -F '[ *\t]+' '
  BEGIN {
    sender=ENVIRON["SENDER"]
    recipient=ENVIRON["RECIPIENT"]
    r_sender=ENVIRON["R_SENDER"]
    r_recipient=ENVIRON["R_RECIPIENT"]
    no_filter=sender=="" && recipient=="" && r_sender=="" && r_recipient==""
    add_info=ENVIRON["ADD_INFO"]
    last=""
    count=0
  }
  function iprint(id, s, r) {
    if (add_info) {
      printf "%s %s %s\n", id, s, r
    } else {
      print id
    }
    count++
  }
  /^[A-F0-9]/ {
    id=$1
    last_sender=$7
    if (sender==$7) {
      iprint($1, $7)
      last=$1
    } else if (r_sender!="" && match($7, r_sender)) {
      iprint($1, $7)
      last=$1
    } else if (no_filter) {
      iprint($1, $7)
    }
  }
  /^ *\(/ { next }
  /^ / {
    if (last!=id) {
      if (recipient==$2) {
        iprint(id, last_sender, $2)
        last=id
      } else if (r_recipient!="" && match($2, r_recipient)>0) {
        iprint(id, last_sender, $2)
        last=id
      }
    }
  }
  /^-- / {
    if (add_info) {
      printf "-- %d requests\n", count
    }
  }
' | $PIPETO
