#!/bin/bash
#===============================================================================
#
#          FILE: gmtool_add_account
#
#         USAGE: gmtool_add_account <GMTool account name> <password> <privilege> <TEST|LIVE>
#
#   DESCRIPTION: Add GMTool account to the Account Database
#
#       OPTIONS: <GMTool account name> <password> <privilege> <TEST|LIVE>
#
#  REQUIREMENTS:
#
#         NOTES:
#
#          BUGS:  ---
#        AUTHOR: rickz (Rick Zhang), xlrickz@gmail.com
#       COMPANY: X-LEGEND Entertainment Corp.
#       CREATED: Fri Oct 14 05:51:36 EDT 2011
#      REVISION: 2.0
#
#          TODO:
#
#===============================================================================

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

source ~/.gamerc

[ "$3" == "" ] && exec echo "Usage: $0 <GMTool account name> <password> <priviledge> <TEST|LIVE>"

#gm_tool_accounts
#id | account_name | password | privilege

echo -n "Account name: "
echo "$1" | colorize cyan

echo -n "Password: "
echo "$2" | colorize cyan

echo -n "Privilege: "
echo "$3" | colorize cyan

echo

if grep -qi "test" <<< "$4" ; then

   echo "select account_name from gm_tool_accounts where account_name = '$1';" \
   | PGPASSWORD="$TEST_SERVER_DB_PASSWORD" psql -h test -t $ACCOUNT_DB_NAME|grep -q "^ $1$" \
   && GMTOOL_ACCOUNT_EXIST=1 || GMTOOL_ACCOUNT_EXIST=0

   if [ "$GMTOOL_ACCOUNT_EXIST" == "0" ] ; then
	echo -n "Adding GMTool account on "
	echo -n "TEST" | colorize green black 
	echo " server ... "
	echo "insert into gm_tool_accounts (id,account_name,password,privilege) values ($RANDOM,'$1','$2',$3);" \
	| PGPASSWORD="$TEST_SERVER_DB_PASSWORD" psql -h test $ACCOUNT_DB_NAME
   else
	echo -n "GMTool account $1 existed, updating GMTool account on "
	echo -n "TEST" | colorize green black 
	echo " server ... "
	echo "update gm_tool_accounts set password = '$2', privilege = $3 where account_name = '$1';" \
	| PGPASSWORD="$TEST_SERVER_DB_PASSWORD" psql -h test $ACCOUNT_DB_NAME
   fi

else

   echo "select account_name from gm_tool_accounts where account_name = '$1';" \
   | PGPASSWORD="$LIVE_SERVER_DB_PASSWORD" psql -h accountdb -t $ACCOUNT_DB_NAME|grep -q "^ $1$" \
   && GMTOOL_ACCOUNT_EXIST=1 || GMTOOL_ACCOUNT_EXIST=0

   if [ "$GMTOOL_ACCOUNT_EXIST" == "0" ] ; then
	echo -n "Adding GMTool account on "
	echo -n "LIVE" | colorize red black 
	echo " server ... "
	echo "insert into gm_tool_accounts (id,account_name,password,privilege) values ($RANDOM,'$1','$2',$3);" \
	| PGPASSWORD="$LIVE_SERVER_DB_PASSWORD" psql -h accountdb $ACCOUNT_DB_NAME
   else
	echo -n "GMTool account $1 existed, updating GMTool account on "
	echo -n "LIVE" | colorize red black 
	echo " server ... "
	echo "update gm_tool_accounts set password = '$2', privilege = $3 where account_name = '$1';" \
	| PGPASSWORD="$LIVE_SERVER_DB_PASSWORD" psql -h accountdb $ACCOUNT_DB_NAME
   fi

fi


