#!/bin/bash
#===============================================================================
#
#          FILE: frauder_finder_by_mail_log
#
#         USAGE: frauder_finder_by_mail_log <Mail Log File>
#
#   DESCRIPTION: Check the mail with gold from Mail log and try to figure out who 
#                is the frauder account
#
#       OPTIONS: <IP>
#
#  REQUIREMENTS:
#
#         NOTES:
#
#          BUGS:  ---
#        AUTHOR: rickz (Rick Zhang), xlrickz@gmail.com
#       COMPANY: X-LEGEND Entertainment Corp.
#       CREATED: Wed Apr 18 13:31:44 KST 2012
#      REVISION: 1.0
#
#          TODO:
#
#===============================================================================

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

source ~/.gamerc

[ "$1" == "" ] && exec echo "Usage: $0 <Mail Log File> [Minimal receive count]"
[ "$2" == "" ] && MIN_MAIL_RECEIVE=50 || MIN_MAIL_RECEIVE="$2"
[ -e $1 ] && LOGFILE="$1" || exec echo "Error: Log file doesn't exist."
LOGFILENAME="$(basename $LOGFILE)"

mkdir -p ~/frauder/

xgrep -h -v ",G:0," $LOGFILE|awk -F, '{print $5}'|sed "s/^RID://g" > ~/frauder/$LOGFILENAME-rid

cat ~/frauder/$LOGFILENAME-rid |sort|uniq -c|sort -gr|awk "\$1>$MIN_MAIL_RECEIVE" > ~/frauder/$LOGFILENAME-most_receivers

echo "select id,given_name,gold,account_name from player_characters where $(for char_id in $(cat ~/frauder/$LOGFILENAME-most_receivers|awk '{print $2}');do echo -n " id = $char_id or " ;done|sed 's/ or $//g') order  by gold desc;"|game_db|grep -v " rows" > ~/frauder/$LOGFILENAME-frauder-from-db

echo -e " Count | CharacterID\n--------------------" > ~/frauder/$LOGFILENAME-left
cat ~/frauder/$LOGFILENAME-most_receivers >> ~/frauder/$LOGFILENAME-left

paste ~/frauder/$LOGFILENAME-left ~/frauder/$LOGFILENAME-frauder-from-db | \
highlight - $(awk '{print $2}' ~/frauder/$LOGFILENAME-most_receivers)
