#!/bin/bash
source $HOME/.gamerc

NEW_SET_ID="$1"
XLUSER_ID="$2"
AID="$3"

START_DATETIME=$(date)
echo "====== BEGIN ======" | colorize white black
echo "${START_DATETIME}" | colorize white magenta

echo "Get Database ..." | colorize white green
DBFILE=$(ssh GAMEDB${NEW_SET_ID} "cd \$HOME/DBbackup/; ls \${GAME_TYPE}DB* | tail -n 1")
DBNAME=$(ssh GAMEDB${NEW_SET_ID} "cd \$HOME/DBbackup/; ls \${GAME_TYPE}DB* | tail -n 1 | awk -F\"T\" '{print \$1}' | sed 's/-/_LIVE_/'")

echo "Transfer Database File ..." | colorize white green
echo "DBFILE: ${DBFILE}, DBNAME: ${DBNAME}" 
rsync -avz GAMEDB${NEW_SET_ID}:$HOME/DBbackup/${DBFILE} /tmp/

echo "Restore Database ..." | colorize white green
psql -U postgres -c "CREATE DATABASE \"${DBNAME}\" ENCODING \"SQL_ASCII\" template=template0;"
pg_restore -U postgres -d ${DBNAME} < /tmp/${DBFILE}

echo "Change Set ID ..." | colorize white yellow
ORIGINAL_SET_ID=$(psql -U postgres ${GAME_TYPE}Account -c "COPY (SELECT DISTINCT id/1000 FROM worlds ORDER BY id/1000 DESC LIMIT 1) TO STDOUT;")
set_server_id change ${ORIGINAL_SET_ID} ${NEW_SET_ID} norestart
pg_dump -U postgres ${GAME_TYPE}DB1 -t serverstatus --insert | grep ^INSERT > /tmp/mapping_db_serverstatus.sql

echo "Modify Database ..." | colorize white red
echo "serverstatus" | colorize black blue
psql -U postgres ${DBNAME} -c "TRUNCATE serverstatus;"
psql -U postgres ${DBNAME} -c "\i /tmp/mapping_db_serverstatus.sql;"
echo "node_stream" | colorize black blue
psql -U postgres ${DBNAME} -c "UPDATE node_stream SET world_id = '${NEW_SET_ID}020';"
echo "player_elfisland" | colorize black blue
psql -U postgres ${DBNAME} -c "UPDATE player_elfisland SET worldserver = ${NEW_SET_ID}020;"
echo "family" | colorize black blue
psql -U postgres ${DBNAME} -c "UPDATE family SET worldserver = ${NEW_SET_ID}020;"
echo "setup.ini" | colorize black blue
sed -i "s/GameDB=.*/GameDB=$DBNAME/" ~/servers1/setup.ini

echo "Mapping Account ..." | colorize white red
psql -U postgres ${GAME_TYPE}Account -c "UPDATE accounts SET id = ${AID} WHERE username = '${XLUSER_ID}';"

echo "Start Mapping Servers ..." | colorize white cyan
yes | TestCtrl restart

END_DATETIME=$(date)
echo "====== END ======" | colorize white black
echo "${END_DATETIME}" | colorize white magenta

rm -rf /tmp/${DBFILE}
