#!/bin/bash
#===============================================================================
#
#          FILE: check_mail_returns
#
#         USAGE: check_mail_returns <rotated log directories>
#
#   DESCRIPTION: Check all the mail returns with same ItemUID
#
#       OPTIONS: <rotated log directories>
#
#  REQUIREMENTS: 
#
#         NOTES: 
#
#          BUGS:  ---
#        AUTHOR: rickz (Rick Zhang), xlrickz@gmail.com
#       COMPANY: X-LEGEND Entertainment Corp.
#       CREATED: Fri Jul 29 01:55:40 EDT 2011
#      REVISION: 1.0
#
#          TODO:
#
#===============================================================================

#set -o nounset                              # Treat unset variables as an error
set -m                                       # Enable job control


[ "$1" == "" ] && exec echo "Usage: check_mail_returns <rotated log directories>"

echo "Counting all mail returns with same UID ... "

IFS='
'

for i in $*;do 
   > $i/multi-ret
   echo $i
   zcat $i/*/Mail*|awk -F, '/Ret,/ {print $2","$5","$6","$15}'|sed 's/^\(..............\)[^,]\+/\1/g'|\
   grep -v "ItemUID:-1"|sort|uniq -cd|sort -g|grep -v ,Return:1|tee $i/multi-ret
done


echo "
###############################################
#     Caculating all mail returns history     #
###############################################
"

for i in $*;do 
   > rets-$i
   for j in `cat $i/multi-ret`;do 
	echo "Checking: "$j | tee -a rets-$i
	zcat $i/*/Mail*|awk -F, '/Ret,/ {print $2","$5","$6","$14","$15","$16}'|\
	sed 's/^\(..............\)[^,]\+/\1/g'| grep $(grep "$j" $i/multi-ret|awk -F, '{print $NF}')|\
	sort -t : -k 7 -g|tee -a rets-$i
   done
   echo
done



