#!/bin/sh
##
# Get last "time period" mail delivery data.
##

##
# one parameter, indicating far into the past you want the logs for, ie
# "1 day" or "1 hour" or "3 days", etc.
##

if [[ "$1" == "" ]] || [[ "$1" == "--help" ]] || [[ "$1" == "-h" ]]; then
  echo "Usage: $0 '<time period>'"
  echo "Examples: "
  echo "$0 '1 hour' "
  echo "$0 '2 days' "
  echo "$0 '15 minutes' "
  echo
  exit 1
fi

DIR="$( cd "$( dirname "$0" )" && pwd )"
LOGDIR=/var/log/send
TAI64N2TAI=/usr/bin/tai64n2tai
MATCHUP=/usr/local/qmailanalog/bin/matchup
AWK=/usr/bin/awk
STRIP_VIRT="${DIR}/../lib/strip-virt.sh"
LOGS_BY_DATE="${DIR}/../lib/get-logs-by-date.sh"

if [[ "$1" == "all" ]]; then
  files=`ls "$LOGDIR"/{"@",cur}*`
else
  period="$1 ago"
  last=`date -d "$period" +%s`
  files=`$LOGS_BY_DATE $last`
fi

if [[ "$files" == "" ]]; then
  echo "Usage: $0 '<time period>'"
  echo "Examples: "
  echo "$0 '1 hour' "
  echo "$0 '2 days' "
  echo "$0 '15 minutes' "
  echo
  exit 1
fi

cat $files \
   | $TAI64N2TAI \
   | $AWK '{ if( $1 > x ) print }' x=$last \
   | $MATCHUP 5> /dev/null \
   | $STRIP_VIRT
