#!/bin/bash
#===============================================================================
#
#          FILE: addgm
#
#         USAGE: addgm <Player name|Character ID> <Privilege> [Set Number]
#
#   DESCRIPTION: Add GM privildge to a player character to the LIVE servers
#
#       OPTIONS: <Player name|Character ID> <Privilege> [Set Number]
#
#  REQUIREMENTS:
#
#         NOTES: 
#
#          BUGS:  ---
#        AUTHOR: rickz (Rick Zhang), xlrickz@gmail.com
#       COMPANY: X-LEGEND Entertainment Corp.
#       CREATED: Mon May 23 02:35:52 EDT 2011
#      REVISION: 2.0
#
#          TODO:
#
#===============================================================================

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


source ~/.gamerc
PGPASSWORD="$LIVE_SERVER_DB_PASSWORD"

[ "$2" == "" ] && exec echo "Usage: $0 <Player name|Character ID> <Privilege> [Set Number]

Privileges: 0 ~ 5
0 <- No privilege
5 <- Max privielge
"

if [ "$2" -gt 5 ] ; then
   ulogger_echo "Error: Privilege number range exceeded.

Privileges: 0 ~ 5
0 <- No privilege
5 <- Max privilege" | colorize red black
   exit
else
   ulogger_echo "Set privilege to $2 for $1 ... " | colorize green black
fi

[ "$3" == "" ] && SETS="$(print_hosts GAMEDB)" || SETS="$(print_hosts GAMEDB|grep "[^0-9]$3$")"
[ "$3" == "" ] || print_hosts GAMEDB|grep -q "[^0-9]$3$" || echo "Error: No such set: $3" | colorize red black

ACTION="update"

if grep -q "^[0-9]\+$" <<< "$1" ; then
   for GAMEDB in $SETS;do
	echo $GAMEDB | colorize yellow black
	echo -n "Character: "
	echo "copy (select id from player_characters where id = $1) to STDOUT csv ;" \
	| psql -h $GAMEDB $GAME_DB_NAME$(get_set $GAMEDB) | grep "^.\+$" \
	   && echo "update player_characters set privilege=$2 where id = $1 ;" \
	      | psql -h $GAMEDB $GAME_DB_NAME$(get_set $GAMEDB) \
	   && ulogger_echo "Set privilege to $2 for $1 on $GAMEDB successfully" | colorize green black \
	   || ulogger_echo "Error: No such character id $1 on $GAMEDB" | colorize red black
   done
else
   for GAMEDB in $SETS;do 
	echo $GAMEDB | colorize yellow black
	echo -n "Character: "
	echo "copy (select id from player_characters where given_name = '$1') to STDOUT csv ;" \
	| psql -h $GAMEDB $GAME_DB_NAME$(get_set $GAMEDB) | grep "^.\+$" \
	   && echo "update player_characters set privilege=$2 where given_name = '$1' ;" \
	      | psql -h $GAMEDB $GAME_DB_NAME$(get_set $GAMEDB) \
	   && ulogger_echo "Set privilege to $2 for $1 on $GAMEDB successfully" | colorize green black \
	   || ulogger_echo "Error: No such character $1 on $GAMEDB" | colorize red black
   done
fi
