#!/bin/bash

source ~/.gamerc

[ "$2" == "" ] && exec echo "Usage: $0 <Date from(YYYYmmdd)> <Date to(YYYYmmdd)>"

DATE_FROM="$1"
DATE_TO="$2"
TOTAL_DAYS="$(( ($(date -d "$DATE_TO 00:00:00" +%s) - $(date -d "$DATE_FROM 00:00:00" +%s)) / 86400))"

(
    echo -n ",Base"
    for((DAY=1;DAY<=$TOTAL_DAYS;DAY++));do
        echo -n ",D+$DAY"
    done
    echo

    for((DAY=0;DAY<=$TOTAL_DAYS;DAY++));do
        BASE_DATE="$(date -d "$DATE_FROM + $DAY day" +%Y-%m-%d)"
        echo -n "$BASE_DATE,"
        member_db <<< "copy (SELECT count(distinct(mid)) from tb_user where firstlogindate::date between '$BASE_DATE 00:00:00' and '$BASE_DATE 24:00:00') to stdout csv;" | tr -d '\n'
        for((D=1;D<=$(($TOTAL_DAYS-$DAY));D++));do
            D_DATE="$(date -d "$BASE_DATE + $D day" +%Y-%m-%d)"
            echo -n ,
#            member_db <<< "copy (select count(distinct(mid)) from game_log where mid in (select distinct(mid) from game_log where logindate between '$BASE_DATE 00:00:00' and '$BASE_DATE 24:00:00') and logindate between '$D_DATE 00:00:00' and '$D_DATE 24:00:00') to stdout csv;" | tr -d '\n'
#            member_db <<< "copy (SELECT count(*) from tb_user where firstlogindate::date between '$BASE_DATE 00:00:00' and '$BASE_DATE 24:00:00' and mid in (select mid from game_log where logindate between '$D_DATE 00:00:00' and '$D_DATE 24:00:00')) to stdout csv;" | tr -d '\n'
            member_db <<< "copy ( select count(distinct(mid)) from game_log where logindate between '$D_DATE 00:00:00' and '$D_DATE 24:00:00' and mid in (select distinct(mid) from tb_user where firstlogindate::date between '$BASE_DATE 00:00:00' and '$BASE_DATE 24:00:00' ) ) to stdout csv;" | tr -d '\n'
#            PGPASSWORD="vpjkkgdiupo2012" psql -U spiritking -h 192.168.33.193 AccountInfo <<< "copy (SELECT count(*) from accountinfo where firstlogindate::date between '$BASE_DATE 00:00:00' and '$BASE_DATE 24:00:00' and acc_name in (select mid acc_name from game_log where logindate between '$D_DATE 00:00:00' and '$D_DATE 24:00:00')) to stdout csv;" | tr -d '\n'
            #echo -n ,$D_DATE
        done
        echo
    done
) \
| awk -F, '
    {
        for(i=1;i<=NF;i++){
            arr[NR,i]=$i;
            if(big <= NF) big=NF;
        }
    } END {
        for(i=1;i<=big;i++){
            for(j=1;j<=NR;j++){
                printf("%s,",arr[j,i]);
            }
            printf("\n");
        }
    }' \
| sed 's/,\+$//g'
