#!/bin/bash
#===============================================================================
#
#          FILE: gmtool_config_gen
#
#         USAGE: gmtool_config_gen
#
#   DESCRIPTION: Automatically generate setup.xml for GMTool
#
#       OPTIONS: <Player name> <priviledge>
#
#  REQUIREMENTS:
#
#         NOTES:
#
#          BUGS:  ---
#        AUTHOR: rickz (Rick Zhang), xlrickz@gmail.com
#       COMPANY: X-LEGEND Entertainment Corp.
#       CREATED: Sun Jun 19 23:14:44 EDT 2011
#      REVISION: 1.0
#
#          TODO:
#
#===============================================================================

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

source ~/.gamerc

PGPASSWORD="$LIVE_SERVER_DB_PASSWORD"

MAX_WORLDS="$(sed -n '/BELOW/,/ABOVE/p' /etc/hosts|tr ' ' '\n'|grep "GAMEDB[0-9]"|sort -g|wc -l)"

cat << __EOF__
<?xml version="1.0" ?>
<ChannelSetting LogDataLimit="$GM_TOOL_LOG_DATA_LIMIT" />
<Locate country="$COUNTRY_CODE" Path="$GAME_CLIENT_DEFAULT_INSTALL_PATH"/>
<ComboNameSetting ComboFirst="1" />
<ServerInfo>
__EOF__

for SET in $SET_NUMBER_LIST ; do

   echo "   <Set SetID=\"$SET\" SetName=\"$(ssh gamedb$SET "get_world_name $SET")(Set $SET)\">"
   MAX_CHANNELS="$(sed -n '/BELOW/,/ABOVE/p' /etc/hosts|tr ' ' '\n'|grep "WZ$SET[0-9]"|sort -g|wc -l)"

   if [ "$GAME_TYPE" == "GD" ] || [ "$GAME_TYPE" == "FF" ] || [ "$GAME_TYPE" == "AR" ] ; then
	CHANNEL_TO_LIST=$MAX_CHANNELS
   else
	CHANNEL_TO_LIST=$(($MAX_CHANNELS-1))
   fi

        for((CH=$CHANNEL_NUMBER_SEQUENCE_START_WITH;CH<=$CHANNEL_TO_LIST;CH++));do

                CHANNEL_NAME="$(psql -h accountdb --tuples-only $ACCOUNT_DB_NAME <<< "select name from worlds where id=$(get_server_id $SET $CH world);"| grep -v "^$" | sed 's/^ //g')"

                if [ -n "$CHANNEL_NAME" ] ; then

                        echo -n "      <Server ServerID=\"$(get_server_id $SET $CH zone)\" ServerName=\"$CHANNEL_NAME\" "
                        echo "IP=\"$(ssh WZ$(get_wz_num $SET $CH) "another_ip $(print_serverip WZ$(get_wz_num $SET $CH))")\" Port=\"$(ssh WZ$(get_wz_num $SET $CH) "grep GM $WORKING_DIRECTORY/servers*/ZoneServer$(get_wz_num $SET $CH)/setup.ini|sed 's/GMToolPort=//g'")\" />"

                fi

        done
   echo "   </Set>"
done
echo "</ServerInfo>"
