#!/usr/bin/env bash
# move_source_wids_directory_after_merge
# 合併後搬移 source world_ids 的 server 目錄到 prepare 目錄
# target world id 不處理

set -uo pipefail

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="$1"; shift  # target 不處理（保留參數但不使用）
source_world_ids=("$@")

SSH_OPT=(
  -o StrictHostKeyChecking=no
  -o BatchMode=yes
  -o ConnectTimeout=10
  -o ServerAliveInterval=10
  -o ServerAliveCountMax=3
)

log_ts() { date '+%Y-%m-%d %H:%M:%S'; }
log_info() { echo "[${0##*/}] $(log_ts) INFO: $*"; }
log_moved() { echo "[${0##*/}] $(log_ts) MOVED: $*"; }
log_error() { echo "[${0##*/}] $(log_ts) ERROR: $*" >&2; }

# 依 MERGE_MODE + SET_ID 取得 test 環境的機器名
_get_test_machine() {
  local sid="$1"
  case "${MERGE_MODE:-single}" in
    single)
      echo "MERGE"
      ;;
    multiple)
      if   [ "$sid" -ge 10 ] && [ "$sid" -lt 20 ]; then echo "MERGE_ASIA"
      elif [ "$sid" -ge 20 ] && [ "$sid" -lt 30 ]; then echo "MERGE_US"
      elif [ "$sid" -ge 30 ] && [ "$sid" -lt 40 ]; then echo "MERGE_EU"
      else return 1
      fi
      ;;
    *)
      echo "Error: unknown MERGE_MODE '${MERGE_MODE}'" >&2
      return 1
      ;;
  esac
}

fail_count=0

for world_id in "${source_world_ids[@]}"; do
  if ! [[ "${world_id}" =~ ^[0-9]+$ ]]; then
    log_error "world_id 必須是數字：${world_id}"
    fail_count=$((fail_count + 1))
    continue
  fi

  SET_ID=$((world_id / 100))

  if [ "${environment}" == "live" ]; then
    MACHINE="WS${world_id}"
  elif [ "${environment}" == "test" ]; then
    MACHINE="$(_get_test_machine "$SET_ID")" || {
      log_error "Unknown SET_ID ${SET_ID} (world_id=${world_id})"
      fail_count=$((fail_count + 1))
      continue
    }
  else
    log_error "Unknown environment ${environment}, must be test or live"
    exit 1
  fi

  log_info "START world_id=${world_id} SET_ID=${SET_ID} MACHINE=${MACHINE} DEST=\$HOME/prepare/${dest_directory}/servers${SET_ID}"

  # 在遠端一次完成：匹配(保留修正) -> 逐筆 mv -> 印出 MOVED/ERROR
  # 保留你要求的「避免誤判」修正：
  #   world_id 左側必須是開頭或非數字：避免 1121 誤中 11121/11211
  #   右側允許數字：可命中 ...11061 / ...11111
  output=$(
    ssh "${SSH_OPT[@]}" "${MACHINE}" "bash -lc '
      set -u
      src=\"\$HOME/servers${SET_ID}\"
      dest=\"\$HOME/prepare/${dest_directory}/servers${SET_ID}\"
      regex=\"(^|[^0-9])${world_id}\"

      mkdir -p \"\$dest\" || { echo \"ERROR\\tMKDIR\\t\$dest\"; exit 0; }
      cd \"\$src\" 2>/dev/null || { echo \"INFO\\tNO_SRC\\t\$src\"; exit 0; }

      moved=0
      matched=0

      shopt -s nullglob
      for d in *; do
        [[ -d \"\$d\" ]] || continue
        if [[ \"\$d\" =~ \$regex ]]; then
          matched=\$((matched+1))
          if mv \"\$d\" \"\$dest/.\"; then
            moved=\$((moved+1))
            echo \"MOVED\\t\$d\\t->\\t\$dest/\"
          else
            echo \"ERROR\\tMV_FAIL\\t\$d\\t->\\t\$dest/\"
          fi
        fi
      done

      if [ \"\$matched\" -eq 0 ]; then
        echo \"INFO\\tNO_MATCH\\tworld_id=${world_id}\\t\$src\"
      else
        echo \"INFO\\tSUMMARY\\tworld_id=${world_id}\\tmatched=\$matched\\tmoved=\$moved\"
      fi
      exit 0
    '"
  ) || {
    log_error "ssh failed (MACHINE=${MACHINE}, world_id=${world_id}, SET_ID=${SET_ID})"
    fail_count=$((fail_count + 1))
    continue
  }

  # 將遠端輸出轉成本機 log（不影響流程）
  while IFS= read -r line; do
    [ -n "${line}" ] || continue
    case "${line}" in
      MOVED$'\t'*)
        log_moved "machine=${MACHINE} world_id=${world_id} set_id=${SET_ID} ${line#MOVED	}"
        ;;
      ERROR$'\t'*)
        log_error "machine=${MACHINE} world_id=${world_id} set_id=${SET_ID} ${line#ERROR	}"
        fail_count=$((fail_count + 1))
        ;;
      INFO$'\t'*)
        log_info "machine=${MACHINE} world_id=${world_id} set_id=${SET_ID} ${line#INFO	}"
        ;;
      *)
        log_info "machine=${MACHINE} world_id=${world_id} set_id=${SET_ID} ${line}"
        ;;
    esac
  done <<< "${output}"

  log_info "END world_id=${world_id} SET_ID=${SET_ID} MACHINE=${MACHINE}"
done

if [ "${fail_count}" -gt 0 ]; then
  log_error "DONE with errors: fail_count=${fail_count}"
  exit 2
fi

log_info "DONE OK"
exit 0
