#!/bin/bash
#===============================================================================
#
#          FILE: count_in_game_days
#
#         USAGE: count_in_game_days
#
#   DESCRIPTION: Count how many days the account COUNTINUOUSLY login to the game.
#
#       OPTIONS: N/A
#
#  REQUIREMENTS: 
#
#         NOTES:
#
#          BUGS:  ---
#        AUTHOR: rickz (Rick Zhang), xlrickz@gmail.com
#       COMPANY: X-LEGEND Entertainment Corp.
#       CREATED: Tue Feb 20 13:07:15 KST 2012
#      REVISION: 1.0
#
#          TODO:
#
#===============================================================================

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


[ "$3" == "" ] && exec echo "Count how many days the accounts COUNTINUOUSLY login to the game.

Usage: $0 <From date> <To date> <Days> [Days] [Days] ...
Date format only accept YYYY-mm-dd.
"

source ~/.gamerc

FROM_DATE="$1"
TO_DATE="$2"
DIR_NAME="count_in_game_days_From-$FROM_DATE-To-$TO_DATE"

shift
shift
mkdir -p "$DIR_NAME"

echo "Dumping the data from the database ... " | colorize green black
psql $MEMBER_DB_NAME <<< "copy (select mid,logindate,logoutdate from game_log where (logindate > '$FROM_DATE 00:00:00' and logindate < '$TO_DATE 23:59:59') or (logindate < '$TO_DATE 23:59:59' and logoutdate > '$TO_DATE 23:59:59')) to '/tmp/gamelog.csv' csv;"

cd "$DIR_NAME"
cat /tmp/gamelog.csv > gamelog.csv

echo "Counting days in game ... " | colorize green black
for((day=0;day<=$((($(date -d "$TO_DATE 00:00:00" +%s)-$(date -d "$FROM_DATE 00:00:00" +%s))/86400));day++));do
   DATE="$(date -d "$FROM_DATE + $day day" +%Y-%m-%d)"
   echo -n "$DATE "
   (awk -F, "\$2 >= \"$DATE 00:00:00\" && \$2 <= \"$DATE 23:59:59\" {print \$1}" gamelog.csv
    awk -F, "\$3 >= \"$DATE 00:00:00\" && \$3 <= \"$DATE 23:59:59\" {print \$1}" gamelog.csv
    awk -F, "\$2 <= \"$DATE 00:00:00\" && \$3 >= \"$DATE 23:59:59\" {print \$1}" gamelog.csv
   )|sort|uniq|tee $DATE-in_game|wc -l
done

rm -f in_game_days_*
echo "Counting players ... " | colorize green black
for in_game_days in $*; do
   echo in_game_days: $in_game_days | colorize cyan
   for((day=0;day<=$((($(date -d "$TO_DATE 00:00:00" +%s)-$(date -d "$FROM_DATE 00:00:00" +%s))/86400));day++));do
        DATE="$(date -d "$FROM_DATE + $day day" +%Y-%m-%d)"
        echo From $DATE ... 1>&2
        cat $(ls 20*|grep -A$(($in_game_days-1)) $DATE)|sort|uniq -cd|grep "^ *$in_game_days "
   done | sort | uniq > in_game_days_$in_game_days
done

echo
echo "All data in $PWD" | colorize yellow black

wc -l in_game_days*
