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

set -euo pipefail

# 檢查至少要有 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
            echo "Unknown SET_ID ${SET_ID}" >&2
            exit 1
        fi
    else
        echo "Unknown environment ${environment}, must be test or live" >&2
        exit 1
    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}\""

    # 修正：避免 world_id 子字串誤判（例如 1121 命中 11121/11211）
    # 只匹配：world_id 前後都不能是數字（等同數字 token 邊界）
    remote_dir=$(ssh -o StrictHostKeyChecking=no "${MACHINE}" \
      "bash -lc 'shopt -s nullglob; cd \"\$HOME/servers${SET_ID}\" || exit 0;
                for d in *; do
                  [[ -d \"\$d\" ]] || continue
                  [[ \"\$d\" =~ (^|[^0-9])${world_id}([^0-9]|$) ]] && printf \"%s\n\" \"\$d\"
                done'")

    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

