#!/bin/bash
#===============================================================================
#
#          FILE: whowas
#
#         USAGE: whowas <Account Name|Character name|Character ID|Client IP>
#
#   DESCRIPTION: Looking for "Who was the player?" from the databases.
#
#       OPTIONS: <Account Name|Character name|Character ID|Client IP>
#
#  REQUIREMENTS:
#
#         NOTES:
#
#          BUGS:  ---
#        AUTHOR: rickz (Rick Zhang), xlrickz@gmail.com
#       COMPANY: X-LEGEND Entertainment Corp.
#       CREATED: Mon Nov 19 16:18:08 JST 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 <Account Name|Character name|Character ID|Client IP>"

NUM="$(echo $1|tr -d '[[:space:][:punct:][:cntrl:]A-Za-z]')"
[ "$NUM" == "" ] && NUM=0

echo "In the table currentuser($MEMBER_DB_NAME):" | highlight - "" $MEMBER_DB_NAME currentuser
echo "select * from currentuser where strcharid like '$1' or mid like '$1' or char_id::text like '$NUM' or clientip like '$1';" \
| PGPASSWORD="$LIVE_SERVER_DB_PASSWORD" psql -h "accountdb" $MEMBER_DB_NAME | highlight - "$1"

PGPASSWORD="$LIVE_SERVER_DB_PASSWORD" psql -h "accountdb" $MEMBER_DB_NAME <<< "\d game_log" | grep -q gold \
&& GAME_LOG_HAS_COLUMN_GOLD=1 || GAME_LOG_HAS_COLUMN_GOLD=0

SET_NUM="$(get_set $(echo "select serverid from game_log where strcharid like '$1' or mid like '$1' or char_id::text like '$NUM' or clientip like '$1' limit 1" | PGPASSWORD="$LIVE_SERVER_DB_PASSWORD" psql -h "accountdb" $MEMBER_DB_NAME))"

echo "In the table player_characters($GAME_DB_NAME$SET_NUM):" | highlight - "" $GAME_DB_NAME$SET_NUM player_characters
echo "select account_name,given_name,id,level,gold,deleted_time,login_time_limit from player_characters where given_name like '$1' or account_name like '$1' or id::text like '$NUM';" \
| ssh GAMEDB$SET_NUM game_db | highlight - "$1"

echo "In the table game_log($MEMBER_DB_NAME):" | highlight - "" $MEMBER_DB_NAME game_log
if [ "$GAME_LOG_HAS_COLUMN_GOLD" == "1" ] ; then
	echo "select mid,strcharid,char_id,char_level,gold,logindate,logoutdate,nduring,serverid,clientip from game_log \
where strcharid like '$1' or mid like '$1' or char_id::text like '$NUM' or clientip like '$1' order by logindate asc;" 
else
	echo "select mid,strcharid,char_id,char_level,logindate,logoutdate,nduring,serverid,clientip from game_log \
where strcharid like '$1' or mid like '$1' or char_id::text like '$NUM' or clientip like '$1' order by logindate asc;" 
fi | PGPASSWORD="$LIVE_SERVER_DB_PASSWORD" psql -h "accountdb" $MEMBER_DB_NAME | highlight - "$1"


