#!/bin/bash -
#===============================================================================
#
#          FILE: Ctrl
#
#         USAGE: Ctrl <Command>
#
#   DESCRIPTION: Live Server Controller
#
#       OPTIONS: All options: run this script without any command will show
#
#  REQUIREMENTS: 1. A correct bin/hosts (check "Naming" on wiki)
#                2. A correct bin/rsync.exclude for gmsync
#                3. DBbackup script
#                4. Customized function file(customized_function)
#
#         NOTES: ALL CONFIG INSIDE ~/.gamerc, DO NOT EDIT THIS FILE.
#
#          BUGS:  ---
#        AUTHOR: rickz (Rick Zhang), xlrickz@gmail.com
#       COMPANY: X-LEGEND Entertainment Corp.
#       CREATED: Mon Mar  7 15:30:55 CST 2011
#      REVISION: 2.0
#
#          TODO:
#
#===============================================================================

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

#############################################################################
#                                                                           #
#                           DO NOT EDIT THIS FILE                           #
#                            EDIT ~/.gamerc ONLY                            #
#                                                                           #
#############################################################################
[ -r ~/.gamerc ] && source ~/.gamerc || exec echo "Error: Read ~/.gamerc failed."

# What to do?
ACTION="$1"


# The customized function file
NANO_SECOND="$(date +%N)"
CUSTFUNC="/tmp/customized_function.$NANO_SECOND"
sed  -n '/() { # .* -> .*/,/^}$/p' $(dirname $0)/customized_function > $CUSTFUNC
echo >> $CUSTFUNC
sed  -n '/() {[[:blank:]]*$/,/^}$/p' $(dirname $0)/customized_function >> $CUSTFUNC
echo >> $CUSTFUNC

# 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\tARG:$*" >> "$CTRL_LOGFILE"

ulogger $0 Begin $DO <<< $*

# Detect the ACTION right or not
grep -a -h "^[A-Za-z0-9_-]\+ *(" $CUSTFUNC $0|awk '{print $1}'|grep -a -q "^$ACTION$" || ACTION="show_help"
[ "$ACTION" == "" ] && ACTION="show_help"
DESCRIPTION="$(grep -a "^$ACTION .*" $0 $CUSTFUNC|tail -1|awk -F"# " '{print $2}'|awk -F'..argument' '{print $1}'|tr -d '\n')"

# Ctrl can only run on TEST or CTRL or DATA
if ! egrep -a -q "CTRL|TEST|DATA" <<< "$HOST_NAME" ; then
    ulogger_echo "bash: Ctrl: Permission denied"
    echo "Ctrl can only run on TEST or CTRL" | ulogger
    exit
fi

#############################
# Built-in script functions #
#############################
show_cmd () {
  for CMD_TYPE in $(grep -a "^[A-Za-z0-9_-]\+ (.*) { # .*->" $CUSTFUNC $0|awk -F" # " '{print $2}'|awk -F" -> " '{print $1}'|sort -r|uniq) ; do
	echo "$CMD_TYPE:" | colorize yellow black
	for CMD in $(grep -a -h "^[A-Za-z0-9_-]\+ (.*) { # .*->" $CUSTFUNC $0|grep -a " # $CMD_TYPE -> "|awk '{print $1}'|sort|uniq) ; do
		DESCRIPTION="$(grep -a "^$CMD () { # " $CUSTFUNC $0|head -1|awk -F" # " '{print $2}'|awk -F" -> " '{print $2}')"
		echo -n "$CMD" | colorize cyan black
		echo " -> $DESCRIPTION"
	done
	echo
  done
}

show_help () {
	echo $"Usage: $0 <Command>

Commands:
$(show_cmd)
"
}

IsTodayMDay () {
   DayOfWeek="$(date +%u)"
   for server in $(print_hosts MS) ; do
	let $(ssh $server "cd \$WORKING_DIRECTORY;grep -a -h MaintenanceDate= servers*/setup.ini")
	[ "$MaintenanceDate" != "$DayOfWeek" ] && return 1 || return 0
   done
}

ChangeMDayToToday () { ## Change Maintenance Day to Today
   for server in $(print_hosts MS) ; do
	ssh $server "cd \$WORKING_DIRECTORY;sed -i -e \"s/MaintenanceDate=.*/MaintenanceDate=$(date +%u)/g\" servers*/setup.ini"
   done
}

LIVEBackup () {
   echo -n "Backing up the LIVE server binary to LIVEBackup ... " | colorize magenta
   rm -rf $WORKING_DIRECTORY/common-LIVEBackup/*
   rsync -a GAMEDB1:$WORKING_DIRECTORY/common/. $WORKING_DIRECTORY/common-LIVEBackup/ \
   && echo "OK" | colorize green \
   || echo "FAILED" | colorize red
}

#####################
# Command functions #
#####################
itemmall () { # Maintenance -> Update Promotion Files/Tables from TEST Server to LIVE Server (argument: table names)

   TABLES_TO_APPLY="$ARG2 $ARG3 $ARG4 $ARG5 $ARG6 $ARG7"
   grep -a -q "[A-Za-z]" <<< "$TABLES_TO_APPLY" && PROMOTION_TABLES_APPLY_TO_LIVE="$TABLES_TO_APPLY"

   if [ "$PROMOTION_DATA_APPLY_TO_LIVE_MODE" == "2" ] ; then # 2 = File(on TEST)  -->  Table(on LIVE)
	echo "Mode 2: File(on TEST)  -->  Table(on LIVE)" | colorize green
	for SQL_FILE in $PROMOTION_FILES_APPLY_TO_LIVE ; do
	        echo "File $SQL_FILE(on TEST)  -->  Table(on LIVE):" | colorize yellow
		ssh $TEST_SERVER_USER@TEST "cat ~/common-$SOURCE_OF_SYNC_TO_LIVE/$SQL_FILE" | grep -a -v "GRANT ALL" | sed 's/PUBLIC/PUBLIC\;/g' | ssh accountdb "psql $ACCOUNT_DB_NAME" 2>&1 | uniq -c
	done

   elif [ "$PROMOTION_DATA_APPLY_TO_LIVE_MODE" == "3" ] ; then # 3 = File(on LIVE)  -->  Table(on LIVE)
	echo "Mode 3: File(on LIVE)  -->  Table(on LIVE)" | colorize green
	for SQL_FILE in $PROMOTION_FILES_APPLY_TO_LIVE ; do
		echo "File $SQL_FILE(on LIVE)  -->  Table(on LIVE):" | colorize yellow
		ssh accountdb "cat ~/servers1/$SQL_FILE" | grep -a -v "GRANT ALL" | sed 's/PUBLIC/PUBLIC\;/g' | ssh accountdb "psql $ACCOUNT_DB_NAME" 2>&1 | uniq -c
	done

   else
	echo "Mode 1: Table(on TEST) -->  Table(on LIVE)" | colorize green
	for TABLE in $PROMOTION_TABLES_APPLY_TO_LIVE ; do # 1 = Table(on TEST) -->  Table(on LIVE)
		echo "Syncing table $TABLE(on TEST) -->  Table(on LIVE):" | colorize yellow black
		ssh $TEST_SERVER_USER@TEST pg_dump --clean --attribute-inserts -t $TABLE $ACCOUNT_DB_NAME | grep -a -v "SET lock_timeout" | ssh accountdb "psql $ACCOUNT_DB_NAME" | uniq -c \
		&& echo "Table $TABLE done." | colorize green \
		|| echo "Table $TABLE failed." | colorize red
		online_reload_cgi ${TABLE}
	done
   fi

   #ssh accountdb "psql $ACCOUNT_DB_NAME -c 'SELECT refresh_forever_item()'"  && echo "refresh_forever_item Done."

   echo "
Remember, if you are updating the Promotion Files/Tables on running servers,
You will have to run these GM commands to apply in game:
1. /reload_itemmall_db
2. /rnba
3. /reload_daily_login_reward
4. /reload_playground_db
5. /reload_iap_db" | colorize green
}

synctranslate () { # Maintenance -> Sync translation ONLY to live servers
   sendscript allall <<< "rsync -av --exclude-from=bin/rsync.exclude TEST:common-$SOURCE_OF_SYNC_TO_LIVE/Data/db/[Tt]_* common/Data/db/."
   eval $LIVE_TRANSLATE_CDN_SYNC_CMDLINE

   if [ -e $HOME/ibackup/ibackup.list ] ; then
       grep -a -q "^translate" $HOME/ibackup/ibackup.list \
       || echo -e "translate\t$TRANSLATED_INI_UPLOAD_DIR" >> $HOME/ibackup/ibackup.list
       ssh TEST "ibackup backup translate 'Restore to sync translate only to LIVE at $(date +%Y%m%dT%H%M)' 2>&1" | grep -a -v "Processing changed file "
   fi
}


gmsync_pre () { # Maintenance -> Sync server to live before maintenance (argument: "binary_only")
   DATETIME="$(/bin/date +%Y%m%dT%H%M)"
   [ ! -d "$WORKING_DIRECTORY/live_pre_sync" ] && mkdir -p $WORKING_DIRECTORY/live_pre_sync
   cd $WORKING_DIRECTORY/live_pre_sync
   SERVER_DIFF_FILE="$WORKING_DIRECTORY/live_pre_sync/server_diff.txt.$DATETIME"
   if grep -a -qi "binary_only" <<< "$ALLARGS" ; then
	rsync -i -avn --exclude-from=$WORKING_DIRECTORY/bin/rsync.exclude --out-format="FILE:%n" ~/common-TEST/ CTRL:~/common_pre/ | grep -a "^FILE:" | grep -a -v "/$" | sed 's/^FILE:/\//g' > $SERVER_DIFF_FILE
	#sendscript allall <<< "rsync -av --exclude-from=bin/rsync.exclude $TEST_SERVER_USER@TEST:common-$SOURCE_OF_SYNC_TO_LIVE/bin/. common_pre/bin/"
	for ip in $(cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | egrep -a 'CTRL|GAMEDB|MS|WZ|ACCOUNTDB|LOGIN|ACCTDB|GDS|GAMEAGENT|SAT|GAG|CRS|SOCIETY|CES' | awk -F" " '{print $1}'); do
		echo ${ip} | colorize blue black
		print_servername ${ip} | colorize yellow black
		if grep -a -qi "check" <<< "$ALLARGS" ; then
			ssh ${ip} "source ~/.gamerc; rsync -avz --exclude-from=bin/rsync.exclude $TEST_SERVER_USER@TEST:common-$SOURCE_OF_SYNC_TO_LIVE/bin/. common_pre/bin/"
		else
			ssh ${ip} "source ~/.gamerc; rsync -aHAXxv --numeric-ids --delete --progress --quiet --exclude-from=$WORKING_DIRECTORY/bin/rsync.exclude -e \"ssh -T -o Compression=no -x\" $TEST_SERVER_USER@TEST:$WORKING_DIRECTORY/common-$SOURCE_OF_SYNC_TO_LIVE/bin/. $WORKING_DIRECTORY/common_pre/bin/; sed -i 's/AllGM=1/AllGM=0/' $WORKING_DIRECTORY/common_pre/bin/config.ini" &
		fi
		sleep 1
	done
   else
	rsync -i -avn --exclude-from=$WORKING_DIRECTORY/bin/rsync.exclude --out-format="FILE:%n" ~/common-TEST/ CTRL:~/common_pre/ | grep -a "^FILE:" | grep -a -v "/$" | sed 's/^FILE:/\//g' > $SERVER_DIFF_FILE
	#sendscript allall <<< "rsync -av --exclude-from=bin/rsync.exclude $TEST_SERVER_USER@TEST:common-$SOURCE_OF_SYNC_TO_LIVE/. common_pre/"
	GAME_TYPE_LOWER=$(echo ${GAME_TYPE} | tr '[:upper:]' '[:lower:]')
	for ip in $(cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | egrep -a 'CTRL|GAMEDB|MS|WZ|ACCOUNTDB|LOGIN|ACCTDB|GDS|GAMEAGENT|SAT|GAG|CRS|SOCIETY|CES' | awk -F" " '{print $1}'); do
		echo ${ip} | colorize blue black
		print_servername ${ip} | colorize yellow black
		if grep -a -qi "check" <<< "$ALLARGS" ; then
			ssh ${ip} "source ~/.gamerc; rsync -avz --exclude-from=bin/rsync.exclude $TEST_SERVER_USER@TEST:common-$SOURCE_OF_SYNC_TO_LIVE/. common_pre/"
		else
			ssh ${ip} "source ~/.gamerc; rsync -aHAXxv --numeric-ids --delete --progress --quiet --exclude-from=$WORKING_DIRECTORY/bin/rsync.exclude -e \"ssh -T -o Compression=no -x\" $TEST_SERVER_USER@TEST:$WORKING_DIRECTORY/common-$SOURCE_OF_SYNC_TO_LIVE/. $WORKING_DIRECTORY/common_pre/; cd $WORKING_DIRECTORY/common_pre/Data/db; if [ -h S_GMToolCmds.ini ]; then unlink S_GMToolCmds.ini; fi; cd $WORKING_DIRECTORY/common_pre/Data/db; ln -s ${WORKING_DIRECTORY}/bin/S_RootCmds.ini_live_${GAME_TYPE_LOWER} s_rootcmds.ini; sed -i 's/AllGM=1/AllGM=0/' $WORKING_DIRECTORY/common_pre/bin/config.ini" &
		fi
		sleep 1
	done
   fi
}

gmsync () { # Maintenance -> Sync test to live (argument: "binary_only", "no_cdn_sync", "local")
   [ "$SOURCE_OF_SYNC_TO_LIVE" == "LIVEBackup" ] || LIVEBackup
   DATETIME="$(/bin/date +%Y%m%dT%H%M)"
   [ ! -d "$WORKING_DIRECTORY/live_sync" ] && mkdir -p $WORKING_DIRECTORY/live_sync
   cd $WORKING_DIRECTORY/live_sync
   SERVER_DIFF_FILE="$WORKING_DIRECTORY/live_sync/server_diff.txt.$DATETIME"
   if grep -a -qi "binary_only" <<< "$ALLARGS" ; then
	rsync -i -avn --exclude-from=$WORKING_DIRECTORY/bin/rsync.exclude --out-format="FILE:%n" ~/common-TEST/ CTRL:~/common/ | grep -a "^FILE:" | grep -a -v "/$" | sed 's/^FILE:/\//g' > $SERVER_DIFF_FILE
	#sendscript allall <<< "rsync -av --exclude-from=bin/rsync.exclude $TEST_SERVER_USER@TEST:common-$SOURCE_OF_SYNC_TO_LIVE/bin/. common/bin/"
	for ip in $(cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | egrep -a 'CTRL|GAMEDB|MS|WZ|ACCOUNTDB|LOGIN|ACCTDB|GDS|GAMEAGENT|SAT|GAG|CRS|SOCIETY|CES' | awk -F" " '{print $1}'); do
		echo ${ip} | colorize blue black
		print_servername ${ip} | colorize yellow black
		if grep -a -qi "local" <<< "$ALLARGS" ; then
			#ssh ${ip} "source ~/.gamerc; rsync -avz --exclude-from=bin/rsync.exclude common_pre/bin/. common/bin/"
			ssh ${ip} "rm -rf common_old/bin; mv common/bin common_old/; mv common_pre/bin common/; sed -i 's/AllGM=1/AllGM=0/' common/bin/config.ini"
		else
			ssh ${ip} "source ~/.gamerc; rsync -avz --exclude-from=bin/rsync.exclude $TEST_SERVER_USER@TEST:common-$SOURCE_OF_SYNC_TO_LIVE/bin/. common/bin/; sed -i 's/AllGM=1/AllGM=0/' common/bin/config.ini"
		fi
	done
	send_chatbot_text_only "系統腳本" "Server binary 同步完成 ( gmsync binary_only )"
   else
	rsync -i -avn --exclude-from=$WORKING_DIRECTORY/bin/rsync.exclude --out-format="FILE:%n" ~/common-TEST/ CTRL:~/common/ | grep -a "^FILE:" | grep -a -v "/$" | sed 's/^FILE:/\//g' > $SERVER_DIFF_FILE
	#sendscript allall <<< "rsync -av --exclude-from=bin/rsync.exclude $TEST_SERVER_USER@TEST:common-$SOURCE_OF_SYNC_TO_LIVE/. common/"
	for ip in $(cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | egrep -a 'CTRL|GAMEDB|MS|WZ|ACCOUNTDB|LOGIN|ACCTDB|GDS|GAMEAGENT|SAT|GAG|CRS|SOCIETY|CES' | awk -F" " '{print $1}'); do
		echo ${ip} | colorize blue black
		print_servername ${ip} | colorize yellow black
		if grep -a -qi "local" <<< "$ALLARGS" ; then
			#ssh ${ip} "source ~/.gamerc; rsync -avz --exclude-from=bin/rsync.exclude common_pre/. common/"
			ssh ${ip} "rm -rf common_old; mv common common_old; mv common_pre common; sed -i 's/AllGM=1/AllGM=0/' common/bin/config.ini"
		else
			ssh ${ip} "source ~/.gamerc; rsync -avz --exclude-from=bin/rsync.exclude $TEST_SERVER_USER@TEST:common-$SOURCE_OF_SYNC_TO_LIVE/. common/; sed -i 's/AllGM=1/AllGM=0/' common/bin/config.ini"
		fi
	done
	send_chatbot_text_only "系統腳本" "Server 全部同步完成 ( gmsync )"
   fi
   if grep -a -qi "no_cdn_sync" <<< "$ALLARGS" ; then
	echo "Okay, sync client patch to LIVE disabled"
   else
	eval $LIVE_PATCH_CDN_SYNC_CMDLINE
	ssh TEST "$CLIENT_PATCH_BACKUP_COMMAND_LINE 'Restore to sync to LIVE at $(date +%Y%m%dT%H%M)' 2>&1" | grep -a -v "Processing changed file "
   fi

   #if [ -e $HOME/ibackup/ibackup.list ] ; then
   #    grep -a -q "^translate" $HOME/ibackup/ibackup.list \
   #    || echo -e "translate\t$TRANSLATED_INI_UPLOAD_DIR" >> $HOME/ibackup/ibackup.list
   #    ssh TEST "ibackup backup translate 'Restore to sync to LIVE at $(date +%Y%m%dT%H%M)' 2>&1" | grep -a -v "Processing changed file "
   #fi
   if [ "${GAME_TYPE}-${COUNTRY_CODE_DISPLAY}" == "M12-GLOBAL" -o "${GAME_TYPE}-${COUNTRY_CODE_DISPLAY}" == "G1-EN" ]; then
   	ssh TEST "ibackup_translate maintenance" | grep -a -v "Processing changed file "
   fi
}

RollbackSync () { # Maintenance -> Rollback the server binary from lastest LIVEBackup
   echo
   echo "DANGER, THIS WILL SYNC FROM LIVEBackup(AUTOMATICALLY BACKUP ONCE BEFORE gmsync) TO LIVE SERVERS" | colorize red
   echo "WARNING: NOT INCLUDE DATABASE" | colorize yellow
   echo
   CAPTCHA="$RANDOM"
   read -p "Please type $CAPTCHA to confirm you want to do this: " CAPTCHA_A
   [ "$CAPTCHA" == "$CAPTCHA_A" ] || exec echo "Error: Wrong answer."

   sendscript allall <<< "rsync -av --exclude-from=bin/rsync.exclude $TEST_SERVER_USER@TEST:common-LIVEBackup/. common/"
}

clientsync () { # Maintenance -> Sync client to the live patch server
   for server in $(print_hosts_ip_from_whole_hosts PATCH) ; do
        print_servername $server
        rsync -arHzv --progress /var/www/html/$CLIENT_PATCH_DIR/ $LOGINUSER@$server:/var/www/html/$CLIENT_PATCH_DIR
   done
}


dbpatch () { # Maintenance -> Patch the databases
dbpatch_precheck GAMEDB
dbpatch_precheck ACCOUNTDB

gamedb_flag=$(cat /tmp/gamedb_falg)
accountdb_flag=$(cat /tmp/accountdb_flag)

   if ! [ "$DO_NOT_RUN_DBBACKUP_BEFORE_DBPATCH" == "1" ] ; then
	yes | $0 DBbackup
   fi

if [ "$gamedb_flag" -eq 1 ]; then
   for server in $(print_hosts GAMEDB) ; do
	print_servername $server
	ssh $server "sed -i -e 's/system (\"pg_dump/#system (\"pg_dump/g;s/^\(.*vacuum.*\)$/#\1/g' common/db/dbalter"
	ssh $server "cd servers$(get_set $server)/db;perl dbalter :$GAME_DB_NAME$(get_set $server)"
   done
else
   exit
fi

if [ "$accountdb_flag" -eq 1 ]; then
   print_servername accountdb
   ssh accountdb "sed -i -e 's/system (\"pg_dump/#system (\"pg_dump/g;s/^\(.*vacuum.*\)$/#\1/g' common/db/db_account_alter"
   ssh accountdb "cd servers1/db;perl db_account_alter :$ACCOUNT_DB_NAME"
else
   exit
fi

   SOCIETYDB_EXIST=$(check_server_exist_from_hosts SOCIETYDB)
   if [ "$SOCIETYDB_EXIST" -eq 1 ]; then
        print_servername societydb
        ssh societydb "sed -i -e 's/system (\"pg_dump/#system (\"pg_dump/g;s/^\(.*vacuum.*\)$/#\1/g' common/db/db_society_alter"
        ssh societydb "cd servers1/db;perl db_society_alter :$SOCIETY_DB_NAME"
   fi

   if ! [ "$DO_NOT_RUN_DBVACUUM_AFTER_DBPATCH" == "1" ] ; then
	yes | $0 DBvacuum
   fi

   send_chatbot_text_only "系統腳本" "Database Schema 更新完成 ( dbpatch )"
   # Vacuum once after maintenance on the lowest CCU
   #LOWEST_CCU_HOUR="$(PGPASSWORD="$TEST_SERVER_DB_PASSWORD" psql -h TEST -t WebTool <<< "select DISTINCT ON (to_char(date_trunc('day', time),'YYYY-MM-DD')) to_char(time,'HH24:MI:SS'),to_char(date_trunc('day', time),'YYYY-MM-DD') as date from (SELECT date_trunc('minute', regdate) as time,sum(ccu) from ccu_log where date(regdate) between '$(date -d "-1 month" +%Y-%m-%d)' and '$(date +%Y-%m-%d)'  group by date_trunc('minute', regdate) ) as t1 order by date asc,sum asc;"|cut -c 2-3|sort|uniq -c|sort -g|tail -1|awk '{print $2}')"
#   ps -Ao cmd|grep -a -q [/]atd || exec echo "Error: atd is not running, vacuum on lowest CCU will not work."
#   at $LOWEST_CCU_HOUR:00 <<< "sendscript alldb <<< 'psql -U postgres <<< \"vacuum analyze;vacuum full;\"' > /tmp/vacuum.log"
}

StopMonitor () { # Maintenance -> Stop the server monitor
   sendscript allall <<< 'source ~/.gamerc;rm -fv $WORKING_DIRECTORY/servers*/*/pid'
   ~/bin/update_localize_info_gdglobal maintenance
}

StartMonitor () { # Maintenance -> Start the server monitor
   sendscript allall <<< 'source ~/.gamerc;ls $WORKING_DIRECTORY/servers*/*/auto_start|sed "s/auto_start/pid/g;s/^/echo 65535 > /g"|sh'
}


LIVEStatus () { # ServerStatus -> Show status of LIVE servers
   sendscript allall nosave <<< "cat /proc/loadavg;ps -Ao pid,lstart,pcpu,s,cmd f|grep -a \"[A-Za-z]\+Server\""
}

LIVEBuild () { # Initialization -> Build the live servers (arguments: "nosync", "noreset")
   [ -f ~/.hosts ] && cat ~/.hosts ~/bin/hosts > /etc/hosts 2> /dev/null
   echo "Notice: /etc/hosts updated!" | colorize green

   echo -n "Checking any server process running ... " | colorize magenta
   SERVER_PROCESS="$(sendscript allall nosave nohostname <<< "source ~/.gamerc ; all_running_servers" | wc -l)"
   if [ "$SERVER_PROCESS" == "0" ] ; then
	echo "clean, good to run now." | colorize green
   else
	echo "NOT CLEAN." | colorize red black
	sendscript allall nohostname nosave <<< "ps -Ao pid,lstart,pcpu,s,cmd f|grep -a \"[A-Za-z]\+Server\""
	echo "                          ______                            " | colorize red black 5
	echo "                         /      \                           " | colorize red black 5
	echo "                        /        \                          " | colorize red black 5
	echo "                       |   STOP   |                         " | colorize red black 5
	echo "                        \        /                          " | colorize red black 5
	echo "                         \______/                           " | colorize red black 5
	echo "                                                            " | colorize red black 5
	echo
	echo "           $SERVER_PROCESS server process(es) still running." | colorize red black 5
	echo
	if grep -a -qi "noreset" <<< "$ALLARGS" ; then
		echo
		echo "If you are adding channel or set, you can just hit [Enter]"   | colorize yellow black
		echo "to continue."                                                 | colorize yellow black
		echo
		echo "If you are not adding channel or set, please hit Ctrl + C."   | colorize red black 5
		echo
		read
	else
		echo
		echo "     YOU ARE TRYING TO RUN LIVEBuild WITHOUT \"noreset\"    "    | colorize red black
		echo
		echo "LIVEBuild WITHOUT \"noreset\", MissionServer(s) WILL CRASH"   | colorize red black
		exit
	fi
   fi


   if [ "$NAT" == "1" ] || [ "$ONLY_ONE_NETWORK_INTERFACE" == "1" ] ; then
	[ "$DONT_GET_NAT_EXT_IP" == "1" ] || generate_NAT_IP_table
   fi

   echo "Syncing the scripts to all the LIVE servers ... " | colorize yellow
   syncscript
   echo

   echo "Make sure every server has same content of /etc/hosts ... " | colorize yellow
   sendscript allall nosave <<< "source ~/.gamerc ; rewrite_etc_hosts"
   echo

   sed -n -i -e  '/^[^awg]/p' ~/.ssh/known_hosts
   echo "Testing the connection from every server to TEST server ... " | colorize yellow
   sendscript allall <<< "ssh -o StrictHostKeyChecking=no TEST echo 'OK'"

   if ! grep -a -qi "noreset" <<< "$ALLARGS" ; then
	echo "Reset the minimum ports ... " | colorize yellow black
	sendscript allall <<< "rm -rfv .min_ports"
	echo "OK" | colorize green

	echo "Removing the auto_start files ... " | colorize yellow black
	sendscript allall <<< 'find ~/servers*|grep -a "/auto_start$"|xargs rm -f'
	echo "OK" | colorize green
   fi

   echo -n "Saving last_start_time ... " | colorize yellow black
   for set_number in $SET_NUMBER_LIST;do
	ssh gamedb$set_number "psql -q -t $GAME_DB_NAME$set_number <<< 'select last_start_time from serverstatus where id<0;'|awk '/[0-9]/ {print \$1}' 2> /dev/null > /tmp/gamedb$set_number-last_start_time"
   done
   echo "OK" | colorize green black

   sendscript allall <<< "mkdir -p common"
   if [ "$GAME_TYPE" == "M2" ] ; then
       grep -a -qi "nosync" <<< "$ALLARGS" || sendscript allall <<< "rsync -av --exclude-from=bin/rsync.exclude-build-m2 TEST:$WORKING_DIRECTORY/common-$SOURCE_OF_SYNC_TO_LIVE/. $WORKING_DIRECTORY/common/."
   else
       grep -a -qi "nosync" <<< "$ALLARGS" || sendscript allall <<< "rsync -av --exclude-from=bin/rsync.exclude-build TEST:$WORKING_DIRECTORY/common-$SOURCE_OF_SYNC_TO_LIVE/. $WORKING_DIRECTORY/common/."
   fi

   grep -a -qi "noreset" <<< "$ALLARGS" && SKSERVER_BUILD_COMMAND="BuildIfNotExist" || SKSERVER_BUILD_COMMAND="Build"

   ssh -o StrictHostKeyChecking=no ACCOUNTDB "yes|SKServer $SKSERVER_BUILD_COMMAND SetDir 1"
   grep -a -qi "noreset" <<< "$ALLARGS" || PGPASSWORD="$LIVE_SERVER_DB_PASSWORD" psql -h ACCOUNTDB $ACCOUNT_DB_NAME <<< "delete from worlds;" 2>&1 | sed 's/^/worlds: /g'
   ssh -o StrictHostKeyChecking=no ACCOUNTDB "yes|SKServer $SKSERVER_BUILD_COMMAND ACCOUNTDB"

   SOCIETYDB_EXIST=$(check_server_exist_from_hosts SOCIETYDB)
   if [ "$SOCIETYDB_EXIST" -eq 1 ]; then
        ssh -o StrictHostKeyChecking=no SOCIETYDB "yes|SKServer $SKSERVER_BUILD_COMMAND SOCIETYDB"
   fi

   for server in $(print_hosts GAMEDB);do
	print_servername $server | colorize yellow black
	ssh -o StrictHostKeyChecking=no $server "yes|SKServer $SKSERVER_BUILD_COMMAND SetDir $(get_set $server)"
	grep -a -qi "noreset" <<< "$ALLARGS" || PGPASSWORD="$LIVE_SERVER_DB_PASSWORD" psql -h $server $GAME_DB_NAME$(get_set $server) <<< "delete from serverstatus;" 2>&1 \
        | sed 's/^/serverstatus: /g'
	ssh -o StrictHostKeyChecking=no $server "yes|SKServer $SKSERVER_BUILD_COMMAND GAMEDB $(get_set $server)"
	#ssh -o StrictHostKeyChecking=no $server "generate_node_stream $(get_set $server)"
	#if [ "$GAME_TYPE" != "UG1" ]; then
	#	ssh -o StrictHostKeyChecking=no $server "yes|SKServer $SKSERVER_BUILD_COMMAND $(hostname2build $server)"
	#fi
   done
   for server in BGW TICKET $(print_hosts HTTPA) $(print_hosts LOGIN) $(print_hosts WZ) $(print_hosts GLOBAL) $(print_hosts ACCTDB) $(print_hosts SAT) $(print_hosts SOCIETYS); do
	if [ "$GAME_TYPE" == "UG1" ] && [ "$server" == "BGW" ]; then
		continue
	fi
	print_servername $server | colorize yellow black
	ssh -o StrictHostKeyChecking=no $server "yes|SKServer $SKSERVER_BUILD_COMMAND SetDir $(get_set $server)"
	ssh -o StrictHostKeyChecking=no $server "yes|SKServer $SKSERVER_BUILD_COMMAND $(hostname2build $server)"
   done
   for server in $(print_hosts GDS) ; do
	print_servername $server | colorize yellow black
	ssh -o StrictHostKeyChecking=no $server "yes|SKServer $SKSERVER_BUILD_COMMAND SetDir $(get_set $server)"
	ssh -o StrictHostKeyChecking=no $server "yes|SKServer $SKSERVER_BUILD_COMMAND GameDBServer $(get_set $server)"
   done
   for server in $(print_hosts MS) ; do
	print_servername $server | colorize yellow black
	ssh -o StrictHostKeyChecking=no $server "yes|SKServer $SKSERVER_BUILD_COMMAND SetDir $(get_set $server)"
	ssh -o StrictHostKeyChecking=no $server "yes|SKServer $SKSERVER_BUILD_COMMAND Mission $(get_set $server)"
   done
   for server in $(print_hosts GAG) ; do
        print_servername $server | colorize yellow black
        ssh -o StrictHostKeyChecking=no $server "yes|SKServer $SKSERVER_BUILD_COMMAND SetDir $(get_set $server)"
        ssh -o StrictHostKeyChecking=no $server "yes|SKServer $SKSERVER_BUILD_COMMAND GameAgentServer $(get_set $server)"
   done
   for server in $(print_hosts CRS) ; do
	print_servername $server | colorize yellow black
	ssh -o StrictHostKeyChecking=no $server "yes|SKServer $SKSERVER_BUILD_COMMAND SetDir $(get_set $server)"
	ssh -o StrictHostKeyChecking=no $server "yes|SKServer $SKSERVER_BUILD_COMMAND CrossRouterServer $(get_set $server)"
   done
   for server in $(print_hosts CES) ; do
	print_servername $server | colorize yellow black
	ssh -o StrictHostKeyChecking=no $server "yes|SKServer $SKSERVER_BUILD_COMMAND SetDir $(get_set $server)"
	ssh -o StrictHostKeyChecking=no $server "yes|SKServer $SKSERVER_BUILD_COMMAND CentralServer $(get_set $server)"
   done

   SOCIETYS_EXSIT=$(check_server_exist_from_hosts SOCIETYS)
   if [ "$SOCIETYS_EXSIT" -eq 1 ]; then
        for ip in $(cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | grep -a -v '#' | awk -F" " '{print $1}' | sed '/^$/d'); do
                echo ${ip} | colorize blue black
                print_servername ${ip} | colorize yellow black
                ssh ${ip} "update_society_ip EXT; update_society_ip INT"
        done
   fi

   if [ "$GAME_TYPE" == "UG1" ]; then
		echo ACCOUNTDB | colorize yellow black
		ssh -o StrictHostKeyChecking=no ACCOUNTDB "yes|SKServer $SKSERVER_BUILD_COMMAND SetDir 1"
		ssh -o StrictHostKeyChecking=no ACCOUNTDB "yes|SKServer $SKSERVER_BUILD_COMMAND Mission 1"
   fi
   #if [ "$GAME_TYPE" == "G1" ] || [ "$GAME_TYPE" == "G2" ]; then
   GDS_EXIST=$(check_server_exist_from_hosts GDS)
   if [ "$GDS_EXIST" -eq 1 ]; then
	for ip in $(cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | grep -a -v '#' | awk -F" " '{print $1}' | sed '/^$/d'); do
		echo ${ip} | colorize blue black
		print_servername ${ip} | colorize yellow black
		ssh ${ip} "update_empty_gds_port"
	done
   fi
   GAMEAGENT_EXIST=$(check_server_exist_from_hosts GAG)
   if [ "$GAMEAGENT_EXIST" -eq 1 ]; then
        for ip in $(cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | grep -a -v '#' | awk -F" " '{print $1}' | sed '/^$/d'); do
                echo ${ip} | colorize blue black
                print_servername ${ip} | colorize yellow black
                ssh ${ip} "update_empty_gag_port"
        done
   fi
   CROSSROUTER_EXIST=$(check_server_exist_from_hosts CRS)
   if [ "$CROSSROUTER_EXIST" -eq 1 ]; then
	for ip in $(cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | grep -a -v '#' | egrep -a 'CRS' | awk -F" " '{print $1}' | sed '/^$/d'); do
		echo ${ip} | colorize blue black
		print_servername ${ip} | colorize yellow black
		ssh ${ip} "upsert_cross_setup $CROSS_ROUTER_SID_LIVE"
		ssh ${ip} "sed -i 's/CrossMission=0/CrossMission=1/' $WORKING_DIRECTORY/servers$CROSS_ROUTER_SID_LIVE/setup.ini"
	done
   fi
   #CENTRALSERVER_EXIST=$(check_server_exist_from_hosts CES)
   #if [ "$CENTRALSERVER_EXIST" -eq 1 ]; then
   #     for ip in $(cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | grep -a -v '#' | awk -F" " '{print $1}' | sed '/^$/d'); do
   #     	echo ${ip} | colorize blue black
   #     	print_servername ${ip} | colorize yellow black
   #     	#ssh ${ip} "upsert_cross_setup $CROSS_ROUTER_SID_LIVE"
   #     	#ssh ${ip} "sed -i 's/CrossMission=0/CrossMission=1/' $WORKING_DIRECTORY/servers$CROSS_ROUTER_SID_LIVE/setup.ini"
   #     done
   #fi

   echo -n "Restoring last_start_time ... " | colorize yellow
   for set_number in $SET_NUMBER_LIST;do
	ssh gamedb$set_number "psql -q -t $GAME_DB_NAME$set_number <<< \"update serverstatus set last_start_time=\$(cat /tmp/gamedb$set_number-last_start_time) where id<0;\" 2> /dev/null"
   done
   echo "OK"

   if psql log_search <<< '\q' 2> /dev/null ; then
	echo -n "Checking the item_log tables on log_search database ... " | colorize yellow black
	for do_times in 1 2;do
		echo -n "Pass $do_times, " | colorize magenta
		for((SET=1;SET<=$(print_hosts GAMEDB|wc -l);SET++));do
			for((i=1;i<=12;i++));do
				pg_dump --schema-only -t set1_item_log_$i log_search \
				|sed "s/set1/set$SET/g"|psql log_search > /dev/null 2>&1
			done
			pg_dump --schema-only -t set1_item_log log_search \
			|sed "s/set1/set$SET/g"|psql log_search > /dev/null 2>&1
		done
 	done
	echo "Done" | colorize green black
   fi

   echo "Webtool remapping ... "
   $WEBTOOL_REMAPPING_CMDLINE
   echo "OK"
}

HealthyCheck () { # Maintenance -> Check the Disk/DeadLine/s_rootcmds.ini between LIVE and TEST

   # Disk Space Monitor
   #ssh TEST '~/bin/disk_space_monitor_notice_cron maintenance'
   ssh TEST '~/bin/disk_space_monitor_notice_cron_new maintenance'

   # Deadline Days Remaining Check
   #ssh TEST '~/bin/deadline_monitor_notice_cron maintenance'
   #ssh TEST '~/bin/deadline_monitor_notice_cron_new maintenance'

   # s_rootcmds.ini LIVE vs. TEST Check
   if [ "$MOBILE" == "1" ] ; then
       CHECK_FILE="s_rootcmds.ini"
   else
       CHECK_FILE="S_RootCmds.ini"
   fi

   echo "Checking ${CHECK_FILE} is different or not ... " | colorize magenta
   OUTPUT=$(source ~/.gamerc ; final_return_compare_test_srootcmds_ini)

   if [ -z "${OUTPUT}" ]; then
        echo "Looks good, ${CHECK_FILE} between LIVE and TEST is different." | colorize green black
   else
        #ulogger_echo "${OUTPUT} ${CHECK_FILE} is the same and we can not start live servers."
        echo "${OUTPUT}=>${CHECK_FILE} is the same and we can not start live servers." | ulogger
        echo '                         FETAL ERRORS!!                         ' | colorize red black 5
        echo "${OUTPUT}=> ${CHECK_FILE} between LIVE and TEST is the same. We can not start LIVE servers. Please check it!" | colorize red black

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

        ulogger $0 =End= $DO x <<< $*

        exit
   fi

   if ! [ "$DISABLE_SETUP_INI_CHECK_AFTER_GMSYNC" == "1" ] ; then
        echo ""
        echo "As we did sync to live today, let's check any different in setup.ini between TEST and LIVE ... " | colorize green black
        #sendscript all <<< "source ~/.gamerc ; compare_test_setup_ini"
	for ip in $(cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | egrep -a 'GAMEDB|MS|WZ|ACCOUNTDB|LOGIN|ACCTDB|GDS|GAMEAGENT|SAT|GAG|CRS|SOCIETY|CES' | awk -F" " '{print $1}'); do
		echo ${ip} | colorize blue black
		print_servername ${ip} | colorize yellow black
		ssh ${ip} "source ~/.gamerc ; compare_test_setup_ini"
	done
   fi

   if ! [ "$DISABLE_SROOTCMD_INI_CHECK_AFTER_GMSYNC" == "1" ] ; then
        echo ""
        echo "As we did sync to live today, let's also check any different in S_RootCmds.ini between TEST and LIVE ... " | colorize green black
        #sendscript all <<< "source ~/.gamerc ; compare_test_srootcmds_ini"
	for ip in $(cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | egrep -a 'WZ' | awk -F" " '{print $1}'); do
		echo ${ip} | colorize blue black
		print_servername ${ip} | colorize yellow black
		ssh ${ip} "source ~/.gamerc ; compare_test_srootcmds_ini"
	done
   fi
}

LIVEStart () { # Maintenance -> Start the live servers (argument: "fast")

   echo -n "Checking any server process running ... " | colorize magenta
   SERVER_PROCESS="$(sendscript allall nosave nohostname <<< "source ~/.gamerc ; all_running_servers" | wc -l)"
   if [ "$SERVER_PROCESS" == "0" ] ; then
	echo "clean, good to run now." | colorize green
   else
	echo
	echo "                          ______                            " | colorize red black 5
	echo "                         /      \                           " | colorize red black 5
	echo "                        /        \                          " | colorize red black 5
	echo "                       |   STOP   |                         " | colorize red black 5
	echo "                        \        /                          " | colorize red black 5
	echo "                         \______/                           " | colorize red black 5
	echo "                                                            " | colorize red black 5
	echo
	echo "           $SERVER_PROCESS server process(es) still running." | colorize red black 5
	echo
	sendscript allall nohostname nosave <<< "ps -Ao pid,lstart,pcpu,s,cmd f|grep -a \"[A-Za-z]\+Server\""
	echo
	echo "If you are adding channel or set, you can just hit [Enter]"   | colorize yellow black
	echo "to continue."                                                 | colorize yellow black
	echo
	echo "If you are on the maintenance, you should have a clean-start" | colorize red black
	echo "or the player may not be able to login."                      | colorize red black
	echo "Please do LIVEStop and LIVEStatus again to check if the"      | colorize red black
	echo "servers stopped correctly."                                   | colorize red black
	echo
	echo "Hit Ctrl+C if you want to abort LIVEStart."                   | colorize cyan black 5
	read
	PROCESS_IS_NOT_CLEAN="1"
   fi


   if [ "$GAME_TYPE" != "UG1" ]; then
	   if ! IsTodayMDay ; then
		echo "                          ______                            " | colorize red black 5
		echo "                         /      \                           " | colorize red black 5
		echo "                        /        \                          " | colorize red black 5
		echo "                       |   STOP   |                         " | colorize red black 5
		echo "                        \        /                          " | colorize red black 5
		echo "                         \______/                           " | colorize red black 5
		echo "                                                            " | colorize red black 5
		echo "            Read before you answer this question.           " | colorize red black 5
		echo "                                                            " | colorize red black 5
		echo "
#############################################################
# The day of week is $DayOfWeek.
# Do you want to change the MaintenanceDate from $MaintenanceDate to $DayOfWeek
# for the Guild Wars or Territory War and Rank Award
# and also resets the achivement point and guild point, etc.
#############################################################
	" | colorize yellow black
		$0 ChangeMDayToToday
	   fi
   fi

   #check_gm_command_config

   #[ "$GAME_TYPE" == "GD" ] || change_family_statue_world_id

   # Stop the LIVEDBbackup and pg_dump to prevent table lock
   killall LIVEDBbackup 2> /dev/null ; killall pg_dump 2> /dev/null

   if [ "${NTP_CHECK}" == "1" ] ; then
   	echo -n "Time Synchronization with NTP ... " | colorize yellow
   	if [ -z "$NTP_SERVER" ] ; then
   	     echo "\$NTP_SERVER is empty, no time-server setting." | colorize red
   	else
   	     if [ "$PROCESS_IS_NOT_CLEAN" == "1" ] ; then
   	         echo "Process is not clean, maybe you are adding a set or channel, so we won't run ntpdate this time." | colorize magenta
   	         sleep 5
   	     else
   	         echo
   	         # Test
   	         echo TEST | colorize yellow black
   	         NTP_RESULT="$(ssh $TEST_SERVER_USER@TEST /usr/sbin/ntpdate -u $NTP_SERVER 2>&1)";ulogger_echo "$NTP_RESULT"

   	         # Live
   	         sendscript allall <<< 'source ~/.gamerc;NTP_RESULT="$(/usr/sbin/ntpdate -u $NTP_SERVER 2>&1)";ulogger_echo "$NTP_RESULT"'
   	     fi
   	fi
   fi

   # Start from here
   if [ "$ARG2" == "fast" ] ; then
	for server in $(print_hosts BGW) TICKET $(print_hosts BATTLE) $(print_hosts ACCTDB) $(print_hosts HTTPA) $(print_hosts LOGIN) $(print_hosts GLOBAL) $(print_hosts GAMEAGENT) $(print_hosts SOCIETYS) ; do
		print_servername $server | colorize yellow black
		grep -a -q TICKET <<< "$server" && ssh $server "log_rotate 0 TicketServer 2> /dev/null" &
		grep -a -q LOGIN <<< "$server" \
		&& ssh $server "cd servers1;SKServer start LoginServer*" \
		|| ssh $server "cd servers$(get_set $server);SKServer start $(hostname2server $server)"
		sleep 3
	done

	for server in $(print_hosts GDS) ; do
		print_servername $server | colorize yellow black
		ssh $server "cd servers$(get_set $server);SKServer start $(hostname2server $server)"
		sleep 1
	done
	sleep 15

	if [ "$GAME_TYPE" == "UG1" ]; then
		ssh ACCOUNTDB "cd servers1;SKServer start MissionServer1"
	else
		for MS in $(print_hosts MS) ; do
			print_servername $MS | colorize yellow black
			ssh $MS "SKServer start $(hostname2server $MS)" &
			sleep 1
		done
	fi
	sleep 15

	#if [ "${GAME_TYPE}" == "G1" -o "$GAME_TYPE" == "G2" ]; then
   	SAT_EXIST=$(check_server_exist_from_hosts SAT)
   	if [ "$SAT_EXIST" -eq 1 ]; then
		for server in $(print_hosts SAT) ; do
			print_servername $server | colorize yellow black
			ssh $server "cd servers$(get_set $server);SKServer start $(hostname2server $server)" &
		done
	fi
	sleep 10

	GAMEAGENT_EXIST=$(check_server_exist_from_hosts GAG)
	if [ "$GAMEAGENT_EXIST" -eq 1 ]; then
		for server in $(print_hosts GAG) ; do
			print_servername $server | colorize yellow black
			ssh $server "cd servers$(get_set $server);SKServer start $(hostname2server $server)" &
		done
	fi
	sleep 10

	if [ "${GAME_TYPE}-${COUNTRY_CODE_DISPLAY}" == "M12-GLOBAL" -o "$GAME_TYPE" == "UG1" -o "$GAME_TYPE" == "G1" ]; then
		for ip in $(cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | egrep -a 'WZ' | awk -F" " '{print $1}'); do
			echo ${ip} | colorize blue black
			print_servername ${ip} | colorize yellow black
			ssh ${ip} "SKServer start all" &
			sleep 1
		done
	else
		for WZ in $(print_hosts WZ) ; do
			print_servername $WZ | colorize yellow black
			ssh $WZ "SKServer start $(hostname2server $WZ)" &
			sleep 1
		done
	fi
	sleep 30

	CROSSROUTER_EXIST=$(check_server_exist_from_hosts CRS)
	if [ "$CROSSROUTER_EXIST" -eq 1 ]; then
		for server in $(print_hosts CRS); do
			print_servername CRS$CROSS_ROUTER_SID_LIVE | colorize yellow black
			ssh CRS$CROSS_ROUTER_SID_LIVE "cd servers$CROSS_ROUTER_SID_LIVE; SKServer start $(hostname2server $server)"
		done
	fi
	sleep 30

	CENTRALSERVER_EXIST=$(check_server_exist_from_hosts CES)
	if [ "$CENTRALSERVER_EXIST" -eq 1 ]; then
		for server in $(print_hosts CES); do
			print_servername CES$CENTRAL_SID_LIVE | colorize yellow black
			ssh CES$CENTRAL_SID_LIVE "cd servers$CENTRAL_SID_LIVE; SKServer start $(hostname2server $server)"
		done
	fi
	wait

	sendscript allall nosave <<< "cat /proc/loadavg;ps -Ao pid,lstart,pcpu,s,cmd f|grep -a \"[A-Za-z]\+Server\"|grep -a -v SKServer"
   else

	for server in $(print_hosts BGW) TICKET $(print_hosts BATTLE) $(print_hosts ACCTDB) $(print_hosts HTTPA) $(print_hosts LOGIN) $(print_hosts SOCIETYS) $(print_hosts GLOBAL) $(print_hosts GAMEAGENT) ; do
		print_servername $server | colorize yellow black
		if [ "$GAME_TYPE" != "UG1" ]; then
			grep -a -q TICKET <<< "$server" && ssh $server "log_rotate 0 TicketServer 2> /dev/null" &
			grep -a -q LOGIN <<< "$server" \
			&& ssh $server "cd servers1;SKServer start LoginServer*" \
			|| ssh $server "cd servers$(get_set $server);SKServer start $(hostname2server $server)"
		else
			grep -a -q TICKET <<< "$server" && ssh $server "log_rotate 0 TicketServer 2> /dev/null" &
			grep -a -q LOGIN <<< "$server" && ssh $server "cd servers1;SKServer start LoginServer*" &
			grep -a -q ACCOUNTDB <<< "$server" \
			&& ssh $server "cd servers1; SKServer start MissionServer1" \
			|| ssh $server "cd servers$(get_set $server);SKServer start $(hostname2server $server)"
		fi
		sleep 3
	done

	for server in $(print_hosts GDS) ; do
		print_servername $server | colorize yellow black
		ssh $server "cd servers$(get_set $server);SKServer start GameDBServer$(get_set $server)"
	done

	for server in $(print_hosts MS) ; do
		print_servername $server | colorize yellow black
		if [ "$GAME_TYPE" != "UG1" ]; then
			ssh $server "cd servers$(get_set $server);SKServer start $(hostname2server $server)"
		fi
	done

	#if [ "${GAME_TYPE}" == "G1" -o "$GAME_TYPE" == "G2" ]; then
   	SAT_EXIST=$(check_server_exist_from_hosts SAT)
   	if [ "$SAT_EXIST" -eq 1 ]; then
		for server in $(print_hosts SAT) ; do
			print_servername $server | colorize yellow black
			ssh $server "cd servers$(get_set $server);SKServer start $(hostname2server $server)"
		done
	fi

	GAMEAGENT_EXIST=$(check_server_exist_from_hosts GAG)
	if [ "$GAMEAGENT_EXIST" -eq 1 ]; then
		for server in $(print_hosts GAG) ; do
			print_servername $server | colorize yellow black
			ssh $server "cd servers$(get_set $server);SKServer start $(hostname2server $server)" &
		done
	fi
	sleep 10

	for server in $(print_hosts WZ) ; do
		print_servername $server | colorize yellow black
		ssh $server "cd servers$(get_set $server);SKServer start $(hostname2server $server)"
	done
	sleep 10

	CROSSROUTER_EXIST=$(check_server_exist_from_hosts CRS)
	if [ "$CROSSROUTER_EXIST" -eq 1 ]; then
		for server in $(print_hosts CRS); do
			print_servername CRS$CROSS_ROUTER_SID_LIVE | colorize yellow black
			ssh CRS$CROSS_ROUTER_SID_LIVE "cd servers$CROSS_ROUTER_SID_LIVE; SKServer start $(hostname2server $server)"
		done
	fi
	sleep 30

	CENTRALSERVER_EXIST=$(check_server_exist_from_hosts CES)
	if [ "$CENTRALSERVER_EXIST" -eq 1 ]; then
		for server in $(print_hosts CES); do
			print_servername CES$CENTRAL_SID_LIVE | colorize yellow black
			ssh CES$CENTRAL_SID_LIVE "cd servers$CENTRAL_SID_LIVE; SKServer start $(hostname2server $server)"
		done
	fi
	wait

	sendscript allall nosave <<< "cat /proc/loadavg;ps -Ao pid,lstart,pcpu,s,cmd f|grep -a \"[A-Za-z]\+Server\"|grep -a -v SKServer"
   fi

   #[ "1" == "$(sendscript allwz nohostname <<< "source ~/.gamerc ; [ -f $APEXITEMSERVER_PATH/$APEXITEMSERVER_BIN ] && echo 1" | sort | uniq)" ] \
   #&& APEXStart

   #if ! [ "$GAME_TYPE" == "FF" ] || [ "$GAME_TYPE" == "AR" ] ; then
   #    echo "RankAward list will be automatically save into ~/RankAward/ after 10 minutes." | colorize yellow black
   #    ( sleep 600 ; get_rankaward_list ) & disown
   #fi

   send_chatbot_text_only "系統腳本" "遊戲伺服器已開啟完成\n對內了，請營運 5 ~ 10 分鐘後，嘗試看看登入正式機"   
}

LIVEStop () { # Maintenance -> Stop the live servers (argument: "fast")
   if [ "$ARG2" == "fast" ] ; then
      echo "Removing the pid files ... "
      for ip in $(cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | egrep -a 'CTRL|GAMEDB|WZ|MS|ACCOUNTDB|LOGIN|GDS|GAG|CRS|SOCIETY|CES' | awk -F" " '{print $1}'); do
         echo ${ip} | colorize blue black
         print_servername ${ip} | colorize yellow black
         ssh ${ip} "rm -f $WORKING_DIRECTORY/server*/*Server*/pid" 2>/dev/null
      done

	CENTRALSERVER_EXIST=$(check_server_exist_from_hosts CES)
	if [ "$CENTRALSERVER_EXIST" -eq 1 ]; then
		for server in $(print_hosts CES) ; do
			echo -n "Sending stop signal to the CentralServer ... " | colorize magenta
			print_servername $server | colorize yellow black
			ssh ${server} "ps -Ao cmd|grep -a 'CentralServer[0-9]'|awk -F'/' '{print \"killall -USR1 \"\$2}'|sh" > /dev/null 2>&1
			echo "OK" | colorize green
			ssh $server "SKServer stop $(hostname2server $server stop)"
			#ssh $server "kill_server_process $(hostname2server $server)"
		done
	fi

	CROSSROUTER_EXIST=$(check_server_exist_from_hosts CRS)
	if [ "$CROSSROUTER_EXIST" -eq 1 ]; then
		for server in $(print_hosts CRS) ; do
			echo -n "Sending stop signal to the CrossRouterServer ... " | colorize magenta
			print_servername $server | colorize yellow black
			ssh ${server} "ps -Ao cmd|grep -a 'CrossRouterServer[0-9]'|awk -F'/' '{print \"killall -USR1 \"\$2}'|sh" > /dev/null 2>&1
			echo "OK" | colorize green
			#ssh $server "SKServer stop $(hostname2server $server stop)"
			ssh $server "kill_server_process $(hostname2server $server)"
		done
	fi

	  if [ "$GAME_TYPE" != "UG1" ]; then
      	echo -n "Sending stop signal to all ZoneServer ... " | colorize magenta
      	for ip in $(cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | egrep -a 'WZ' | awk -F" " '{print $1}'); do
      	   echo ${ip} | colorize blue black
      	   print_servername ${ip} | colorize yellow black
      	   ssh ${ip} "ps -Ao cmd|grep -a 'ZoneServer[0-9]'|awk -F'/' '{print \"killall -USR1 \"\$2}'|sh" > /dev/null 2>&1
      	done
      	sleep 10
      	echo "OK" | colorize green
	  fi

      for ip in $(cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | egrep -a 'WZ' | awk -F" " '{print $1}'); do
	    if [ "$GAME_TYPE" != "UG1" ]; then
        	[ "$STOP_SIGNAL_SENT_TO_ALL_WORLDSERVER" != "1" ] \
        	&& ZONESERVERS_STILL_RUNNING="$(sendscript allall nosave nohostname <<< "ps -Ao pid,lstart,pcpu,s,cmd f|grep -a '\.[/]ZoneServer'" | wc -l)"
        	if [ "$ZONESERVERS_STILL_RUNNING" == "0" ] && [ "$STOP_SIGNAL_SENT_TO_ALL_WORLDSERVER" != "1" ] ; then
				echo -n "All ZoneServers have been stopped. Sending stop signal to all WorldServer ... " | colorize magenta
      	    	for ip in $(cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | egrep -a 'WZ' | awk -F" " '{print $1}'); do
      	    		echo ${ip} | colorize blue black
      	    		print_servername ${ip} | colorize yellow black
      	    		ssh ${ip} "ps -Ao cmd|grep -a 'WorldServer[0-9]'|awk -F'/' '{print \"killall -USR1 \"\$2}'|sh" > /dev/null 2>&1
      	    	done
      	    	echo "OK" | colorize green
      	    	STOP_SIGNAL_SENT_TO_ALL_WORLDSERVER="1"
      		fi
		else
        	if [ "$STOP_SIGNAL_SENT_TO_ALL_WORLDSERVER" != "1" ] ; then
      	    	for ip in $(cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | egrep -a 'WZ' | awk -F" " '{print $1}'); do
      	    		echo ${ip} | colorize blue black
      	    		print_servername ${ip} | colorize yellow black
      	    		ssh ${ip} "ps -Ao cmd|grep -a 'WorldServer[0-9]'|awk -F'/' '{print \"killall -USR1 \"\$2}'|sh" > /dev/null 2>&1
      	    	done
      	    	echo "OK" | colorize green
      	    	STOP_SIGNAL_SENT_TO_ALL_WORLDSERVER="1"
			fi
		fi
      	echo ${ip} | colorize blue black
        print_servername ${ip} | colorize yellow black
      	#ssh ${ip} "SKServer stop wz"
	if [ "${GAME_TYPE}-${COUNTRY_CODE_DISPLAY}" == "M12-GLOBAL" -o "$GAME_TYPE" == "UG1" -o "$GAME_TYPE" == "G1" ]; then
		ssh ${ip} "SKServer stop all"
	else
		ssh ${ip} "SKServer stop wz"
	fi
      done

	SOCIETYS_EXIST=$(check_server_exist_from_hosts SOCIETYS)
	if [ "$SOCIETYS_EXIST" -eq 1 ]; then
		echo -n "Sending stop signal to SocietyServer ... " | colorize magenta
		for ip in $(cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | egrep -a 'SOCIETYS' | awk -F" " '{print $1}'); do
			echo ${ip} | colorize blue black
			print_servername ${ip} | colorize yellow black
			ssh ${ip} "ps -Ao cmd|grep -a 'SocietyServer'|awk -F'/' '{print \"killall -USR1 \"\$2}'|sh" > /dev/null 2>&1
			ssh ${ip} "SKServer stop soc"
		done
	fi

	GAMEAGENT_EXIST=$(check_server_exist_from_hosts GAG)
	if [ "$GAMEAGENT_EXIST" -eq 1 ]; then
      		echo -n "Sending stop signal to all GameAgentServer ... " | colorize magenta
      	    	for ip in $(cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | egrep -a 'GAG' | awk -F" " '{print $1}'); do
			print_servername $ip | colorize yellow black
      	    		ssh ${ip} "ps -Ao cmd|grep -a 'GameAgentServer[0-9]'|awk -F'/' '{print \"killall -USR1 \"\$2}'|sh" > /dev/null 2>&1
			ssh ${ip} "SKServer stop gag"
		done
	fi

	#if [ "${GAME_TYPE}" == "G1" -o "$GAME_TYPE" == "G2" ]; then
   	SAT_EXIST=$(check_server_exist_from_hosts SAT)
   	if [ "$SAT_EXIST" -eq 1 ]; then
      		echo -n "Sending stop signal to all SatelliteServer ... " | colorize magenta
      	    	for ip in $(cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | egrep -a 'SAT' | awk -F" " '{print $1}'); do
			print_servername $ip | colorize yellow black
      	    		ssh ${ip} "ps -Ao cmd|grep -a 'SatelliteServer[0-9]'|awk -F'/' '{print \"killall -USR1 \"\$2}'|sh" > /dev/null 2>&1
			ssh ${ip} "SKServer stop sat"
		done
	fi

      echo -n "Sending stop signal to all MissionServer ... " | colorize magenta
	  if [ "$GAME_TYPE" != "UG1" ]; then
      	for ip in $(cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | egrep -a 'MS' | awk -F" " '{print $1}'); do
      	  echo ${ip} | colorize blue black
      	  print_servername ${ip} | colorize yellow black
      	  ssh ${ip} "ps -Ao cmd|grep -a 'MissionServer[0-9]'|awk -F'/' '{print \"killall -USR1 \"\$2}'|sh" > /dev/null 2>&1
      	done
	  else
	    ip=$(cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | egrep -a 'ACCOUNTDB' | awk -F" " '{print $1}')
		echo ${ip} | colorize blue black
     	print_servername ${ip} | colorize yellow black
      	ssh ${ip} "ps -Ao cmd|grep -a 'MissionServer[0-9]'|awk -F'/' '{print \"killall -USR1 \"\$2}'|sh" > /dev/null 2>&1
	  fi

      echo -n "Sending stop signal to all GameDBServer ... " | colorize magenta
      	for ip in $(cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | egrep -a 'GDS' | awk -F" " '{print $1}'); do
		echo ${ip} | colorize blue black
		print_servername ${ip} | colorize yellow black
		ssh ${ip} "ps -Ao cmd|grep -a 'GameDBServer[0-9]'|awk -F'/' '{print \"killall -USR1 \"\$2}'|sh" > /dev/null 2>&1
	done

	#CROSSROUTER_EXIST=$(check_server_exist_from_hosts CRS)
	#if [ "$CROSSROUTER_EXIST" -eq 1 ]; then
	#	for server in $(print_hosts CRS) ; do
	#		echo -n "Sending stop signal to the CrossRouterServer ... " | colorize magenta
	#		print_servername $server | colorize yellow black
	#		ssh ${server} "ps -Ao cmd|grep -a 'CrossRouterServer[0-9]'|awk -F'/' '{print \"killall -USR1 \"\$2}'|sh" > /dev/null 2>&1
	#		echo "OK" | colorize green
	#		#ssh $server "SKServer stop $(hostname2server $server stop)"
	#		ssh $server "kill_server_process $(hostname2server $server)"
	#	done
	#fi

   else
      echo "Removing the pid files ... "
      sendscript allall <<< "rm -f $WORKING_DIRECTORY/server*/*Server*/pid" 2>/dev/null

	CENTRALSERVER_EXIST=$(check_server_exist_from_hosts CES)
	if [ "$CENTRALSERVER_EXIST" -eq 1 ]; then
		for server in $(print_hosts CES) ; do
			echo -n "Sending stop signal to the CentralServer ... " | colorize magenta
			print_servername $server | colorize yellow black
			ssh ${server} "ps -Ao cmd|grep -a 'CentralServer[0-9]'|awk -F'/' '{print \"killall -USR1 \"\$2}'|sh" > /dev/null 2>&1
			echo "OK" | colorize green
			ssh $server "SKServer stop $(hostname2server $server stop)"
			#ssh $server "kill_server_process $(hostname2server $server)"
		done
	fi

	CROSSROUTER_EXIST=$(check_server_exist_from_hosts CRS)
	if [ "$CROSSROUTER_EXIST" -eq 1 ]; then
		for server in $(print_hosts CRS) ; do
			echo -n "Sending stop signal to the CrossRouterServer ... " | colorize magenta
			print_servername $server | colorize yellow black
			ssh ${server} "ps -Ao cmd|grep -a 'CrossRouterServer[0-9]'|awk -F'/' '{print \"killall -USR1 \"\$2}'|sh" > /dev/null 2>&1
			echo "OK" | colorize green
			#ssh $server "SKServer stop $(hostname2server $server stop)"
			ssh $server "kill_server_process $(hostname2server $server)"
		done
	fi

	  if [ "$GAME_TYPE" != "UG1" ]; then
      	echo -n "Sending stop signal to all ZoneServer ... " | colorize magenta
      	sendscript allwz <<< "ps -Ao cmd|grep -a 'ZoneServer[0-9]'|awk -F'/' '{print \"killall -USR1 \"\$2}'|sh" > /dev/null 2>&1
      	sleep 10
      	echo "OK" | colorize green
	  fi

      for server in $(print_hosts WZ) ; do
	  	if [ "$GAME_TYPE" != "UG1" ]; then
           [ "$STOP_SIGNAL_SENT_TO_ALL_WORLDSERVER" != "1" ] \
           && ZONESERVERS_STILL_RUNNING="$(sendscript allall nosave nohostname <<< "ps -Ao pid,lstart,pcpu,s,cmd f|grep -a '\.[/]ZoneServer'" | wc -l)"
           if [ "$ZONESERVERS_STILL_RUNNING" == "0" ] && [ "$STOP_SIGNAL_SENT_TO_ALL_WORLDSERVER" != "1" ] ; then
               echo -n "All ZoneServers have been stopped. Sending stop signal to all WorldServer ... " | colorize magenta
               sendscript allwz <<< "ps -Ao cmd|grep -a 'WorldServer[0-9]'|awk -F'/' '{print \"killall -USR1 \"\$2}'|sh" > /dev/null 2>&1
               echo "OK" | colorize green
               STOP_SIGNAL_SENT_TO_ALL_WORLDSERVER="1"
           fi
		else
           if [ "$STOP_SIGNAL_SENT_TO_ALL_WORLDSERVER" != "1" ] ; then
               sendscript allwz <<< "ps -Ao cmd|grep -a 'WorldServer[0-9]'|awk -F'/' '{print \"killall -USR1 \"\$2}'|sh" > /dev/null 2>&1
               echo "OK" | colorize green
               STOP_SIGNAL_SENT_TO_ALL_WORLDSERVER="1"
		   fi
		fi
           print_servername $server | colorize yellow black
           ssh $server "SKServer stop $(hostname2server $server stop)"
      done

        SOCIETYS_EXIST=$(check_server_exist_from_hosts SOCIETYS)
        if [ "$SOCIETYS_EXIST" -eq 1 ]; then
		echo -n "Sending stop signal to SocietyServer ... " | colorize magenta
		sendscript societys <<< "ps -Ao cmd|grep -a 'SocietyServer'|awk -F'/' '{print \"killall -USR1 \"\$2}'|sh" > /dev/null 2>&1
	fi

	GAMEAGENT_EXIST=$(check_server_exist_from_hosts GAG)
	if [ "$GAMEAGENT_EXIST" -eq 1 ]; then
		for server in $(print_hosts GAG) ; do
      		echo -n "Sending stop signal to all GameAgentServer ... " | colorize magenta
			print_servername $server | colorize yellow black
      	    		ssh ${server} "ps -Ao cmd|grep -a 'GameAgentServer[0-9]'|awk -F'/' '{print \"killall -USR1 \"\$2}'|sh" > /dev/null 2>&1
			ssh $server "SKServer stop $(hostname2server $server stop)"
		done
	fi

	#if [ "${GAME_TYPE}" == "G1" -o "$GAME_TYPE" == "G2" ]; then
   	SAT_EXIST=$(check_server_exist_from_hosts SAT)
   	if [ "$SAT_EXIST" -eq 1 ]; then
		for server in $(print_hosts SAT) ; do
			print_servername $server | colorize yellow black
      	    		ssh $server "ps -Ao cmd|grep -a 'SatelliteServer[0-9]'|awk -F'/' '{print \"killall -USR1 \"\$2}'|sh" > /dev/null 2>&1
			ssh $server "SKServer stop $(hostname2server $server stop)"
		done
	fi

	  if [ "$GAME_TYPE" != "UG1" ]; then
      	echo -n "Sending stop signal to all MissionServer ... " | colorize magenta
      	sendscript allgamedb <<< "ps -Ao cmd|grep -a 'MissionServer[0-9]'|awk -F'/' '{print \"killall -USR1 \"\$2}'|sh" > /dev/null 2>&1
	  else
      	echo -n "Sending stop signal to MissionServer1 ... " | colorize magenta
      	sendscript accountdb <<< "ps -Ao cmd|grep -a 'MissionServer1'|awk -F'/' '{print \"killall -USR1 \"\$2}'|sh" > /dev/null 2>&1
	  fi
   fi
   sleep 10
   echo "OK" | colorize green

   for server in $(print_hosts SOCIETYS); do
        print_servername $server | colorize yellow black
        ssh $server "SKServer stop $(hostname2server $server stop)"
   done

	if [ "$GAME_TYPE" != "UG1" ]; then
 	   	for server in $(print_hosts MS) ; do
			print_servername $server | colorize yellow black
			ssh $server "SKServer stop $(hostname2server $server stop)"
   		done
	else
		print_servername ACCOUNTDB | colorize yellow black
		ssh ACCOUNTDB "cd servers1;SKServer stop MissionServer1"
	fi

	for server in $(print_hosts GDS) ; do
		print_servername $server | colorize yellow black
		ssh $server "cd servers$(get_set $server);SKServer stop $(hostname2server $server)"
		sleep 3
	done

	#CROSSROUTER_EXIST=$(check_server_exist_from_hosts CRS)
	#if [ "$CROSSROUTER_EXIST" -eq 1 ]; then
	#	for server in $(print_hosts CRS) ; do
	#		echo -n "Sending stop signal to the CrossRouterServer ... " | colorize magenta
	#		print_servername $server | colorize yellow black
	#		ssh ${server} "ps -Ao cmd|grep -a 'CrossRouterServer[0-9]'|awk -F'/' '{print \"killall -USR1 \"\$2}'|sh" > /dev/null 2>&1
	#		echo "OK" | colorize green
	#		#ssh $server "SKServer stop $(hostname2server $server stop)"
	#		ssh $server "kill_server_process $(hostname2server $server)"
	#	done
	#fi

   for server in $(print_hosts GLOBAL) $(print_hosts LOGIN) $(print_hosts HTTPA) $(print_hosts ACCTDB) $(print_hosts BATTLE) TICKET $(print_hosts BGW) ; do
	print_servername $server | colorize yellow black
	ssh $server "cd servers1;SKServer stop $(hostname2server $server stop)"
   done

   echo -n "Cleaning table currentuser on $MEMBER_DB_NAME ... " | colorize yellow black
   if [ "$(sendscript allgamedb nosave nohostname <<< "ps -Ao cmd|grep -a 'MissionServer[0-9]'"|wc -l)" == "0" ] ; then
	ssh accountdb clean_currentuser \
	&& echo "OK" | colorize green \
	|| echo "FAILED, Unable to call function clean_currentuser." | colorize red
   else
	echo "FAILED, There are some MissionServer still running:" | colorize red
	sendscript allgamedb <<< "ps -Ao cmd|grep -a 'MissionServer[0-9]'|egrep -a -v 'level.log'"
   fi

   ssh accountdb "psql $ACCOUNT_DB_NAME <<< 'UPDATE worlds set online_user = 0;'"

   [ "1" == "$(sendscript allwz nohostname <<< "source ~/.gamerc ; [ -f $APEXITEMSERVER_PATH/$APEXITEMSERVER_BIN ] && echo 1" | sort | uniq)" ] \
   && APEXStop

   send_chatbot_text_only "系統腳本" "遊戲伺服器 已關閉完成"
}

CheckAlive () { # ServerStatus -> Check the LIVE servers running status
   sendscript allall <<< "SKServer CheckAlive all"
}

LGStop () { # Maintenance -> Stop login servers
   for login in $(print_hosts LOGIN);do
	ssh $login "cd servers1;SKServer stop LoginServer*"
   done
}
LGStart () { # Maintenance -> Start login servers
   for login in $(print_hosts LOGIN);do
	ssh $login "cd servers1;SKServer start LoginServer*"
   done
}
LGRestart () { # Maintenance -> Restart login servers
   for login in $(print_hosts LOGIN);do
	ssh $login "cd servers1;SKServer stop LoginServer*;SKServer start LoginServer*"
   done
}

LGBlock () { # Maintenance -> Block the players by iptables firewall ( Login )
   for login in $(print_hosts LOGIN);do
	echo $login | colorize yellow black
	if [ "$LGFW_MODE" == "1" ] ; then
		ssh $login "sudo iptables-restore < $IPTABLES_LGFW_ON_CONFIG_FILE; sudo iptables -L -v -n"
	elif [ "$LGFW_MODE" == "2" ] ; then
		ssh $login "for PORT in $LOGIN_SERVER_PORTS ;do
			for IP in $LOGIN_SERVER_ALLOW_IP ;do
				sudo iptables -v -A INPUT -p tcp -s \$IP --dport \$PORT -j ACCEPT
			done
			sudo iptables -v -A INPUT -p tcp --dport \$PORT -j DROP
   		done
		sudo iptables -L -v -n"
	elif [ "$LGFW_MODE" == "3" ] ; then
		ssh -t $login "sudo su -l -c '/etc/init.d/iptables start'"
		ssh -t $login "sudo su -l -c '/etc/init.d/iptables status'"
	fi
   done
   $HOME/bin/check_live_iptables_and_notify
}

LGAllow () { # Maintenance -> Allow the players by iptables firewall ( Login )
   for login in $(print_hosts LOGIN);do
	echo $login | colorize yellow black
	if [ "$LGFW_MODE" == "1" ] ; then
		ssh $login "sudo iptables-restore < $IPTABLES_LGFW_OFF_CONFIG_FILE; sudo iptables -L -v -n"
	elif [ "$LGFW_MODE" == "2" ] ; then
		ssh $login "for PORT in $LOGIN_SERVER_PORTS ;do
			for IP in $LOGIN_SERVER_ALLOW_IP ;do
				sudo iptables -v -D INPUT -p tcp -s \$IP --dport \$PORT -j ACCEPT
			done
			sudo iptables -v -D INPUT -p tcp --dport \$PORT -j DROP
   		done
		sudo iptables -L -v -n"
	elif [ "$LGFW_MODE" == "3" ] ; then
		ssh -t $login "sudo su -l -c '/etc/init.d/iptables stop'; sudo iptables -L -v -n'"
	fi
   done
   $HOME/bin/check_live_iptables_and_notify
}

WSBlock () { # Maintenance -> Block the players by iptables firewall ( World )
   MACHINE=$ARG2

   if [ ! -z "$ARG2" ]; then
                echo $MACHINE | colorize yellow black
                if [ "$LGFW_MODE" == "1" ] ; then
                        ssh $MACHINE "sudo iptables-restore < $IPTABLES_LGFW_ON_CONFIG_FILE; sudo iptables -L -v -n"
                elif [ "$LGFW_MODE" == "2" ] ; then
                        PORT_START=$(echo $WORLD_SERVER_PORTS_RANGE | cut -d'-' -f1)
                        PORT_END=$(echo $WORLD_SERVER_PORTS_RANGE | cut -d'-' -f2)
                        ssh $MACHINE "sudo iptables_port_range ADD $PORT_START $PORT_END"
                elif [ "$LGFW_MODE" == "3" ] ; then
                        ssh -t $MACHINE "sudo su -l -c '/etc/init.d/iptables start'"
                        ssh -t $MACHINE "sudo su -l -c '/etc/init.d/iptables status'"
                fi
   else
                for WS in $(print_hosts WS);do
                        echo $WS | colorize yellow black
                        if [ "$LGFW_MODE" == "1" ] ; then
                                ssh $WS "sudo iptables-restore < $IPTABLES_LGFW_ON_CONFIG_FILE; sudo iptables -L -v -n"
                        elif [ "$LGFW_MODE" == "2" ] ; then
                                PORT_START=$(echo $WORLD_SERVER_PORTS_RANGE | cut -d'-' -f1)
                                PORT_END=$(echo $WORLD_SERVER_PORTS_RANGE | cut -d'-' -f2)
                                ssh $WS "sudo iptables_port_range ADD $PORT_START $PORT_END"
                        elif [ "$LGFW_MODE" == "3" ] ; then
                                ssh -t $WS "sudo su -l -c '/etc/init.d/iptables start'"
                                ssh -t $WS "sudo su -l -c '/etc/init.d/iptables status'"
                        fi
                done
   fi
}

WSAllow () { # Maintenance -> Allow the players by iptables firewall ( World )
   MACHINE=$ARG2

   if [ ! -z "$ARG2" ]; then
                echo $MACHINE | colorize yellow black
                if [ "$LGFW_MODE" == "1" ] ; then
                        ssh $MACHINE "sudo iptables-restore < $IPTABLES_LGFW_OFF_CONFIG_FILE; sudo iptables -L -v -n"
                elif [ "$LGFW_MODE" == "2" ] ; then
                        PORT_START=$(echo $WORLD_SERVER_PORTS_RANGE | cut -d'-' -f1)
                        PORT_END=$(echo $WORLD_SERVER_PORTS_RANGE | cut -d'-' -f2)
                        ssh $MACHINE "sudo iptables_port_range REMOVE $PORT_START $PORT_END"
                elif [ "$LGFW_MODE" == "3" ] ; then
                        ssh -t $MACHINE "sudo su -l -c '/etc/init.d/iptables stop'; sudo iptables -L -v -n'"
                fi
   else
                for WS in $(print_hosts WS);do
                        echo $WS | colorize yellow black
                        if [ "$LGFW_MODE" == "1" ] ; then
                                ssh $WS "sudo iptables-restore < $IPTABLES_LGFW_OFF_CONFIG_FILE; sudo iptables -L -v -n"
                        elif [ "$LGFW_MODE" == "2" ] ; then
                                PORT_START=$(echo $WORLD_SERVER_PORTS_RANGE | cut -d'-' -f1)
                                PORT_END=$(echo $WORLD_SERVER_PORTS_RANGE | cut -d'-' -f2)
                                ssh $WS "sudo iptables_port_range REMOVE $PORT_START $PORT_END"
                        elif [ "$LGFW_MODE" == "3" ] ; then
                                ssh -t $WS "sudo su -l -c '/etc/init.d/iptables stop'; sudo iptables -L -v -n'"
                        fi
                done
   fi
}

ZSBlock () { # Maintenance -> Block the players by iptables firewall ( Zone )
   MACHINE=$ARG2

   if [ ! -z "$ARG2" ]; then
                echo $MACHINE | colorize yellow black
                if [ "$LGFW_MODE" == "1" ] ; then
                        ssh $MACHINE "sudo iptables-restore < $IPTABLES_LGFW_ON_CONFIG_FILE; sudo iptables -L -v -n"
                elif [ "$LGFW_MODE" == "2" ] ; then
                        PORT_START=$(echo $ZONE_SERVER_PORTS_RANGE | cut -d'-' -f1)
                        PORT_END=$(echo $ZONE_SERVER_PORTS_RANGE | cut -d'-' -f2)
                        ssh $MACHINE "sudo iptables_port_range ADD $PORT_START $PORT_END"
                elif [ "$LGFW_MODE" == "3" ] ; then
                        ssh -t $MACHINE "sudo su -l -c '/etc/init.d/iptables start'"
                        ssh -t $MACHINE "sudo su -l -c '/etc/init.d/iptables status'"
                fi
   else
                for ZS in $(print_hosts ZS);do
                        echo $ZS | colorize yellow black
                        if [ "$LGFW_MODE" == "1" ] ; then
                                ssh $ZS "sudo iptables-restore < $IPTABLES_LGFW_ON_CONFIG_FILE; sudo iptables -L -v -n"
                        elif [ "$LGFW_MODE" == "2" ] ; then
                                PORT_START=$(echo $ZONE_SERVER_PORTS_RANGE | cut -d'-' -f1)
                                PORT_END=$(echo $ZONE_SERVER_PORTS_RANGE | cut -d'-' -f2)
                                ssh $ZS "sudo iptables_port_range ADD $PORT_START $PORT_END"
                        elif [ "$LGFW_MODE" == "3" ] ; then
                                ssh -t $ZS "sudo su -l -c '/etc/init.d/iptables start'"
                                ssh -t $ZS "sudo su -l -c '/etc/init.d/iptables status'"
                        fi
                done
   fi
}

ZSAllow () { # Maintenance -> Allow the players by iptables firewall ( Zone )
   MACHINE=$ARG2

   if [ ! -z "$ARG2" ]; then
                echo $MACHINE | colorize yellow black
                if [ "$LGFW_MODE" == "1" ] ; then
                        ssh $MACHINE "sudo iptables-restore < $IPTABLES_LGFW_OFF_CONFIG_FILE; sudo iptables -L -v -n"
                elif [ "$LGFW_MODE" == "2" ] ; then
                        PORT_START=$(echo $ZONE_SERVER_PORTS_RANGE | cut -d'-' -f1)
                        PORT_END=$(echo $ZONE_SERVER_PORTS_RANGE | cut -d'-' -f2)
                        ssh $MACHINE "sudo iptables_port_range REMOVE $PORT_START $PORT_END"
                elif [ "$LGFW_MODE" == "3" ] ; then
                        ssh -t $MACHINE "sudo su -l -c '/etc/init.d/iptables stop'; sudo iptables -L -v -n'"
                fi
   else
                for ZS in $(print_hosts ZS);do
                        echo $ZS | colorize yellow black
                        if [ "$LGFW_MODE" == "1" ] ; then
                                ssh $ZS "sudo iptables-restore < $IPTABLES_LGFW_OFF_CONFIG_FILE; sudo iptables -L -v -n"
                        elif [ "$LGFW_MODE" == "2" ] ; then
                                PORT_START=$(echo $ZONE_SERVER_PORTS_RANGE | cut -d'-' -f1)
                                PORT_END=$(echo $ZONE_SERVER_PORTS_RANGE | cut -d'-' -f2)
                                ssh $ZS "sudo iptables_port_range REMOVE $PORT_START $PORT_END"
                        elif [ "$LGFW_MODE" == "3" ] ; then
                                ssh -t $ZS "sudo su -l -c '/etc/init.d/iptables stop'; sudo iptables -L -v -n'"
                        fi
                done
   fi
} 

PrivateBlock () { # Maintenance -> Block the players by iptables firewall ( Private )
   MACHINE=$ARG2

   if [ ! -z "$ARG2" ]; then
                echo $MACHINE | colorize yellow black
                if [ "$LGFW_MODE" == "1" ] ; then
                        ssh $MACHINE "sudo iptables-restore < $IPTABLES_LGFW_ON_CONFIG_FILE; sudo iptables -L -v -n"
                elif [ "$LGFW_MODE" == "2" ] ; then
                        ssh $MACHINE "sudo iptables_port_range_class_c ADD $WZ_SERVER_IP_RANGE"
                elif [ "$LGFW_MODE" == "3" ] ; then
                        ssh -t $MACHINE "sudo su -l -c '/etc/init.d/iptables start'"
                        ssh -t $MACHINE "sudo su -l -c '/etc/init.d/iptables status'"
                fi
   else
                for ZS in $(print_hosts ZS);do
                        echo $ZS | colorize yellow black
                        if [ "$LGFW_MODE" == "1" ] ; then
                                ssh $ZS "sudo iptables-restore < $IPTABLES_LGFW_ON_CONFIG_FILE; sudo iptables -L -v -n"
                        elif [ "$LGFW_MODE" == "2" ] ; then
                                ssh $ZS "sudo iptables_port_range_class_c ADD $WZ_SERVER_IP_RANGE"
                        elif [ "$LGFW_MODE" == "3" ] ; then
                                ssh -t $ZS "sudo su -l -c '/etc/init.d/iptables start'"
                                ssh -t $ZS "sudo su -l -c '/etc/init.d/iptables status'"
                        fi
                done
   fi
}

PrivateAllow () { # Maintenance -> Allow the players by iptables firewall ( Private )
   MACHINE=$ARG2

   if [ ! -z "$ARG2" ]; then
                echo $MACHINE | colorize yellow black
                if [ "$LGFW_MODE" == "1" ] ; then
                        ssh $MACHINE "sudo iptables-restore < $IPTABLES_LGFW_OFF_CONFIG_FILE; sudo iptables -L -v -n"
                elif [ "$LGFW_MODE" == "2" ] ; then
                        ssh $MACHINE "sudo iptables_port_range_class_c REMOVE $WZ_SERVER_IP_RANGE"
                elif [ "$LGFW_MODE" == "3" ] ; then
                        ssh -t $MACHINE "sudo su -l -c '/etc/init.d/iptables stop'; sudo iptables -L -v -n'"
                fi
   else
                for ZS in $(print_hosts ZS);do
                        echo $ZS | colorize yellow black
                        if [ "$LGFW_MODE" == "1" ] ; then
                                ssh $ZS "sudo iptables-restore < $IPTABLES_LGFW_OFF_CONFIG_FILE; sudo iptables -L -v -n"
                        elif [ "$LGFW_MODE" == "2" ] ; then
                                ssh $ZS "sudo iptables_port_range_class_c REMOVE $WZ_SERVER_IP_RANGE"
                        elif [ "$LGFW_MODE" == "3" ] ; then
                                ssh -t $ZS "sudo su -l -c '/etc/init.d/iptables stop'; sudo iptables -L -v -n'"
                        fi
                done
   fi
}  

APEXStart () { # APEX -> Start APEXItemServer
   for server in $(print_hosts_ip WZ) ; do
	print_servername $server
	ssh $server "echo Starting $APEXITEMSERVER_BIN ... ; cd $APEXITEMSERVER_PATH;ps -C $APEXITEMSERVER_BIN > /dev/null 2>&1 && echo $APEXITEMSERVER_BIN already running. || LD_LIBRARY_PATH=. ./$APEXITEMSERVER_BIN"
   done
}
APEXStop () { # APEX -> Stop APEXItemServer
   for server in $(print_hosts_ip WZ) ; do
	print_servername $server
	ssh $server "echo Stoping $APEXITEMSERVER_BIN ... ; ps -C $APEXITEMSERVER_BIN > /dev/null 2>&1 && killall -USR1 $APEXITEMSERVER_BIN || echo $APEXITEMSERVER_BIN is not running."
   done
}

APEXLogPack () { # APEX -> Pack up APEXItemServer log to a zip
   DAYS_TO_PACK="$((($(date +%s)-$(date -d "$(grep -a APEXLogPack ~/.ctrl.log |tail -1|awk '{print $1}')" +%s ))/86400+1))"
   [ "$DAYS_TO_PACK" -gt "7" ] && DAYS_TO_PACK=7
   grep -a -q APEXLogPack ~/.ctrl.log || DAYS_TO_PACK=7
   [ "$ARG2" == "" ] || DAYS_TO_PACK="$ARG2"
   DATE_TODAY="$(date +%Y%m%dT%H%M)"
   mkdir /tmp/APEXItemServer_log_$DATE_TODAY
   for server in $(print_hosts_ip WZ) ; do
        print_servername $server
    	ssh $server "rm -rf /tmp/apexlog;mkdir -p /tmp/apexlog;find $APEXITEMSERVER_PATH/hook_log -name '*.txt' -mtime -$DAYS_TO_PACK|xargs -I {} cp -avx {} /tmp/apexlog"
        ssh $server "find ~/servers*/bin/proxy_log/ -name '*.txt' -mtime -$DAYS_TO_PACK|xargs -I {} cp -avx {} /tmp/apexlog"
        scp -r $server:/tmp/apexlog /tmp/APEXItemServer_log_$DATE_TODAY/$(print_servername $server|sed 's/ /_/g')
   done
   cd /tmp
   zip APEXItemServer_log_$DATE_TODAY -r -9 APEXItemServer_log_$DATE_TODAY
   ssh TEST "mkdir -p ~/www/download"
   scp /tmp/APEXItemServer_log_$DATE_TODAY.zip $TEST_SERVER_USER@TEST:~/www/download
   echo "Please download from: http://$TEST_SERVER_GLOBAL_IP/download/APEXItemServer_log_$DATE_TODAY.zip"
}

APEXSync () { # APEX -> Sync APEX only from TEST to LIVE
   sendscript allwz <<< "mkdir -p $APEX_BASE_PATH;rsync -av --exclude-from=bin/rsync.exclude $TEST_SERVER_USER@TEST:$APEX_BASE_PATH/ $APEX_BASE_PATH"
}

DBbackup () { # Maintenance -> Backup databases (argument: "accountdb_only")
   print_servername accountdb | colorize yellow black
   ssh accountdb "DBbackup $ACCOUNT_DB_NAME" &
   ssh accountdb "DBbackup $MEMBER_DB_NAME" &
   SOCIETYDB_EXIST=$(check_server_exist_from_hosts SOCIETYDB)
   if [ "$SOCIETYDB_EXIST" -eq 1 ]; then
	ssh societydb "DBbackup $SOCIETY_DB_NAME" &
   fi

   [ "$ARG2" == "accountdb_only" ] || for server in $(print_hosts GAMEDB) ; do
	print_servername $server | colorize yellow black
	ssh $server "DBbackup $GAME_DB_NAME$(get_set $server)" &
   done
   wait

   [ ! -z "${LOGIN_USER}" ] && send_chatbot_text_only "系統腳本" "遊戲資料庫 備分完成"
}

GMList () { # ServerStatus -> The list of GM characters
   sendscript allgamedb <<< 'source ~/.gamerc ; psql -P border=2 -P footer=0 $GAME_DB_NAME$(get_set $HOST_NAME) <<< "select id, given_name, privilege, account_name from player_characters where privilege <> 0 order by id;"'
}

GMCmds () { # ServerStatus -> List all the commands that used by GM characters
   [ "$ARG2" == "" ] \
   && exec echo "Usage: $0 GMCmds <Set number>" \
   || sendscript set${ARG2}wz nosave nohostname <<< 'xcat `find server*|grep -a GMCommand.*`|tr -d "\r";cat server*/Zone*/GMCommand*|tr -d "\r"'|sort -t , -k 2
}

GMToolCmds () { # ServerStatus -> List all the commands that used by GM Tool
   ssh accountdb 'psql $ACCOUNT_DB_NAME -c "copy (select time,gm_id,cmd_type,cmd_detail,reason from gm_tool_log order by time) to stdout csv;"'
}

GMToolAccounts () { # ServerStatus -> List all the GM Tool accounts
   ssh accountdb "psql -P border=2 -P footer=0 $ACCOUNT_DB_NAME <<< 'select * from gm_tool_accounts;'"
}

IP () { # ServerStatus -> Show all IP and ports list
   if grep -a -q csv <<< "$ARG2" ; then

	for server in $(print_hosts GAMEDB) ; do
		ssh $server "psql $GAME_DB_NAME$(get_set $server) postgres -c 'copy (select id,name,ext_address,ext_port,int_address,int_port from serverstatus order by ext_address) to stdout with csv header;'"|sed "s/^\([^a-z]\)/Set $(get_set $server),\1/g;s/id,/set,id,/g"
	done

	echo
	echo or
	echo
	sendscript allall <<< "ifconfig|grep -a 'inet addr'|grep -a -v 127.0.0.1"|awk -F: '{print $1,$2}'|sed 's/ \+inet addr //g;s/Bcast//g'|sed ':a;N;$!ba;s/\n//g;s/\([A-Z]\{2,\}\)/|\1/g;s/ \+/,/g;s/_|/_/g'|tr '|' '\n'

   else

	echo "/etc/hosts:" | colorize yellow black
	sed -n '/BELOW/,/ABOVE/p' /etc/hosts|egrep -a "^[0-9]|^##"
	echo

        for LOGIN_SERVER_HOSTNAME in $(print_hosts LOGIN) ; do
  	    if [ "$NAT" == "1" ] || [ "$ONLY_ONE_NETWORK_INTERFACE" == "1" ] ; then
		    LOGIN_SERVER_EXT_IP="$(get_nat_ext_ip $(print_serverip $LOGIN_SERVER_HOSTNAME))"
	    else
		    LOGIN_SERVER_EXT_IP="$(ssh $LOGIN_SERVER_HOSTNAME "another_ip $(print_serverip $LOGIN_SERVER_HOSTNAME)")"
	    fi

	    echo "$LOGIN_SERVER_HOSTNAME: LoginServer ports(External IP: $LOGIN_SERVER_EXT_IP)" | colorize yellow black
	    ssh $LOGIN_SERVER_HOSTNAME "grep -a -h LoginServerPort */*/setup.ini"|sort|uniq
	    echo
        done

	echo "Connects.ini for LIVE server:" | colorize yellow black
	NUM_OF_STREAM=1
        for LOGIN_SERVER_HOSTNAME in $(print_hosts LOGIN) ; do
  	    if [ "$NAT" == "1" ] || [ "$ONLY_ONE_NETWORK_INTERFACE" == "1" ] ; then
		    LOGIN_SERVER_EXT_IP="$(get_nat_ext_ip $(print_serverip $LOGIN_SERVER_HOSTNAME))"
	    else
		    LOGIN_SERVER_EXT_IP="$(ssh $LOGIN_SERVER_HOSTNAME "another_ip $(print_serverip $LOGIN_SERVER_HOSTNAME)")"
	    fi

	    for LOGIN_PORT in $(ssh $LOGIN_SERVER_HOSTNAME "grep -a -h LoginServerPort */*/setup.ini"|sort|uniq|awk -F= '{print $NF}') ; do
		    echo "Stream$(seq -w 99|head -$NUM_OF_STREAM|tail -1)=$LOGIN_SERVER_EXT_IP,$LOGIN_PORT"
                    NUM_OF_STREAM=$(($NUM_OF_STREAM+1))
	    done
        done
	echo

	for server in $(print_hosts GAMEDB) ; do
		print_servername $server | colorize yellow black
		ssh $server "psql $GAME_DB_NAME$(get_set $server) postgres -c 'select id,name,ext_address,ext_port,int_address,int_port from serverstatus where int_port>0 and ext_port>0' -P border=2 -P border=2"
	done
   fi
}

DBvacuum () { # Maintenance -> Vacuum all the databases on live server
   SERVER_PROCESS="$(sendscript allall nosave nohostname <<< "source ~/.gamerc;all_running_servers|grep -a -v TicketServer"|wc -l)"
   if [ "$SERVER_PROCESS" == "0" ] ; then
	echo "Clean, no any server running." | colorize green
	sendscript alldb -p <<< 'psql -U postgres <<< "vacuum analyze;vacuum full;" 2>&1 | tee /tmp/VacuumDB.log'
   else
	echo "      YOU ARE TRYING TO DO VACUUM ON THE RUNNING SERVERS     " | colorize red black
	echo "  THIS WILL CAUSE DATA LOSS AND LOCKS TABLE ON THE DATABASE  " | colorize red black
	exit
   fi
}

Channels () { # ServerStatus -> Show channels and current players
   PGPASSWORD="$LIVE_SERVER_DB_PASSWORD" psql -h accountdb -P border=2 -P footer=0 $ACCOUNT_DB_NAME <<< "select * from worlds order by id;select sum(online_user) from worlds;"
}

DiskSpace () { # ServerStatus -> Report the disk spece usage
   sendscript allall <<< 'df -h .|grep -a "% /"|awk "{print \"Used:\"\$(NF-3)\"(\"\$(NF-1)\"), Free:\"\$(NF-2)}"'
}

WZTraffic () { # ServerStatus -> Show current traffic on all WZ servers
   sendscript allwz <<< "traffic $WZ_EXT_IF"
}

DBConnCheck () { # ServerStatus -> Check the database connections between servers
   echo "Checking connect to ACCOUNTDB:" | colorize cyan
   sendscript all nohostname <<< "source ~/.gamerc;echo -en 'Connect from '\$HOST_NAME' to ACCOUNTDB ...                        '|head -c 55|colorize yellow;PGPASSWORD='$LIVE_SERVER_DB_PASSWORD' psql -t -h ACCOUNTDB $ACCOUNT_DB_NAME spiritking <<< '\q' && echo 'Return '\$?', OK'|colorize green || echo 'Return '\$?', FAILED, maybe unable to connect or no permission.'|colorize red"
   echo "Checking connect to GAMEDBs:" | colorize cyan
   for set in $SET_NUMBER_LIST;do
	sendscript set${set}wz nohostname <<< "source ~/.gamerc;echo -en 'Connect from '\$HOST_NAME' to GAMEDB$set ...                      '|head -c 55|colorize yellow;PGPASSWORD='$LIVE_SERVER_DB_PASSWORD' psql -t -h GAMEDB$set $GAME_DB_NAME$set spiritking <<< '\q' && echo 'Return '\$?', OK'|colorize green || echo 'Return '\$?', FAILED, maybe unable to connect or no permission.'|colorize red"
   done
}

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

GCPFW () { # CloudServices -> Firewall Setting for GCP
   echo "Allow ports: "
   sendscript allall nohosname <<< "cat ~/.ports_allow 2> /dev/null" | sort | uniq | awk "{printf \"tcp:\"\$1\"; \"}END{print \"\"}"
   echo "Internal only ports(GMTools and FastCGI): "
   sendscript allall nohosname <<< "cat ~/.ports_internal_only 2> /dev/null" | sort | uniq | awk "{printf \"tcp:\"\$1\"; \"}END{print \"\"}"
}

PMStart () { # PerfMonitor -> Start Perf and Create Snapshot every 10 seconds
   echo "Perf Monitor Start"
   sendscript allall <<< "cd /tmp/; nohup $HOME/bin/open_perf &"
}

PMStop () { # PerfMonitor -> Stop Perf and Stop Snapshot Catching
   echo "Perf Monitor Stop"
   sendscript allall <<< "cd /tmp/; nohup $HOME/bin/close_perf &"
}

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


###################################
# Start run the Command from here #
###################################
if [ "$ACTION" == "show_help" ] ; then
	[ -f ~/.hosts ] && cat ~/.hosts ~/bin/hosts > /etc/hosts 2> /dev/null
	echo "Notice: /etc/hosts updated!" | colorize green
	show_help
else
	if grep -a -q "$ACTION" <<< "$DONT_ASK_YES_NO" ; then
		$ACTION
	else
		yesno2 $ACTION "$DESCRIPTION"
	fi
fi

rm -f $CUSTFUNC

# 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\tARG:$*" >> "$CTRL_LOGFILE"

ulogger $0 =End= $DO $ANSWER <<< $*
