#!/bin/bash
set -euo pipefail
shopt -s nullglob

# 檢查參數數量
if [[ "$#" -ne 1 ]]; then
  echo "用法: $0 <merge_filename>" >&2
  exit 1
fi

merge_filename="$1"
file="$HOME/bin/merge_n1/test/${merge_filename}"

# 檢查檔案是否存在
if [[ ! -f "$file" ]]; then
  echo "找不到檔案: $file" >&2
  exit 1
fi

dirs=( "$HOME"/servers* )
if (( ${#dirs[@]} == 0 )); then
  echo "-1"
  exit 0
fi

# PORT 需跨 SET 連續遞增（各 Server 類型獨立計數）
WORLD_PORT_NEXT=1236
HTTPA_PORT_NEXT=1236
WSP_PORT_NEXT=8665

for d in "${dirs[@]}"; do
  [[ -d "$d" ]] || continue

  SET_ID="$(basename "$d" | sed 's/servers//')"
  echo "SET_ID=${SET_ID}"

  original_wid_lists="$(cat "$file" \
    | grep -E "^${SET_ID}| ${SET_ID}" \
    | tr '\n' ' ' \
    | sed 's/  / /g;s/ $//')"

  if [[ -z "${original_wid_lists}" ]]; then
    echo "  (no world_id)"
    continue
  fi

  sorted_wid_lists="$(printf '%s\n' ${original_wid_lists} | sort -n | xargs)"
  read -r -a sorted_wid_list_arr <<< "${sorted_wid_lists}"

  # WorldServer
  for wid in "${sorted_wid_list_arr[@]}"; do
    echo "  ${SET_ID} | WorldServer${wid} | ${WORLD_PORT_NEXT}"
    WORLD_PORT_NEXT=$((WORLD_PORT_NEXT + 1))
  done

  # WorldHTTPAgent
  for wid in "${sorted_wid_list_arr[@]}"; do
    echo "  ${SET_ID} | WHTTPAServer${wid}1 | ${HTTPA_PORT_NEXT}"
    HTTPA_PORT_NEXT=$((HTTPA_PORT_NEXT + 1))
  done

  # WWebSocketProxyServer
  for wid in "${sorted_wid_list_arr[@]}"; do
    echo "  ${SET_ID} | WWebSocketProxyServer${wid}1 | ${WSP_PORT_NEXT}"
    WSP_PORT_NEXT=$((WSP_PORT_NEXT + 1))
  done
done

