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

if [[ $# -lt 2 ]]; then
    echo "Usage: $0 <MERGE_WORLD_ID_LISTS: TARGET_WID SOURCE_WID_LISTS>" >&2
    exit 1
fi

DB_ACCOUNT=$PGUSER
DB_PASS=$LIVE_SERVER_DB_PASSWORD

SET_ID=$(( $1 / 100 ))
#echo "SET_ID: ${SET_ID}"

for world_id in $*; do
    check_set_id=$(( world_id / 100 ))
    if [ "${check_set_id}" -ne "${SET_ID}" ]; then
        exec echo "${world_id} is not equal to SET_ID ${SET_ID}"
    fi
done

ACCOUNTDB_INT_IP=$(HOST="ACCOUNTDB"; awk -v h="${HOST}" '$0 ~ h {print $1}' /etc/hosts)
GAMEDB_INT_IP=$(HOST="GAMEDB${SET_ID}"; awk -v h="${HOST}" '$0 ~ h {print $1}' /etc/hosts)

OUTPUT=""

### Title Section ###
OUTPUT+=$(cat <<TITLE
[Common]
TITLE
)

# 額外補上一個換行
OUTPUT+=$'\n'

### AccountDB Section ###
OUTPUT+=$(cat <<ACCOUNTDB
AccountDBIP=${ACCOUNTDB_INT_IP}
AccountDBName=${ACCOUNT_DB_NAME}
AccountDBUser=${DB_ACCOUNT}
AccountDBPW=${DB_PASS}
ACCOUNTDB
)

# 額外補上二個換行
OUTPUT+=$'\n\n'

### GameDB Section ###
OUTPUT+=$(cat <<GAMEDB
GameDBIP=${GAMEDB_INT_IP}
GameDB=${GAME_DB_NAME}${SET_ID}
GameDBUser=${DB_ACCOUNT}
GameDBPassword=${DB_PASS}
GAMEDB
)

# 額外補上二個換行
OUTPUT+=$'\n\n'

### WorldDB Section ###
for world_id in $*; do
WORLD_INT_IP=$(HOST="WS${world_id}"; awk -v h="${HOST}" '$0 ~ h {print $1}' /etc/hosts)
OUTPUT+=$(cat <<WORLDDB
WorldID=${world_id}
WorldDBIP=${WORLD_INT_IP}
WorldDBName=${WORLD_DB_NAME}${world_id}
WorldDBUser=${DB_ACCOUNT}
WorldDBPassword=${DB_PASS}
WORLDDB
)
# 額外補上二個換行
OUTPUT+=$'\n\n'
done

echo "${OUTPUT}"
