#!/usr/bin/env bash

# 檢查至少要有 3 個參數：
# No.1: 移動的目錄位置
# No.2: target world_id
# No.3: source world_ids

if [ $# -lt 3 ]; then
  echo "用法: $0 dest_directory target_world_id source_world_id1 [source_world_id2 ...]" >&2
  exit 1
fi

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

# 第二個參數：target_world_id（對應 setup_clone_with_backup 的第 1 個參數）
target_world_id="$1"
shift

# 其餘參數：source_world_ids（對應 setup_clone_with_backup 的 ARRAY[...]）
# 組成逗點區隔的字串 source_world_ids
source_world_ids_str=$*

# 輸出 CALL 語法
for world_id in $*; do
    SET_ID=$((world_id / 100))
    echo "ssh WS${world_id} \"mkdir -p $HOME/prepare/${dest_directory}/servers${SET_ID}\""
    ssh WS${world_id} "mkdir -p $HOME/prepare/${dest_directory}/servers${SET_ID}"

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