#!/usr/bin/env bash
# 請在合併後, 更新 hosts 前處理

# 檢查至少要有 4 個參數：
# No.1: 環境 ( test / live )
# No.2: 移動的目錄位置
# No.3: target world_id
# No.4: source world_ids

if [ $# -lt 4 ]; then
  echo "用法: $0 <environment:test/live> <dest_directory> <target_world_id> <source_world_id1> [source_world_id2 ...]" >&2
  exit 1
fi

# 第一個參數: 環境
environment="$1"
shift

# 第二個參數: 目錄位置
dest_directory="$1"
shift

# 第三個參數：target_world_id
target_world_id="$1"
shift

# 其餘參數：source_world_ids
source_world_ids_str=$*

# 將 source world id 相關的 Server 目錄做轉移
for world_id in $*; do
    SET_ID=$((world_id / 100))
    
    if [ "${environment}" == "live" ]; then
        MACHINE="WS${world_id}"
    elif [ "${environment}" == "test" ]; then
        if [ "${SET_ID}" -ge 10 ] && [ "${SET_ID}" -lt 20 ]; then
            MACHINE="MERGE_ASIA"
        elif [ "${SET_ID}" -ge 20 ] && [ "${SET_ID}" -lt 30 ]; then
            MACHINE="MERGE_US"
        elif [ "${SET_ID}" -ge 30 ] && [ "${SET_ID}" -lt 40 ]; then
            MACHINE="MERGE_EU"
        else
            exec echo "Unknown SET_ID ${SET_ID}"
        fi
    fi

    echo "ssh -o StrictHostKeyChecking=no ${MACHINE} \"mkdir -p $HOME/prepare/${dest_directory}/servers${SET_ID}\""
    ssh -o StrictHostKeyChecking=no ${MACHINE} "mkdir -p $HOME/prepare/${dest_directory}/servers${SET_ID}"

    remote_dir=$(ssh -o StrictHostKeyChecking=no ${MACHINE} "cd $HOME/servers${SET_ID}; ls -d *${world_id}*")
    for dir in ${remote_dir}; do
        echo "ssh -o StrictHostKeyChecking=no ${MACHINE} \"cd $HOME/servers${SET_ID}; mv ${dir} $HOME/prepare/${dest_directory}/servers${SET_ID}/.\""
        ssh -o StrictHostKeyChecking=no ${MACHINE} "cd $HOME/servers${SET_ID}; mv ${dir} $HOME/prepare/${dest_directory}/servers${SET_ID}/."
    done
done
