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

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

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

for world_id in "${@:2}"; 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

    if [ "${world_id}" -ge 4000 ]; then
        exec echo "Unknown WORLD_ID ${world_id}"
    fi
    WORLD_ID_LISTS_STR="${WORLD_ID_LISTS_STR}${world_id}_"
done
WORLD_ID_LISTS_STR=${WORLD_ID_LISTS_STR%_}

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)

cd $HOME/servers${SET_ID}
[ -d "${DIRECTORY_NAME}/${WORLD_ID_LISTS_STR}" ] && rm -rf "${DIRECTORY_NAME}/${WORLD_ID_LISTS_STR}"
mkdir -p "${DIRECTORY_NAME}/${WORLD_ID_LISTS_STR}"; echo "mkdir -p ${DIRECTORY_NAME}/${WORLD_ID_LISTS_STR}" | colorize green black; cd "${DIRECTORY_NAME}/${WORLD_ID_LISTS_STR}"
echo "Generate merge_setup.ini" | colorize yellow black
$HOME/bin/generate_merge_setup ${@:2} > merge_setup.ini
echo "Link MergeTool to GameDBserver" | colorize yellow black
ln -s ../../bin/GameDBServer MergeTool
echo "Generate merge script" | colorize red black
cat <<'EOF' >merge_exec
#!/bin/bash
#unlimit core

OLD_LOG_NUMBERS=$(find . -maxdepth 1 -type f \( -name "*log*" -o -name "*.source*" \) | wc -l)

if [ "${OLD_LOG_NUMBERS}" -gt 0 ]; then
        DIRECTORY_NAME=$(date +"%Y%m%d-%H%M%S")
        mkdir -p "${DIRECTORY_NAME}"

        if compgen -G '*log*' > /dev/null; then
                mv -- *log* "${DIRECTORY_NAME}/"
        fi

        if compgen -G '*.source' > /dev/null; then
                mv -- *.source "${DIRECTORY_NAME}/"
        fi

        if [ -e nohup.out ]; then
                mv -- nohup.out "${DIRECTORY_NAME}/"
        fi

        if compgen -G 'core*' > /dev/null; then
                mv -- core* "${DIRECTORY_NAME}/"
        fi
fi

./MergeTool -m >& Test.log &
EOF

chmod +x merge_exec
