#!/bin/bash
#===============================================================================
#
#          FILE: get_log_filter
#
#         USAGE: get_log_filter <From date(YYYYmmdd)> <To Date(YYYYmmdd) or "now"> \
#                 <Server type> <Log file type> [Filter string 1] [Filter string 2] ...
#
#   DESCRIPTION: Directly get the log from local server.
#                Let you select a date range and some keyword filter.
#
#  REQUIREMENTS:
#
#         NOTES:
#
#          BUGS:  ---
#        AUTHOR: rickz (Rick Zhang), xlrickz@gmail.com
#       COMPANY: X-LEGEND Entertainment Corp.
#       CREATED: Mon Mar 12 12:35:52 EDT 2012
#      REVISION: 1.0
#
#          TODO:
#
#===============================================================================

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

[ "$2" == "" ] && exec echo "Usage: get_log_filter <From date(YYYYmmdd)> <To Date(YYYYmmdd) or \"now\"> <Server type> <Log file type> [Filter string 1] [Filter string 2] ..."

# Game servers path
GAME_SERVERS_PATH="$HOME/servers*"

export LC_ALL=C

FROM_DATE="$1"
if grep -q "^[0-9]*$" <<< "$2" ; then
   if [ "$2" -gt "$(date -d "-1 day" +%Y%m%d)" ] ; then
        TO_DATE="99999999"
   else
        TO_DATE="$2"
   fi
else
   TO_DATE="99999999"
fi
SERVER_TYPE="$3"
LOG_FILE_TYPE="$4"
shift 4

cd

(
for FILE in $(ionice -c 3 nice -n 19 find $GAME_SERVERS_PATH/Log/ -type f 2> /dev/null | awk -F/ "\$(NF-2) >= $FROM_DATE && \$(NF-2) <= $TO_DATE  && /$SERVER_TYPE/ && /$LOG_FILE_TYPE[^A-Za-z]/ {print}") /dev/null ; do
   (ionice -c 3 nice -n 19 xcat "$FILE" 2> /dev/null || ionice -c 3 nice -n 19 cat "$FILE")
   # | LC_ALL=C sed ':x;N;$!bx;s/\n/|/g;s/|\([\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x20]\{6,\},\)/\n\1/g'
done
if [ "$TO_DATE" == "99999999" ] ; then
        for FILE in $(find $GAME_SERVERS_PATH/$SERVER_TYPE* -type f 2> /dev/null |awk "/$LOG_FILE_TYPE[^A-Za-z]/ {print}") /dev/null ; do
	        (ionice -c 3 nice -n 19 xcat "$FILE" 2> /dev/null || ionice -c 3 nice -n 19 cat "$FILE")
		# | LC_ALL=C sed ':x;N;$!bx;s/\n/|/g;s/|\([\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x20]\{6,\},\)/\n\1/g'
	done
fi
)\
| eval $(
        [ "$*" == "" ] \
        && echo cat \
        || for i in $* ;do
                echo -n "nice -n 19 egrep '$i'|"
           done|sed 's/|$//g') \
| nice -n 19 sort -t , +1 -2
