#!/bin/bash -
#===============================================================================
#
#          FILE: SKServer
#
#         USAGE: SKServer <Start/Stop/CheckAlive/CoreBackup> <Server1/ALL> [Server2] ....
#
#		 SKServer <Build/BuildIfNotExist> <SetDir> [Number]
#
#		 SKServer <Build/BuildIfNotExist> ACCOUNTDB
#		 SKServer <Build/BuildIfNotExist> GAMEDB [Set]
#                SKServer <Build/BuildIfNotExist> SOCIETYDB
#
#                SKServer <Build/BuildIfNotExist> <Mission/GameDBServer> [Set]
#                SKServer <Build/BuildIfNotExist> <SatelliteServer> [Set] [SAT Number]
#                SKServer <Build/BuildIfNotExist> <World/Zone> [Set] [Channel]
#                SKServer <Build/BuildIfNotExist> <Login> [Number of Servers]
#                SKServer <Build/BuildIfNotExist> <Ticket/Gateway/HTTPA/AcctDB/GameAgentServer/Society>
#                SKServer <Build/BuildIfNotExist> <CrossRouterServer> [Set]
#                SKServer <Build/BuildIfNotExist> <CentralServer> [Set]
#
#                SKServer LogRotate <Server1> [Server2] ....
#
#
#   DESCRIPTION: This is a drop-in replacement of SKServer with new features:
#                1.Monitor inside(CheckAlive)
#                2.Automatic build the server directory and symbolic link
#                3.CoreBackup inside and run in background
#                4.LogRotate inside
#                5.Using the environment variable $PATH
#                6.Logging
#
#       OPTIONS: Start
#                Stop
#                CheckAlive
#                CoreBackup
#                Build
#                LogRotate
#
#
#  REQUIREMENTS:  ---
#          BUGS:  ---
#         NOTES:  ---
#        AUTHOR: rickz (Rick Zhang), xlrickz@gmail.com
#       COMPANY: X-LEGEND Entertainment Corp.
#       CREATED: Mon Apr 11 10:55:01 CST 2011
#      REVISION: 1.0
#===============================================================================

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

#source ~/.gamerc
#if ! type function_loaded &> /dev/null; then
#	. $HOME/.gamerc
#fi
source ~/.gamerc
source ~/.functions
#echo "TICKETSERVER_PORT => $TICKETSERVER_PORT"
#echo "GATEWAYSERVER_PORT => $GATEWAYSERVER_PORT"
#echo "HTTPAGENT_PORT => $HTTPAGENT_PORT"
#echo "ACCOUNTDBSERVER_PORT => $ACCOUNTDBSERVER_PORT"
#exit
cd "$WORKING_DIRECTORY"

# The customized function file
CUSTFUNC="$(dirname $0)/customized_function"

# Log on begin
TTY="$(awk -F/dev/ '{print $2}' <<< "$SSH_TTY")"
SOURCEIP="$(try_to_get_full_hostname $(awk '{print $1}' <<< "$SSH_CLIENT"))"
LOGIN_USER=$(who -m|awk '{print $1}')
DATE_NOW="$(date +%Y/%m/%dT%H:%M:%S)"
[ "$ACTION" == "" ] && DO="NOTHING-TO-DO" || DO="$(head -c 12 <<< "$ACTION                 ")"
echo -e "$DATE_NOW\tBegin\t$DO\tAns:$ANSWER\tLogin:$LOGIN_USER\tUser:$USER\tTTY:$TTY\tIP:$SOURCEIP\tARGS: $*" >> "$SKSERVER_LOGFILE"

# Detect the ACTION right or not
grep "^[A-Za-z0-9_]* *(" "$0"|awk '{print $1}'|grep -q "^$ACTION$" || ACTION="show_help"
[ "$ACTION" == "" ] && ACTION="show_help"
[ "$ARG2" == "" ] && ACTION="show_help"

#############################
# Built-in script functions #
#############################
show_cmd () {
  for CMD in $(grep -h "^[a-zA-Z0-9_].*().* # " $CUSTFUNC $0|grep -v "##"|awk '{print $1}'|sort|uniq) ; do
          DESCRIPTION="$(grep -h "^$CMD .* # " $CUSTFUNC $0|awk -F"# " '{print $2}')"
          echo -n "$CMD" | colorize cyan black
          echo " -> $DESCRIPTION"
  done
}

show_help () {
  echo $"Usage: $0 <Command> <Server1/All> [Server2] ....

Example:
SKServer <Start/Stop/CheckAlive/CoreBackup> <Server1/ALL> [Server2] ....

SKServer <Build/BuildIfNotExist> <SetDir> [Number]

SKServer <Build/BuildIfNotExist> ACCOUNTDB
SKServer <Build/BuildIfNotExist> GAMEDB [Set]
SKServer <Build/BuildIfNotExist> SOCIETYDB

SKServer <Build/BuildIfNotExist> <Mission/GameDBServer> [Set]
SKServer <Build/BuildIfNotExist> <SatelliteServer> [Set] [SAT Number]
SKServer <Build/BuildIfNotExist> <WorldZone> [Set] [Channel]
SKServer <Build/BuildIfNotExist> <Login> [Number of Servers]
SKServer <Build/BuildIfNotExist> <Ticket/Gateway/HTTPA/AcctDB/GameAgentServer/Society>

SKServer LogRotate <Times to keep> <Server1> [Server2] ....

The flow of Build:
Build
     \_ SetDir
              \_ GAMEDB
              |        \_ Mission/GameDBServer
              |                  \_ SatelliteServer/WorldZone
              |                  \_ CrossRouterServer
              |                  \_ CentralServer
              |
              \_ ACCOUNTDB
              |
              |_ SOCIETYDB
	      |
              \_ Ticket/Gateway/HTTPAgent/AcctDB/GameAgentServer/SocietyServer
              |
              \_ Login

Commands:
$(show_cmd)
"
}

#####################
# Command functions #
#####################
Build () { # Build up the servers

   if [ "$HOST_NAME" == "TEST" -o "$HOST_NAME" == "GOOGLE-SUBMIT" -o "$HOST_NAME" == "APPLE-SUBMIT" -o "$HOST_NAME" == "DATA" -o "$HOST_NAME" == "SUBMIT" -o "$HOST_NAME" == "SUB" -o "$HOST_NAME" == "DLC" -o "$HOST_NAME" == "TIME1" -o "$HOST_NAME" == "MEDIA" -o "$HOST_NAME" == "MERGE" ] ; then

	#[ "$ARG3" == "" ] || SOURCE_TO_BUILD="-$ARG3"
	#ZONE_CATEGORY_NUM=""
	#ZONE_NUM=""
	#SET_NUM="${ZONE_CATEGORY_NUM}${ZONE_NUM}"
	#CH_NUM="$ARG4"
	SOURCE_TO_BUILD="-TEST"
	SET_NUM="$ARG3"
	ADDITIONAL_PARAMS="$ARG4"

	DATABASE_PASSWORD="$TEST_SERVER_DB_PASSWORD"
	GAME_DB="$GAME_DB_NAME$SET_NUM"
	SOCIETY_DB="$SOCIETY_DB_NAME$SET_NUM"
	WORLD_DB="$WORLD_DB_NAME$ADDITIONAL_PARAMS"

	#GAME_DB_IP="127.0.0.1"
	#ACCOUNT_DB_IP="127.0.0.1"
	#SOCIETY_DB_IP="127.0.0.1"
	#WORLD_DB_IP="127.0.0.1"

	#TicketServerIP="127.0.0.1"

	#LoginHttpIP="127.0.0.1"

	#MISSION_IP="127.0.0.1"

	#if [ "$NAT" == "1" ] || [ "$ONLY_ONE_NETWORK_INTERFACE" == "1" ] ; then
	#	WS_INT_IPADDR="$TEST_SERVER_PRIVATE_IP"
	#else
	#        WS_INT_IPADDR="127.0.0.1"
	#fi

	#WS_NUM="$(get_wz_num $SET_NUM $CH_NUM)"
    #WS_EXT_IPADDR="$TEST_SERVER_GLOBAL_IP"

    #SOCIETY_INT_IPADDR="$TEST_SERVER_PRIVATE_IP"
    #SOCIETY_EXT_IPADDR="$TEST_SERVER_GLOBAL_IP"

	GAME_DB_IP="$TEST_SERVER_PRIVATE_IP"
    if [ "$HOST_NAME" == "MERGE" ]; then
        ACCOUNT_DB_IP=$(ssh -o StrictHostKeyChecking=no MERGE "ip -4 addr show | grep -v '127.0.0.1' | grep 'inet ' | head -1 | awk '{print \$2}' | cut -d/ -f1")
    elif [ "$HOST_NAME" == "MERGE-COMMON" -o "$HOST_NAME" == "MERGE-ASIA" -o "$HOST_NAME" == "MERGE_US" -o "$HOST_NAME" == "MERGE-EU" ]; then
        ACCOUNT_DB_IP=$(ssh -o StrictHostKeyChecking=no MERGE_COMMON "ip -4 addr show | grep -v '127.0.0.1' | grep 'inet ' | head -1 | awk '{print \$2}' | cut -d/ -f1")
    else
        ACCOUNT_DB_IP="$TEST_SERVER_PRIVATE_IP"
    fi
	SOCIETY_DB_IP="$TEST_SERVER_PRIVATE_IP"
	WORLD_DB_IP="$TEST_SERVER_PRIVATE_IP"

    if [ "$HOST_NAME" == "MERGE" ]; then
        TicketServerIP=$(ssh -o StrictHostKeyChecking=no MERGE "ip -4 addr show | grep -v '127.0.0.1' | grep 'inet ' | head -1 | awk '{print \$2}' | cut -d/ -f1")
    elif [ "$HOST_NAME" == "MERGE-COMMON" -o "$HOST_NAME" == "MERGE-ASIA" -o "$HOST_NAME" == "MERGE_US" -o "$HOST_NAME" == "MERGE-EU" ]; then
        TicketServerIP=$(ssh -o StrictHostKeyChecking=no MERGE_COMMON "ip -4 addr show | grep -v '127.0.0.1' | grep 'inet ' | head -1 | awk '{print \$2}' | cut -d/ -f1")
    else
        TicketServerIP="$TEST_SERVER_PRIVATE_IP"
    fi

	#LoginHttpIP="$TEST_SERVER_PRIVATE_IP"

	#MISSION_IP="$TEST_SERVER_PRIVATE_IP"

	WS_INT_IPADDR="$TEST_SERVER_PRIVATE_IP"

	WS_NUM="${ADDITIONAL_PARAMS}"
    WS_EXT_IPADDR="$TEST_SERVER_GLOBAL_IP"

    SOCIETY_INT_IPADDR="$TEST_SERVER_PRIVATE_IP"
    SOCIETY_EXT_IPADDR="$TEST_SERVER_GLOBAL_IP"
   else
	#ZONE_CATEGORY_NUM=""
	#ZONE_NUM=""
	#SET_NUM="${ZONE_CATEGORY_NUM}${ZONE_NUM}"
	#CH_NUM="$ARG4"
	SET_NUM="$ARG3"
	ADDITIONAL_PARAMS="$ARG4"

	DATABASE_PASSWORD="$LIVE_SERVER_DB_PASSWORD"
	GAME_DB="$GAME_DB_NAME$SET_NUM"
	SOCIETY_DB="$SOCIETY_DB_NAME$SET_NUM"
	WORLD_DB="$WORLD_DB_NAME$ADDITIONAL_PARAMS"

	GAME_DB_IP="$(print_serverip GAMEDB$SET_NUM)"
	ACCOUNT_DB_IP="$(print_serverip ACCOUNTDB)"
	SOCIETY_DB_IP="$(print_serverip SOCIETYDB$SET_NUM)"
	WORLD_DB_IP="$(print_serverip WORLDDB$ADDITIONAL_PARAMS)"

	TicketServerIP="$(print_serverip TICKET)"

	#LoginHttpIP=$(ssh HTTPA 'echo $(ifconfig -a|awk "/inet / {print \$2}"|grep -v 127.0.0.1|awk "{print \$1}")')

	#MISSION_IP="$(echo $(/sbin/ifconfig ens4 | grep 'inet' | grep -v 'inet6' | awk -F' ' '{print $2}' | awk '{print $1}'))"

	WS_NUM="${ADDITIONAL_PARAMS}"
	WS_INT_IPADDR="$(print_serverip WS$WS_NUM)"
	SOCIETY_INT_IPADDR="$(print_serverip SOCIETYS$SET_NUM)"

	if [ "$NAT" == "1" ] || [ "$ONLY_ONE_NETWORK_INTERFACE" == "1" ] ; then
	    WS_EXT_IPADDR="$(get_nat_ext_ip ${WS_INT_IPADDR})"
	    SOCIETY_EXT_IPADDR="$(get_nat_ext_ip ${SOCIETY_INT_IPADDR})"
	else
	    WS_EXT_IPADDR="$(another_ip ${WS_INT_IPADDR})"
	    SOCIETY_EXT_IPADDR="$(another_ip ${SOCIETY_INT_IPADDR})"
	fi
   fi

   if [ "$ARG2" == "Login" ] ; then
	   LOGIN_ID_NUM="${ADDITIONAL_PARAMS}"
   fi
   if [ "$ARG2" == "Httpa" ] ; then
	   HTTPA_ID_NUM="${ADDITIONAL_PARAMS}"
   fi	 
   if [ "$ARG2" == "WorldHttpa" ] ; then
	   WORLD_HTTPA_ID_NUM="${ADDITIONAL_PARAMS}"
   fi	 
   if [ "$ARG2" == "LWebSocketProxyS" ] ; then
           LWSP_ID_NUM="${ADDITIONAL_PARAMS}"
   fi
   if [ "$ARG2" == "WWebSocketProxyS" ] ; then
           WWSP_ID_NUM="${ADDITIONAL_PARAMS}"
   fi   

   export PGUSER="spiritking"
   export PGPASSWORD="$DATABASE_PASSWORD"
   source ~/.gamerc
   source ~/.functions
   [ "$SERVER_DATA_COMMON_DIRECTORIES" == "" ] && SERVER_DATA_COMMON_DIRECTORIES="bin Data db"


# SetDir
   if [ "$ARG2" == "SetDir" ] ; then
	echo "Build up Set Directory for Set $SET_NUM" | colorize green
	mkdir -p "$WORKING_DIRECTORY/servers$SET_NUM"
	cd "$WORKING_DIRECTORY/servers$SET_NUM"

	for dir in $SERVER_DATA_COMMON_DIRECTORIES ; do
		ln -sf "../common$SOURCE_TO_BUILD/$dir"
	done

	if [ "$MOBILE" == "1" ] ; then
		SR_FILE="s_rootcmds.ini"
	else
		SR_FILE="S_RootCmds.ini"
	fi

	if [ "$HOST_NAME" == "TEST" -o "$HOST_NAME" == "GOOGLE-SUBMIT" -o "$HOST_NAME" == "APPLE-SUBMIT" ] ; then
		ln -sf ~/bin/S_RootCmds.ini_test_$GAME_TYPE_LOWER Data/db/${SR_FILE} 2>&1 > /dev/null
	else
		ln -sf ~/bin/S_RootCmds.ini_live_$GAME_TYPE_LOWER Data/db/${SR_FILE} 2>&1 > /dev/null
	fi

	if [ "$HOST_NAME" == "TEST" -o "$HOST_NAME" == "GOOGLE-SUBMIT" -o "$HOST_NAME" == "APPLE-SUBMIT" ] ; then
	    [ -e $WORKING_DIRECTORY/servers$SET_NUM/setup.ini ] \
	    || generate_setup_ini > $WORKING_DIRECTORY/servers$SET_NUM/setup.ini
	else
	    generate_setup_ini > $WORKING_DIRECTORY/servers$SET_NUM/setup.ini
	fi

	[ "$GAME_TYPE" == "N1" -o "$GAME_TYPE" == "H2" ] && ln -sf bin/config.ini

	if ! [ -f $WORKING_DIRECTORY/.min_ports ] ; then
		if [ -f ~/bin/min_ports.$COUNTRY_CODE_LOWER ] ; then
			cat ~/bin/min_ports.$COUNTRY_CODE_LOWER > $WORKING_DIRECTORY/.min_ports
		else
			cat ~/bin/min_ports.default > $WORKING_DIRECTORY/.min_ports
		fi
	fi

	echo "SetDir for Set $SET_NUM built" | colorize green

# GAMEDB
   elif [ "$ARG2" == "GAMEDB" ] ; then
	which psql > /dev/null 2>&1 || exec echo "Error: psql not installed."

	cd servers$SET_NUM

	if ! check_db_exist $GAME_DB ; then
	        cat > db/createdb_${GAME_DB}.sql << __EOF__
CREATE USER spiritking WITH SUPERUSER PASSWORD '$DATABASE_PASSWORD';
ALTER USER spiritking WITH PASSWORD '$DATABASE_PASSWORD';
ALTER USER spiritking SUPERUSER;
CREATE DATABASE "$GAME_DB" ENCODING 'SQL_ASCII' template=template0;
__EOF__
	        psql -U postgres < db/createdb_${GAME_DB}.sql
		psql -U postgres $GAME_DB <<< "CREATE OR REPLACE LANGUAGE plpgsql;"
		if [ "$GAME_TYPE" == "N1" ] || [ "$GAME_TYPE" == "H2" ] ; then
	        	psql $GAME_DB postgres < db/game_schema
		else
	        	psql $GAME_DB postgres < db/sk_schema
		fi

                [ "$(psql -U postgres $GAME_DB <<< "copy (select * from configuration) to stdout csv;" | wc -l)" == "0" ] \
                && echo "INSERT INTO configuration VALUES (1105251799, '0', 0);" | psql -U postgres $GAME_DB

	        cd db
		if [ "$GAME_TYPE" == "N1" ] || [ "$GAME_TYPE" == "H2" ] ; then
	        	perl db_game_alter :$GAME_DB
		else
	        	perl dbalter :$GAME_DB
		fi

	        cd -
		[ -e ~/bin/createdb_post_GAME_DB-$GAME_TYPE_LOWER-$COUNTRY_CODE_LOWER.sql ] \
		&& psql $GAME_DB postgres < ~/bin/createdb_post_GAME_DB-$GAME_TYPE_LOWER-$COUNTRY_CODE_LOWER.sql
    else
                echo "Warning: Game database($GAME_DB) already exist." | colorize cyan
	fi


# ACCOUNTDB
   elif [ "$ARG2" == "ACCOUNTDB" ] ; then
	which psql > /dev/null 2>&1 || exec echo "Error: psql not installed."

	cd servers$SET_NUM

        # ACCOUNT DB
	if ! check_db_exist $ACCOUNT_DB_NAME ; then
                # Account DB not exist
	        cat > db/createdb_accountdb.sql << __EOF__
CREATE USER spiritking WITH SUPERUSER PASSWORD '$DATABASE_PASSWORD';
ALTER USER spiritking WITH PASSWORD '$DATABASE_PASSWORD';
ALTER USER spiritking SUPERUSER;
CREATE DATABASE "$ACCOUNT_DB_NAME" ENCODING 'SQL_ASCII' template=template0;
__EOF__
	        psql -U postgres < db/createdb_accountdb.sql
		psql -U postgres $ACCOUNT_DB_NAME <<< "CREATE OR REPLACE LANGUAGE plpgsql;"
		if [ "$GAME_TYPE" == "N1" ] || [ "$GAME_TYPE" == "H2" ] ; then
	        	psql $ACCOUNT_DB_NAME postgres < db/account_schema
		else
	        	psql $ACCOUNT_DB_NAME postgres < db/ska_schema
		fi

	        cd db
	        perl db_account_alter :$ACCOUNT_DB_NAME

	        cd -
		[ -e ~/bin/createdb_post_ACCOUNT_DB-$GAME_TYPE_LOWER-$COUNTRY_CODE_LOWER.sql ] \
		&& psql $ACCOUNT_DB_NAME postgres < ~/bin/createdb_post_ACCOUNT_DB-$GAME_TYPE_LOWER-$COUNTRY_CODE_LOWER.sql
         else
                # Account DB existed
                echo "Warning: Account database($ACCOUNT_DB_NAME) already exist." | colorize cyan

         fi

         # MEMBER DB
         if ! check_db_exist $MEMBER_DB_NAME ; then
                # Member DB not exist
	        cat > db/createdb_memberdb.sql << __EOF__
CREATE USER spiritking WITH SUPERUSER PASSWORD '$DATABASE_PASSWORD';
ALTER USER spiritking WITH PASSWORD '$DATABASE_PASSWORD';
ALTER USER spiritking SUPERUSER;
CREATE DATABASE "$MEMBER_DB_NAME" ENCODING 'SQL_ASCII' template=template0;
__EOF__
	        psql -U postgres < db/createdb_memberdb.sql
	        psql -U postgres $MEMBER_DB_NAME  <<< "CREATE OR REPLACE LANGUAGE plpgsql;"

	        [ -e ~/bin/$GAME_TYPE-Member_schema.sql_$COUNTRY_CODE_LOWER ] \
	        && psql $MEMBER_DB_NAME postgres < ~/bin/$GAME_TYPE-Member_schema.sql_$COUNTRY_CODE_LOWER \
	        || psql $MEMBER_DB_NAME postgres < ~/bin/$GAME_TYPE-Member_schema.sql

	        [ -e ~/bin/createdb_post_MEMBER_DB-$GAME_TYPE_LOWER-$COUNTRY_CODE_LOWER.sql ] \
	        && psql $MEMBER_DB_NAME postgres < ~/bin/createdb_post_MEMBER_DB-$GAME_TYPE_LOWER-$COUNTRY_CODE_LOWER.sql
         else
                # Member DB existed
                echo "Warning: Member database($MEMBER_DB_NAME) already exist." | colorize cyan
         fi

# SOCIETYDB
   elif [ "$ARG2" == "SOCIETYDB" ] ; then
        which psql > /dev/null 2>&1 || exec echo "Error: psql not installed."

        cd servers$SET_NUM

        if ! check_db_exist $SOCIETY_DB ; then
                cat > db/createdb_societydb.sql << __EOF__
CREATE USER spiritking WITH SUPERUSER PASSWORD '$DATABASE_PASSWORD';
ALTER USER spiritking WITH PASSWORD '$DATABASE_PASSWORD';
ALTER USER spiritking SUPERUSER;
CREATE DATABASE "$SOCIETY_DB" ENCODING 'SQL_ASCII' template=template0;
__EOF__
                psql -U postgres < db/createdb_societydb.sql
                psql -U postgres $SOCIETY_DB <<< "CREATE OR REPLACE LANGUAGE plpgsql;"
		if [ "$GAME_TYPE" == "N1" ] || [ "$GAME_TYPE" == "H2" ] ; then
	        	psql $SOCIETY_DB postgres < db/society_schema
		else
	        	psql $SOCIETY_DB postgres < db/sks_schema
		fi

                cd db
                perl db_society_alter :$SOCIETY_DB

	        cd -
                [ -e ~/bin/createdb_post_SOCIETY_DB-$GAME_TYPE_LOWER-$COUNTRY_CODE_LOWER.sql ] \
                && psql $SOCIETY_DB postgres < ~/bin/createdb_post_SOCIETY_DB-$GAME_TYPE_LOWER-$COUNTRY_CODE_LOWER.sql
        else
                # Society DB existed
                echo "Warning: Society database($SOCIETY_DB) already exist." | colorize cyan
        fi


# WORLDDB
   elif [ "$ARG2" == "WORLDDB" ] ; then
        which psql > /dev/null 2>&1 || exec echo "Error: psql not installed."

        cd servers$SET_NUM

        if ! check_db_exist $WORLD_DB ; then
                cat > db/createdb_worlddb.sql << __EOF__
CREATE USER spiritking WITH SUPERUSER PASSWORD '$DATABASE_PASSWORD';
ALTER USER spiritking WITH PASSWORD '$DATABASE_PASSWORD';
ALTER USER spiritking SUPERUSER;
CREATE DATABASE "$WORLD_DB" ENCODING 'SQL_ASCII' template=template0;
__EOF__
                psql -U postgres < db/createdb_worlddb.sql
                psql -U postgres $WORLD_DB <<< "CREATE OR REPLACE LANGUAGE plpgsql;"
                psql $WORLD_DB postgres < db/world_schema

                cd db
                perl db_world_alter :$WORLD_DB

	        cd -
                [ -e ~/bin/createdb_post_WORLD_DB-$GAME_TYPE_LOWER-$COUNTRY_CODE_LOWER.sql ] \
                && psql $WORLD_DB postgres < ~/bin/createdb_post_WORLD_DB-$GAME_TYPE_LOWER-$COUNTRY_CODE_LOWER.sql

		sed -i -E "s/(WorldDBIP=)(.*)/\1$WORLD_DB_IP/" setup.ini
		sed -i -E "s/(WorldDBName=)(.*)/\1$WORLD_DB/" setup.ini
        else
                # World DB existed
                echo "Warning: World database($WORLD_DB) already exist." | colorize cyan
        fi


# MissionServer
   elif [ "$ARG2" == "Mission" ] ; then
	cd servers$SET_NUM

	echo "Build up MissionServer for Set $SET_NUM" | colorize green
	[ -d "MissionServer$SET_NUM" ] && echo "Warning: MissionServer$SET_NUM already exist." | colorize cyan
	mkdir -p "MissionServer$SET_NUM"
	MISSION_PORT="$(get_port Mission)"
	sed -i -E "s/(MissionServerPort=)(.*)/\1$MISSION_PORT/" setup.ini
	echo $MISSION_PORT > MissionServer$SET_NUM/.port
	MISSION_IP="$(get_internal_ip MS ${SET_NUM})"
	cat > MissionServer$SET_NUM/.worlds.sql << __EOS__
INSERT INTO worlds (id, name, int_ip, int_port) values ('-${SET_NUM}', 'MissionServer$SET_NUM', '$MISSION_IP', $MISSION_PORT);
__EOS__
	#psql -h $ACCOUNT_DB_IP $ACCOUNT_DB_NAME spiritking < MissionServer$SET_NUM/.worlds.sql 2>&1 | sed 's/^/worlds: /g'
	ln -sf ../bin/MissionServer MissionServer$SET_NUM/MissionServer$SET_NUM
	MS_CGI_PORT="$(get_port Mission_CGIPort)"
	[ -e MissionServer$SET_NUM/setup.ini ] || cat > MissionServer$SET_NUM/setup.ini << __EOF__
[MissionServer]
MissionServerIP=$MISSION_IP
MissionServerPort=$MISSION_PORT
MissionServerLogLevel=2
MissionServerAssert=0
CGIIP=$MISSION_IP
CGIPort=$MS_CGI_PORT
CGIKey=$CGI_KEY
__EOF__
	echo MissionServer$SET_NUM > MissionServer$SET_NUM/auto_start
	echo "MissionServer for Set $SET_NUM built" | colorize green

# WorldServer
   elif [ "$ARG2" == "WorldS" ] ; then
	cd servers$SET_NUM

	echo "Build up WorldServer for Set $SET_NUM > $WS_NUM" | colorize green
	[ -d "WorldServer$WS_NUM" ] && echo "Warning: WorldServer$WS_NUM already exist." | colorize cyan
	mkdir -p "WorldServer$WS_NUM"

	WORLD_ID="${WS_NUM}"
	WORLD_PORT="$(get_port World)"
	WORLD_INT_PORT="$(get_port World)"
	WORLD_SUB_PORT="$(get_port World)"
	WORLD_HTTP_PORT="$(get_port HTTPAgent)"

	echo $WORLD_PORT > WorldServer$WS_NUM/.port
	echo $WORLD_INT_PORT > WorldServer$WS_NUM/.port_int
	echo $WORLD_SUB_PORT > WorldServer$WS_NUM/.port_sub

	# setup.ini
	cat > WorldServer$WS_NUM/setup.ini << __EOF__
[WorldServer]
WorldDBIP=$WORLD_DB_IP
WorldDBName=$WORLD_DB
WorldDBUser=spiritking
WorldDBPassword=$DATABASE_PASSWORD
ReserveDeletedCharDays=$RESERVE_DELETED_CHAR_DAYS
WorldServerID=$WORLD_ID
ExtWorldServerIP=$WS_EXT_IPADDR
LoadServerStatus=1
WorldServerLogLevel=2
WorldServerAssert=0
SocketBoost=1
WorldUpdatePopulationTime=30
WorldLoginQueueDBIncCount=100
UniqueIDSave=0
WorldHttpServerIP=$WS_INT_IPADDR
WorldHttpServerPort=$WORLD_HTTP_PORT
WebSocket=1
__EOF__

	# worlds
#	cat > WorldServer$WS_NUM/.worlds.sql << __EOS__ | psql -h $ACCOUNT_DB_IP $ACCOUNT_DB_NAME spiritking
#INSERT INTO worlds (id, name, ip, port, int_ip, int_port, sub_port) values ('$WORLD_ID', 's$WORLD_ID', '$WS_EXT_IPADDR', $WORLD_PORT, '$WS_INT_IPADDR', $WORLD_INT_PORT, $WORLD_SUB_PORT);
#__EOS__
	MAXNUM_USER="0"
	ZONE_NUMBER=$(( $WS_NUM / 100 % 10 ))
	GROUP_TEXT="$GROUP_TEXT_PREFIX $ZONE_NUMBER"
	REGION_ID_CONVERT_TO_IDX=$(( $WS_NUM / 1000 - 1 ))
	TIME_ZONE="${WORLDS_TIMEZONE_MAPPING[$REGION_ID_CONVERT_TO_IDX]}"
	SHOW_ORDER=$(( 100 - ($WS_NUM % 100) ))
	cat > WorldServer$WS_NUM/.worlds.sql << __EOS__ | psql -h $ACCOUNT_DB_IP $ACCOUNT_DB_NAME spiritking
INSERT INTO worlds (id, name, ip, port, int_ip, int_port, sub_port, maxnum_user, maxnum_character_number, group_text, time_zone, show_order) values ('$WORLD_ID', 's$WORLD_ID', '$WS_EXT_IPADDR', $WORLD_PORT, '$WS_INT_IPADDR', $WORLD_INT_PORT, $WORLD_SUB_PORT, $MAXNUM_USER, $MAXNUM_CHARACTER_NUMBERS, '$GROUP_TEXT', '$TIME_ZONE', $SHOW_ORDER);
__EOS__
	psql -h $ACCOUNT_DB_IP $ACCOUNT_DB_NAME spiritking < WorldServer$WS_NUM/.worlds.sql 2>&1 | sed 's/^/worlds: /g'

	ln -sf ../bin/WorldServer WorldServer$WS_NUM/WorldServer$WS_NUM
	echo WorldServer$WS_NUM > WorldServer$WS_NUM/auto_start
	echo "WorldServer for Set $SET_NUM > $WS_NUM built" | colorize green

# LoginServer
   elif [ "$ARG2" == "Login" ] ; then
	cd servers$SET_NUM

	echo "Build up LoginServer${LOGIN_ID_NUM}" | colorize green
	[ -d "LoginServer${LOGIN_ID_NUM}" ] && echo "Warning: LoginServer${LOGIN_ID_NUM} already exist." | colorize cyan
	mkdir -p "LoginServer${LOGIN_ID_NUM}"
	LOGIN_PORT="$(get_port Login)"
	LOGIN_IP="$(get_internal_ip LOGIN ${LOGIN_ID_NUM})"
	LOGIN_HTTP_PORT="$(get_port HTTPAgent)"
	echo $LOGIN_PORT > LoginServer${LOGIN_ID_NUM}/.port
	ln -sf ../bin/LoginServer LoginServer${LOGIN_ID_NUM}/LoginServer${LOGIN_ID_NUM}
	cat > LoginServer${LOGIN_ID_NUM}/setup.ini << __EOF__
[LoginServer]
LoginServerPort=$LOGIN_PORT
LoginQueueDBIncCount=50
LoginQueueNormalTicket=5
LoginUpdatePopulationTime=6
LoginQueueUpdateTime=10
LoginHttpServerIP=$LOGIN_IP
LoginHttpServerPort=$LOGIN_HTTP_PORT
WebSocket=1
__EOF__
	echo LoginServer${LOGIN_ID_NUM} > LoginServer${LOGIN_ID_NUM}/auto_start
	echo "LoginServer${LOGIN_ID_NUM} built" | colorize green
	#sed -i -e 's/^Login [0-9]*/Login 6543/g' $WORKING_DIRECTORY/.min_ports

# TicketServer
   elif [ "$ARG2" == "Ticket" ] ; then
	cd servers$SET_NUM

	echo "Build up TicketServer" | colorize green
	[ -d "TicketServer" ] && echo "Warning: TicketServer already exist." | colorize cyan
	mkdir -p TicketServer
	ln -sf ../bin/TicketServer TicketServer/TicketServer
	echo $TICKETSERVER_PORT > TicketServer/.port
	cat > TicketServer/setup.ini << __EOF__
TicketServerIP=$TicketServerIP
TicketServerPort=$TICKETSERVER_PORT
__EOF__
	echo TicketServer > TicketServer/auto_start
	echo "TicketServer built" | colorize green

# Login HTTPAgent/HTTPAServer
   elif [ "$ARG2" == "Httpa" ] ; then
	cd servers$SET_NUM

	echo "Build up HTTPAServer${HTTPA_ID_NUM} for Login ${HTTPA_ID_NUM}" | colorize green
	[ -d "HTTPAServer${HTTPA_ID_NUM}" ] && echo "Warning: HTTPAServer${HTTPA_ID_NUM} already exist." | colorize cyan
	mkdir -p HTTPAServer${HTTPA_ID_NUM}
	ln -sf ../bin/HTTPAgent HTTPAServer${HTTPA_ID_NUM}/HTTPAServer${HTTPA_ID_NUM}
	#LOGIN_IP=$(grep -E " LOGIN${HTTPA_ID_NUM} | LOGIN${HTTPA_ID_NUM}$" /etc/hosts | awk -F" " '{print $1}')
	#LOGIN_HTTP_IP=$(get_login_http_ip ${HTTPA_ID_NUM})
	LOGIN_HTTP_IP="$(get_internal_ip HTTPA ${HTTPA_ID_NUM})"
	LOGIN_HTTP_PORT=$(get_login_http_port ${HTTPA_ID_NUM})
	echo $LOGIN_HTTP_PORT > HTTPAServer${HTTPA_ID_NUM}/.port
	# DO NOT overwrite httpa config
	cat > HTTPAServer${HTTPA_ID_NUM}/setup.ini << __EOF__
[ToLoginServer]
BillingGatewayIP=$LOGIN_HTTP_IP
BillingGatewayPort=$LOGIN_HTTP_PORT
XLAppKey=$SDK_APP_KEY
XLURL=$XLURL
XLSecretkey=abcdefg
EventHttpTime=0.5
IsLocalTest=0
__EOF__
	echo HTTPAServer${HTTPA_ID_NUM} > HTTPAServer${HTTPA_ID_NUM}/auto_start
	echo "HTTPAServer${HTTPA_ID_NUM} built" | colorize green

# World HTTPAgent/HTTPAServer
   elif [ "$ARG2" == "WorldHttpa" ] ; then
	cd servers$SET_NUM

	echo "Build up WHTTPAServer${WORLD_HTTPA_ID_NUM} for World" | colorize green
	[ -d "WHTTPAServer${WORLD_HTTPA_ID_NUM}" ] && echo "Warning: WHTTPAServer${WORLD_HTTPA_ID_NUM} already exist." | colorize cyan
	mkdir -p WHTTPAServer${WORLD_HTTPA_ID_NUM}
	ln -sf ../bin/HTTPAgent WHTTPAServer${WORLD_HTTPA_ID_NUM}/WHTTPAServer${WORLD_HTTPA_ID_NUM}
	WORLD_ID=$(get_world_id WHS${WORLD_HTTPA_ID_NUM})
	WORLD_HTTP_IP=$(get_world_http_ip $SET_NUM ${WORLD_ID})
	WORLD_HTTP_PORT=$(get_world_http_port $SET_NUM ${WORLD_ID})
	echo $WORLD_HTTP_PORT > WHTTPAServer${WORLD_HTTPA_ID_NUM}/.port
	# DO NOT overwrite httpa config
	cat > WHTTPAServer${WORLD_HTTPA_ID_NUM}/setup.ini << __EOF__
[ToWorldServer]
BillingGatewayIP=$WORLD_HTTP_IP
BillingGatewayPort=$WORLD_HTTP_PORT
PushEventTime=50000
PushAsyncCount=2
PushJson=../bin/service-account.json
PushPy=../bin/messaging.py
PushPyCmd=/usr/bin/python3
PushImageURL=

[PhotoUpdate]
PhotoAPIOnline=1
SkipPhotoAPIVerify=1
PUURL=localhost:3031/upload/image
__EOF__
	echo WHTTPAServer${WORLD_HTTPA_ID_NUM} > WHTTPAServer${WORLD_HTTPA_ID_NUM}/auto_start
	echo "WHTTPAServer${WORLD_HTTPA_ID_NUM} built" | colorize green

# SocietyServer
   elif [ "$ARG2" == "SocietyS" ] ; then
        cd servers$SET_NUM

        echo "Build up SocietyServer for Set $SET_NUM" | colorize green
        [ -d "SocietyServer$SET_NUM" ] && echo "Warning: SocietyServer$SET_NUM already exist." | colorize cyan
        mkdir -p SocietyServer$SET_NUM
        ln -sf ../bin/SocietyServer SocietyServer$SET_NUM/SocietyServer$SET_NUM
        # DO NOT overwrite Society config
	SOCIETY_EXT_IPADDR=$(get_public_ip SOCIETYS $SET_NUM)
	SOCIETY_INT_IPADDR=$(get_internal_ip SOCIETYS $SET_NUM)
	SOCIETY_EXT_PORT=$(get_port SocietyS)
	SOCIETY_INT_PORT=$(get_port SocietyS)
	SOCIETY_CGI_PORT="$(get_port Society_CGIPort)"
        [ -e SocietyServer$SET_NUM/setup.ini ] || cat > SocietyServer$SET_NUM/setup.ini << __EOF__
[SocietyServer]
SocietyDBIP=$SOCIETY_DB_IP
SocietyDBName=$SOCIETY_DB
SocietyDBUser=spiritking
SocietyDBPW=$DATABASE_PASSWORD
ExtSocietyServerIP=$SOCIETY_EXT_IPADDR
ExtSocietyServerPort=$SOCIETY_EXT_PORT
IntSocietyServerIP=$SOCIETY_INT_IPADDR
IntSocietyServerPort=$SOCIETY_INT_PORT
SocietyServerLogLevel=4
SocietyServerAssert=0
ReserveDeletedCharDays=$RESERVE_DELETED_CHAR_DAYS
OnlinePlayersMaxCount=10000
PhotoBuffersMaxCount=1000
PhotoBufferSize=2097152
EventHttpTime=0.05
NAT=$NAT
SocietyCGIIP=$SOCIETY_INT_IPADDR
SocietyCGIKey=$CGI_KEY
SocietyCGIPort=$SOCIETY_CGI_PORT

[SDKServerLog]
SocietyServerID=0

[PhotoUpload]
PUURL=localhost:3031/upload/image
PhotoAPIOnline=1
UsingInternalPhotoAPI=0
SkipPhotoAPIVerify=0
#TestingHttpFileServerUrl=192.168.60.223:9696/UPLOAD
__EOF__
	sed -i -E "s/(ExtSocietyServerPort=)(.*)/\1$SOCIETY_EXT_PORT/" setup.ini
	sed -i -E "s/(IntSocietyServerPort=)(.*)/\1$SOCIETY_INT_PORT/" setup.ini
	sed -i -E "s/(ExtSocietyServerIP=)(.*)/\1$SOCIETY_EXT_IPADDR/" setup.ini
	sed -i -E "s/(IntSocietyServerIP=)(.*)/\1$SOCIETY_INT_IPADDR/" setup.ini

        echo SocietyServer$SET_NUM > SocietyServer$SET_NUM/auto_start
        echo "SocietyServer for Set $SET_NUM built" | colorize green

# GameDBServer
   elif [ "$ARG2" == "GameDBS" ] ; then
	cd servers$SET_NUM

	echo "Build up GameDBServer for Set $SET_NUM" | colorize green
	[ -d "GameDBServer$SET_NUM" ] && echo "Warning: GameDBServer$SET_NUM already exist." | colorize cyan
	mkdir -p GameDBServer$SET_NUM
	ln -sf ../bin/GameDBServer GameDBServer$SET_NUM/GameDBServer$SET_NUM
	GAMEDBSERVER_IP="$(get_internal_ip GDS ${SET_NUM})"
	GAMEDBSERVER_PORT="$(get_port GameDBS)"
	sed -i -E "s/(GameDBServerPort=)(.*)/\1$GAMEDBSERVER_PORT/" setup.ini
	echo $GAMEDBSERVER_PORT > GameDBServer$SET_NUM/.port
	[ -e GameDBServer$SET_NUM/setup.ini ] || cat > GameDBServer$SET_NUM/setup.ini << __EOF__
[GameDBServer]
GameDBServerIP=$GAMEDBSERVER_IP
GameDBServerPort=$GAMEDBSERVER_PORT
GameDBServerLogLevel=2
GameDBServerAssert=0
__EOF__

	echo GameDBServer$SET_NUM > GameDBServer$SET_NUM/auto_start
	echo "GameDBServer for Set $SET_NUM built" | colorize green

# RankServer
   elif [ "$ARG2" == "RankS" ] ; then
	cd servers$SET_NUM

	echo "Build up RankServer for Set $SET_NUM" | colorize green
	[ -d "RankServer$SET_NUM" ] && echo "Warning: RankServer$SET_NUM already exist." | colorize cyan
	mkdir -p RankServer$SET_NUM
	ln -sf ../bin/RankServer RankServer$SET_NUM/RankServer$SET_NUM
	RANKSERVER_IP="$(get_internal_ip RANKS ${SET_NUM})"
	RANKSERVER_PORT="$(get_port RankS)"
	sed -i -E "s/(RankServerPort=)(.*)/\1$RANKSERVER_PORT/" setup.ini
	echo $RANKSERVER_PORT > RankServer$SET_NUM/.port
	[ -e RankServer$SET_NUM/setup.ini ] || cat > RankServer$SET_NUM/setup.ini << __EOF__
[RankServer]
RankServerIP=$RANKSERVER_IP
RankServerPort=$RANKSERVER_PORT
RankServerLogLevel=2
__EOF__

	echo RankServer$SET_NUM > RankServer$SET_NUM/auto_start
	echo "RankServer for Set $SET_NUM built" | colorize green

# ChatServer
   elif [ "$ARG2" == "ChatS" ] ; then
	cd servers$SET_NUM

	echo "Build up ChatServer for Set $SET_NUM" | colorize green
	[ -d "ChatServer$SET_NUM" ] && echo "Warning: ChatServer$SET_NUM already exist." | colorize cyan
	mkdir -p ChatServer$SET_NUM
	ln -sf ../bin/ChatServer ChatServer$SET_NUM/ChatServer$SET_NUM
	CHATSERVER_IP="$(get_internal_ip CHATS ${SET_NUM})"
	CHATSERVER_PORT="$(get_port ChatS)"
	sed -i -E "s/(ChatServerPort=)(.*)/\1$CHATSERVER_PORT/" setup.ini
	echo $CHATSERVER_PORT > ChatServer$SET_NUM/.port
	[ -e ChatServer$SET_NUM/setup.ini ] || cat > ChatServer$SET_NUM/setup.ini << __EOF__
[ChatServer]
ChatServerIP=$CHATSERVER_IP
ChatServerPort=$CHATSERVER_PORT
ChannelMsgCheck=1
CMCURL=localhost:3031/spam
EventHttpTime=0.05
ChatServerLogLevel=2
__EOF__

	echo ChatServer$SET_NUM > ChatServer$SET_NUM/auto_start
	echo "ChatServer for Set $SET_NUM built" | colorize green

# AccountDBServer
   elif [ "$ARG2" == "AcctDBS" ] ; then
	cd servers$SET_NUM

	echo "Build up AccountDBServer" | colorize green
	[ -d "AccountDBServer" ] && echo "Warning: AccountDBServer already exist." | colorize cyan
	mkdir -p AccountDBServer
	ln -sf ../bin/GameDBServer AccountDBServer/AccountDBServer
	echo $ACCOUNTDBSERVER_PORT > AccountDBServer/.port
	[ -e AccountDBServer/setup.ini ] || cat > AccountDBServer/setup.ini << __EOF__
[AcctDBServer]
AcctDBServerIP=$ACCOUNT_DB_IP
AcctDBServerPort=$ACCOUNTDBSERVER_PORT
AcctDBServerLogLevel=4
AcctDBServerAssert=1
UseAcct=1
__EOF__

	echo AccountDBServer > AccountDBServer/auto_start
	echo "AccountDBServer built" | colorize green

# LWebSocketProxyServer ( for Login )
   elif [ "$ARG2" == "LWebSocketProxyS" ] ; then
    cd servers$SET_NUM

    echo "Build up LWebSocketProxyServer${LWSP_ID_NUM} for Login" | colorize green
    [ -d "LWebSocketProxyServer${LWSP_ID_NUM}" ] && echo "Warning: LWebSocketProxyServer${LWSP_ID_NUM} already exist." | colorize cyan
    mkdir -p "LWebSocketProxyServer${LWSP_ID_NUM}"
    LWSP_PORT="$(get_port LWebSocketProxyS)"
    echo $LWSP_PORT > LWebSocketProxyServer${LWSP_ID_NUM}/.port
    generate_login_ip_port_data # /tmp/login_ip_port_data
	generate_login_wsp_allow_cidr_data # /tmp/login_wsp_allow_cidr_data
    ln -sf ../bin/WebSocketProxy LWebSocketProxyServer${LWSP_ID_NUM}/LWebSocketProxyServer${LWSP_ID_NUM}
    cat > LWebSocketProxyServer${LWSP_ID_NUM}/setup.ini << __EOF__
[LWebSocketProxy]
# Web Socket Proxy for Login Server
WebSocketProxyServer=0.0.0.0:${LWSP_PORT}

$(cat /tmp/login_ip_port_data)

$(cat /tmp/login_wsp_allow_cidr_data)

SSL_CertPath=../bin/cert/game-server.local.pem
SSL_KeyPath=../bin/cert/game-server.local-key.pem

LogLevel=2
__EOF__
    echo LWebSocketProxyServer${LWSP_ID_NUM} > LWebSocketProxyServer${LWSP_ID_NUM}/auto_start
	#generate_wsp_domain_for_local_machine
    echo "LWebSocketProxyServer${LWSP_ID_NUM} built" | colorize green

# WWebSocketProxyServer ( for World )
   elif [ "$ARG2" == "WWebSocketProxyS" ] ; then
    cd servers$SET_NUM

    echo "Build up WWebSocketProxyServer${WWSP_ID_NUM} for World" | colorize green
    [ -d "WWebSocketProxyServer${WWSP_ID_NUM}" ] && echo "Warning: WWebSocketProxyServer${WWSP_ID_NUM} already exist." | colorize cyan
    mkdir -p WWebSocketProxyServer${WWSP_ID_NUM}
    WORLD_ID=$(get_world_id WWebSocketProxyServer${WWSP_ID_NUM})
    WWSP_PORT=$(get_port WWebSocketProxyS)
    echo $WWSP_PORT > WWebSocketProxyServer${WWSP_ID_NUM}/.port
    generate_login_ip_port_data # /tmp/login_ip_port_data
    ln -sf ../bin/WebSocketProxy WWebSocketProxyServer${WWSP_ID_NUM}/WWebSocketProxyServer${WWSP_ID_NUM}
    cat > WWebSocketProxyServer${WWSP_ID_NUM}/setup.ini << __EOF__
[WWebSocketProxy]
# Web Socket Proxy for World Server
WebSocketProxyServer=0.0.0.0:${WWSP_PORT}

$(cat /tmp/login_ip_port_data)

SSL_CertPath=../bin/cert/game-server.local.pem
SSL_KeyPath=../bin/cert/game-server.local-key.pem

LogLevel=2
__EOF__

    cat > WWebSocketProxyServer${WWSP_ID_NUM}/.worlds.sql << __EOS__ | psql -h $ACCOUNT_DB_IP $ACCOUNT_DB_NAME spiritking
UPDATE worlds SET wsproxy = '${HOSTNAME}.${WEB_SOCKET_PROXY_DOMAIN}:${WWSP_PORT}' WHERE id = $WORLD_ID;
__EOS__
    psql -h $ACCOUNT_DB_IP $ACCOUNT_DB_NAME spiritking < WWebSocketProxyServer${WWSP_ID_NUM}/.worlds.sql 2>&1 | sed 's/^/worlds: /g'

    echo WWebSocketProxyServer${WWSP_ID_NUM} > WWebSocketProxyServer${WWSP_ID_NUM}/auto_start
    #generate_wsp_domain_for_local_machine
    echo "WWebSocketProxyServer${WWSP_ID_NUM} built" | colorize green
	
# Other Server
   elif grep -q "Server" <<< "$ARG2"; then
	SET_NUM="1"

	cd servers$SET_NUM
	echo "Build up $ARG2" | colorize green
	[ -d "$ARG2" ] && echo "Warning: $ARG2 already exist." | colorize cyan
	mkdir -p $ARG2
	ln -sf ../bin/$ARG2 $ARG2/$ARG2
	touch $ARG2/setup.ini
	echo $ARG2 > $ARG2/auto_start
	echo "$ARG2 built" | colorize green

   else
	exec echo "Error: No server type specified" | colorize red
   fi
}

start () { # Start servers
   if grep -i all <<< "$ARG2" > /dev/null ; then
	for server in $(ls servers*/*Server*/auto_start 2> /dev/null|awk -F/ '{print $2}'|egrep "Ticket") ;do
		cd $WORKING_DIRECTORY/servers$(get_set_id $server)
		start_server $server
		sleep 1
	done
	cd $WORKING_DIRECTORY
	sleep 2
	for server in $(ls servers*/*Server*/auto_start 2> /dev/null|awk -F/ '{print $2}'|egrep "AccountDBS") ;do
		cd $WORKING_DIRECTORY/servers$(get_set_id $server)
		start_server $server
		sleep 1
	done
	cd $WORKING_DIRECTORY
	sleep 2
	for server in $(ls servers*/*Server*/auto_start 2> /dev/null|awk -F/ '{print $2}'|egrep "Login") ;do
		cd $WORKING_DIRECTORY/servers$(get_set_id $server)
		start_server $server
		sleep 1
	done
	cd $WORKING_DIRECTORY
	sleep 2
	for server in $(ls servers*/*Server*/auto_start 2> /dev/null|awk -F/ '{print $2}'|grep -v "WHTTPA"|egrep "HTTPA") ;do
		cd $WORKING_DIRECTORY/servers$(get_set_id $server)
		start_server $server
		sleep 1
	done
	cd $WORKING_DIRECTORY
	sleep 2
	for server in $(ls servers*/*Server*/auto_start 2> /dev/null|awk -F/ '{print $2}'|egrep "GameDBS") ;do
		cd $WORKING_DIRECTORY/servers$(get_set_id $server)
		start_server $server
		sleep 1
	done
	cd $WORKING_DIRECTORY
	sleep 2
	for server in $(ls servers*/*Server*/auto_start 2> /dev/null|awk -F/ '{print $2}'|egrep "Mission") ;do
		cd $WORKING_DIRECTORY/servers$(get_set_id $server)
		start_server $server
		sleep 1
	done
	cd $WORKING_DIRECTORY
	sleep 2
	for server in $(ls servers*/*Server*/auto_start 2> /dev/null|awk -F/ '{print $2}'|egrep "World") ;do
		cd $WORKING_DIRECTORY/servers$(get_set_id $server)
		start_server $server
		sleep 1
	done
	cd $WORKING_DIRECTORY
	sleep 2
	for server in $(ls servers*/*Server*/auto_start 2> /dev/null|awk -F/ '{print $2}'|egrep "WHTTPA") ;do
		cd $WORKING_DIRECTORY/servers$(get_set_id $server)
		start_server $server
		sleep 1
	done
	cd $WORKING_DIRECTORY
	sleep 2
	for server in $(ls servers*/*Server*/auto_start 2> /dev/null|awk -F/ '{print $2}'|egrep "LWebSocketProxyServer") ;do
        cd $WORKING_DIRECTORY/servers$(get_set_id $server)
		start_server $server
		sleep 1
	done
	cd $WORKING_DIRECTORY
	sleep 2
	for server in $(ls servers*/*Server*/auto_start 2> /dev/null|awk -F/ '{print $2}'|egrep "WWebSocketProxyServer") ;do
		cd $WORKING_DIRECTORY/servers$(get_set_id $server)
		start_server $server
		sleep 1
	done
	cd $WORKING_DIRECTORY
	sleep 2	
	for server in $(ls servers*/*Server*/auto_start 2> /dev/null|awk -F/ '{print $2}'|egrep -v "Ticket|AccountDBS|Login|HTTPA|GameDBS|Mission|World|WHTTPA|WebSocketProxyS") ;do
		cd $WORKING_DIRECTORY/servers$(get_set_id $server)
		start_server $server
		if [ "${ENABLE_PERF_MONITOR}" -eq "1" ]; then if [[ ${server} =~ ^World.*$ ]]; then open_perf_single ${server}; fi; fi
		#if [[ ${server} =~ ^World.*$ ]]; then set_ws_fix_cpuid; fi
	done
	#set_server_fix_cpuid
	server_cpu_affinity
   else
	for server in $ARG2 $ARG3 $ARG4 $ARG5 $ARG6 $ARG7 $ARG8 $ARG9 $ARG10 $ARG11 $ARG12 $ARG13 $ARG14 $ARG15 $ARG16 $ARG17 $ARG18 $ARG19;do
		start_server $server
		if [ "${ENABLE_PERF_MONITOR}" -eq "1" ]; then if [[ ${server} =~ ^World.*$ ]]; then open_perf_single ${server}; fi; fi
		#if [[ ${server} =~ ^World.*$ ]]; then set_ws_fix_cpuid; fi
	done
	#set_server_fix_cpuid
	server_cpu_affinity
   fi
}

start_if_auto_start_exist () {
   if grep -i all <<< "$ARG2" > /dev/null ; then
	for server in $(ls servers*/*Server*/auto_start 2> /dev/null|awk -F/ '{print $2}'|egrep "Ticket") ;do
		cd $WORKING_DIRECTORY/servers$(get_set_id $server)
		start_server $server
		sleep 1
	done
	cd $WORKING_DIRECTORY
	sleep 2
	for server in $(ls servers*/*Server*/auto_start 2> /dev/null|awk -F/ '{print $2}'|egrep "AccountDBS") ;do
		cd $WORKING_DIRECTORY/servers$(get_set_id $server)
		start_server $server
		sleep 1
	done
	cd $WORKING_DIRECTORY
	sleep 2
	for server in $(ls servers*/*Server*/auto_start 2> /dev/null|awk -F/ '{print $2}'|egrep "Login") ;do
		cd $WORKING_DIRECTORY/servers$(get_set_id $server)
		start_server $server
		sleep 1
	done
	cd $WORKING_DIRECTORY
	sleep 2
	for server in $(ls servers*/*Server*/auto_start 2> /dev/null|awk -F/ '{print $2}'|grep -v "WHTTPA"|egrep "HTTPA") ;do
		cd $WORKING_DIRECTORY/servers$(get_set_id $server)
		start_server $server
		sleep 1
	done
	cd $WORKING_DIRECTORY
	sleep 2
	for server in $(ls servers*/*Server*/auto_start 2> /dev/null|awk -F/ '{print $2}'|egrep "GameDBS") ;do
		cd $WORKING_DIRECTORY/servers$(get_set_id $server)
		start_server $server
		sleep 1
	done
	cd $WORKING_DIRECTORY
	sleep 2
	for server in $(ls servers*/*Server*/auto_start 2> /dev/null|awk -F/ '{print $2}'|egrep "Mission") ;do
		cd $WORKING_DIRECTORY/servers$(get_set_id $server)
		start_server $server
		sleep 1
	done
	cd $WORKING_DIRECTORY
	sleep 2
	for server in $(ls servers*/*Server*/auto_start 2> /dev/null|awk -F/ '{print $2}'|egrep "World") ;do
		cd $WORKING_DIRECTORY/servers$(get_set_id $server)
		start_server $server
		sleep 1
	done
	cd $WORKING_DIRECTORY
	sleep 2
	for server in $(ls servers*/*Server*/auto_start 2> /dev/null|awk -F/ '{print $2}'|egrep "WHTTPA") ;do
		cd $WORKING_DIRECTORY/servers$(get_set_id $server)
		start_server $server
		sleep 1
	done
	cd $WORKING_DIRECTORY
	sleep 2
	for server in $(ls servers*/*Server*/auto_start 2> /dev/null|awk -F/ '{print $2}'|egrep "LWebSocketProxyServer") ;do
		cd $WORKING_DIRECTORY/servers$(get_set_id $server)
		start_server $server
		sleep 1
	done
	cd $WORKING_DIRECTORY
	sleep 2
	for server in $(ls servers*/*Server*/auto_start 2> /dev/null|awk -F/ '{print $2}'|egrep "WWebSocketProxyServer") ;do
		cd $WORKING_DIRECTORY/servers$(get_set_id $server)
		start_server $server
		sleep 1
	done
	cd $WORKING_DIRECTORY
	sleep 2
	for server in $(ls servers*/*Server*/auto_start 2> /dev/null|awk -F/ '{print $2}'|egrep -v "Ticket|AccountDBS|Login|HTTPA|GameDBS|Mission|World|WHTTPA|WebSocketProxyS") ;do
		cd $WORKING_DIRECTORY/servers$(get_set_id $server)
		start_server $server
		if [ "${ENABLE_PERF_MONITOR}" -eq "1" ]; then if [[ ${server} =~ ^World.*$ ]]; then open_perf_single ${server}; fi; fi
		#if [[ ${server} =~ ^World.*$ ]]; then set_ws_fix_cpuid; fi
	done
	#set_server_fix_cpuid
	#change_server_cpu_affinity_current
	server_cpu_affinity
   else
	for server in $ARG2 $ARG3 $ARG4 $ARG5 $ARG6 $ARG7 $ARG8 $ARG9 $ARG10 $ARG11 $ARG12 $ARG13 $ARG14 $ARG15 $ARG16 $ARG17 $ARG18 $ARG19;do
		cd $WORKING_DIRECTORY/servers$(get_set_id $server)/
		[ -e $server/auto_start ] \
		&& start_server $server; if [ "${ENABLE_PERF_MONITOR}" -eq "1" ]; then if [[ ${server} =~ ^World.*$ ]]; then open_perf_single ${server}; fi; fi \
		|| echo "Notice: $server/auto_start does not exist, $server will not start." | colorize cyan black
		#&& start_server $server; if [ "${ENABLE_PERF_MONITOR}" -eq "1" ]; then if [[ ${server} =~ ^World.*$ ]]; then open_perf_single ${server}; fi; fi; if [[ ${server} =~ ^World.*$ ]]; then set_ws_fix_cpuid; fi \
		#|| echo "Notice: $server/auto_start does not exist, $server will not start." | colorize cyan black
	done
	#set_server_fix_cpuid
	#change_server_cpu_affinity_current
	server_cpu_affinity
   fi
}

stop () { # Stop servers
   if grep -i all <<< "$ARG2" > /dev/null ; then

	rm -f $WORKING_DIRECTORY/server*/*Server*/pid

    	for server in $(all_running_servers|grep WWebSocketProxyServer);do
		stop_server $server &
		wait
	done

	for server in $(all_running_servers|grep LWebSocketProxyServer);do
		stop_server $server &
		wait
	done

    	for server in $(all_running_servers|grep ChatServer);do
        	stop_server $server &
        	wait
    	done

    	for server in $(all_running_servers|grep RankServer);do
        	stop_server $server &
        	wait
    	done

    	for server in $(all_running_servers|grep SocietyServer);do
        	stop_server $server &
        	wait
    	done

    	for server in $(all_running_servers|grep WHTTPAServer);do
        	stop_server $server &
        	wait
    	done

	for server in $(all_running_servers|grep WorldServer);do
		stop_server $server &
		if [[ ${server} =~ ^World.*$ ]]; then close_perf_single ${server}; fi
		wait
	done

	for server in $(all_running_servers|grep MissionServer);do
		stop_server $server &
		wait
	done

	for server in $(all_running_servers|grep GameDBServer);do
		stop_server $server &
		wait
	done

	for server in $(all_running_servers|grep HTTPAServer);do
		stop_server $server &
		wait
	done

	for server in $(all_running_servers|grep LoginServer);do
		stop_server $server &
		wait
	done

	for server in $(all_running_servers|grep AccountDBServer);do
		stop_server $server &
		wait
	done

	for server in $(all_running_servers|grep TicketServer);do
		stop_server $server
	done

	for server in $(all_running_servers);do
		stop_server $server
		if [[ ${server} =~ ^World.*$ ]]; then close_perf_single ${server}; fi
	done

   elif grep -i ws <<< "$ARG2" > /dev/null ; then

	rm -f $WORKING_DIRECTORY/server*/WorldServer*/pid

	for server in $(all_running_servers|grep WorldServer);do
		stop_server $server &
		wait
	done

   elif grep -i society <<< "$ARG2" > /dev/null ; then

        rm -f $WORKING_DIRECTORY/server*/SocietyServer*/pid

        for server in $(all_running_servers|grep SocietyServer);do
                stop_server $server &
                wait
        done

   else

	for server in $ARG2 $ARG3 $ARG4 $ARG5 $ARG6 $ARG7 $ARG8 $ARG9 $ARG10 $ARG11 $ARG12 $ARG13 $ARG14 $ARG15 $ARG16 $ARG17 $ARG18 $ARG19;do
		stop_server $server
		if [[ ${server} =~ ^World.*$ ]]; then close_perf_single ${server}; fi
	done

   fi
}

CheckAlive () { # Check the server is alive or not
   if grep -i all <<< "$ARG2" > /dev/null ; then
	[ -f "$WORKING_DIRECTORY/servers1/TicketServer/pid" ] \
	&& check_and_restart TicketServer
	for server in $(servers_should_running|egrep "AccountDBS") ; do
		check_and_restart $server
		sleep 1
	done
	sleep 2
	for server in $(servers_should_running|egrep "Login") ; do
		check_and_restart $server
		sleep 1
	done
	sleep 2
	for server in $(servers_should_running|grep -v "WHTTPA"|egrep "HTTPA") ; do
		check_and_restart $server
		sleep 1
	done
	sleep 2
	for server in $(servers_should_running|egrep "GameDBS") ; do
		check_and_restart $server
		sleep 1
	done
	sleep 2
	for server in $(servers_should_running|egrep "Mission") ; do
		check_and_restart $server
		sleep 1
	done
	sleep 2
	for server in $(servers_should_running|egrep "World") ; do
		check_and_restart $server
		sleep 1
	done
	sleep 2
	for server in $(servers_should_running|egrep "WHTTPA") ; do
		check_and_restart $server
		sleep 1
	done
	sleep 2
    for server in $(servers_should_running|egrep "LWebSocketProxyServer") ; do
		check_and_restart $server
		sleep 1
	done
	sleep 2
	for server in $(servers_should_running|egrep "WWebSocketProxyServer") ; do
		check_and_restart $server
		sleep 1
	done
	sleep 2	
	for server in $(servers_should_running|egrep -v "Ticket|AccountDBS|Login|HTTPA|GameDBS|Mission|World|WHTTPA|WebSocketProxyS") ;do
		check_and_restart $server
		if [[ ${server} =~ ^World.*$ ]]; then close_perf_single ${server}; fi
		if [ "${ENABLE_PERF_MONITOR}" -eq "1" ]; then if [[ ${server} =~ ^World.*$ ]]; then open_perf_single ${server}; fi; fi
		#if [[ ${server} =~ ^World.*$ ]]; then set_ws_fix_cpuid; fi
		sleep 2
	done
	#set_server_fix_cpuid
	#change_server_cpu_affinity_current
	server_cpu_affinity
   else
	for server in $ARG2 $ARG3 $ARG4 $ARG5 $ARG6 $ARG7 $ARG8 $ARG9 $ARG10 $ARG11 $ARG12 $ARG13 $ARG14 $ARG15 $ARG16 $ARG17 $ARG18 $ARG19;do
		check_and_restart $server
		if [[ ${server} =~ ^World.*$ ]]; then close_perf_single ${server}; fi
		if [ "${ENABLE_PERF_MONITOR}" -eq "1" ]; then if [[ ${server} =~ ^World.*$ ]]; then open_perf_single ${server}; fi; fi
		#if [[ ${server} =~ ^World.*$ ]]; then set_ws_fix_cpuid; fi
	done
	#set_server_fix_cpuid
	#change_server_cpu_affinity_current
	server_cpu_affinity
   fi
}

CoreBackup () { # Automatically backup the coredump file
   if grep -i all <<< "$ARG2" > /dev/null ; then
	for server in $(servers_should_running|egrep -v "Ticket") ; do
		core_backup $server
	done
   else
	for server in $ARG2 $ARG3 $ARG4 $ARG5 $ARG6 $ARG7 $ARG8 $ARG9 $ARG10 $ARG11 $ARG12 $ARG13 $ARG14 $ARG15 $ARG16 $ARG17 $ARG18 $ARG19;do
		core_backup $server
	done
   fi
}

LogRotate () { # Log Rotate
   if grep -i all <<< "$ARG2" > /dev/null ; then
	for server in $(ls server*/*Server*/auto_start 2> /dev/null|awk -F/ '{print $2}'|egrep -v "Ticket") ;do
		log_rotate $server
	done
	check_log_files_date
   else
	for server in $ARG2 $ARG3 $ARG4 $ARG5 $ARG6 $ARG7 $ARG8 $ARG9 $ARG10 $ARG11 $ARG12 $ARG13 $ARG14 $ARG15 $ARG16 $ARG17 $ARG18 $ARG19;do
		log_rotate $server
	done
	check_log_files_date
   fi
}

BuildIfNotExist () { # Build up the server if not exist
   [ "$ARG2" == "" ] && exec show_help
   echo "BuildIfNotExist => check_server_exist $ARG2 $ARG3 $ARG4"
   check_server_exist $ARG2 $ARG3 $ARG4 \
   && echo "WARNING: Server($ARG2 $ARG3 $ARG4) already exist, will not build again." | colorize cyan \
   || yes | $0 Build $ARG2 $ARG3 $ARG4
}

demofunc () { ## demo function, doing nothing
   echo "demo, doing nothing"
}


# Read customized function if exist
#[ -f "$CUSTFUNC" ] && source $CUSTFUNC

###################################
# Start run the Command from here #
###################################
if [ "$ACTION" == "show_help" ] ; then
        show_help
else
        if grep -q "$ACTION" <<< "$DONT_ASK_YES_NO" ; then
                $ACTION
        else
                yesno2 $ACTION
        fi
fi


# Log the time on the end
DATE_NOW="$(date +%Y/%m/%dT%H:%M:%S)"
echo -e "$DATE_NOW\t=End=\t$DO\tAns:$ANSWER\tLogin:$LOGIN_USER\tUser:$USER\tTTY:$TTY\tIP:$SOURCEIP\tARGS: $*" >> "$SKSERVER_LOGFILE"
