#!/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

# 取得目前機器上存在的 serversXX
declare -A servers_exist=()
for d in "$HOME"/servers*; do
  [[ -d "$d" ]] || continue
  b="$(basename "$d")"
  sid="${b#servers}"
  [[ "$sid" =~ ^[0-9]+$ ]] || continue
  servers_exist["$sid"]=1
done

# 從 merge 檔計算 set_id（world_id/100），並與本機 serversXX 取交集
declare -A set_in_file=()
while read -r tok; do
  [[ "$tok" =~ ^[0-9]+$ ]] || continue
  sid=$((10#$tok / 100))
  [[ -n "${servers_exist[$sid]+x}" ]] || continue
  set_in_file["$sid"]=1
done < <(tr -s '[:space:]' '\n' < "$file")

set_list="$(printf '%s\n' "${!set_in_file[@]}" | sort -n | xargs)"
echo "SET_LIST_IN_FILE=${set_list}"

# 沒有任何可處理 set 就結束
if [[ -z "$set_list" ]]; then
  exit 0
fi

# 1) 先針對這些 SET 全刪三種 GameServers 目錄（確保乾淨）
for sid in $set_list; do
  set_dir="$HOME/servers${sid}"
  [[ -d "$set_dir" ]] || continue
  echo "CLEAN_SET_ID=${sid}"

  find "$set_dir" -maxdepth 1 -mindepth 1 \
    \( -name 'World*' -o -name 'WHTTPAServer*' -o -name 'WWebSocketProxyServer*' \) \
    -exec rm -rf -- {} +
done

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

# 2) 開始建立（只針對 set_list）
for sid in $set_list; do
  set_dir="$HOME/servers${sid}"
  [[ -d "$set_dir" ]] || continue

  SET_ID="$sid"
  echo "$set_dir"
  echo "SET_ID: ${SET_ID}"

  # 依 world_id/100 取出該 SET 的 world_id，並排序
  sorted_wid_lists="$(
    awk -v sid="$SET_ID" '
      {
        for (i=1; i<=NF; i++) {
          if ($i ~ /^[0-9]+$/) {
            wid = $i + 0
            if (int(wid/100) == sid) print wid
          }
        }
      }
    ' "$file" | sort -n | xargs
  )"
  echo "sorted_wid_lists: ${sorted_wid_lists}"

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

  read -r -a sorted_wid_list_arr <<< "${sorted_wid_lists}"
  echo "sorted_wid_list_arr: ${sorted_wid_list_arr[*]}"

  external_ip="$(curl -s icanhazip.com || true)"
  internal_ip="$(/sbin/ifconfig ens4 | grep 'inet' | grep -v 'inet6' | awk -F' ' '{print $2}' | awk '{print $1}')"

  # WorldServer
  is_first=1
  for wid in "${sorted_wid_list_arr[@]}"; do
    if (( is_first )); then
      echo "First WorldID: ${wid}"
      is_first=0

      port="${WORLD_PORT_NEXT}"
      OLD_ID="${wid}"
      OLD_PORT="${port}"

      # 關鍵：DEST 不存在時 cp 才會把 template 內容攤平到 DEST（符合你原始腳本結構）
      rm -rf -- "$set_dir/WorldServer${wid}"
      cp -arf "$HOME/bin/test_merge_world_directory_template/WorldServerTemplate" "$set_dir/WorldServer${wid}"

      mv "$set_dir/WorldServer${wid}/WorldServerTemplate" "$set_dir/WorldServer${wid}/WorldServer${wid}"
      sed -i "s/WorldServerTemplate/WorldServer${wid}/" "$set_dir/WorldServer${wid}/auto_start"
      sed -i \
        "s/Template/${wid}/g;\
s/WorldDBIP=/WorldDBIP=${internal_ip}/;\
s/WorldHttpServerIP=/WorldHttpServerIP=${internal_ip}/;\
s/ExtWorldServerIP=/ExtWorldServerIP=${external_ip}/;\
s/WorldHttpServerPort=[0-9]\\+/WorldHttpServerPort=${port}/" \
        "$set_dir/WorldServer${wid}/setup.ini"

      WORLD_PORT_NEXT=$((WORLD_PORT_NEXT + 1))
    else
      echo "Others WorldID: ${wid}"
      NEW_ID="${wid}"
      NEW_PORT="${WORLD_PORT_NEXT}"

      cp -arf "$set_dir/WorldServer${OLD_ID}" "$set_dir/WorldServer${NEW_ID}"
      mv "$set_dir/WorldServer${NEW_ID}/WorldServer${OLD_ID}" "$set_dir/WorldServer${NEW_ID}/WorldServer${NEW_ID}"
      sed -i "s/WorldServer${OLD_ID}/WorldServer${NEW_ID}/" "$set_dir/WorldServer${NEW_ID}/auto_start"
      sed -i \
        "s/WorldDBName=N1World${OLD_ID}/WorldDBName=N1World${NEW_ID}/g;\
s/WorldServerID=${OLD_ID}/WorldServerID=${NEW_ID}/g;\
s/WorldHttpServerPort=${OLD_PORT}/WorldHttpServerPort=${NEW_PORT}/g" \
        "$set_dir/WorldServer${NEW_ID}/setup.ini"

      OLD_ID="${NEW_ID}"
      OLD_PORT="${NEW_PORT}"
      WORLD_PORT_NEXT=$((WORLD_PORT_NEXT + 1))
    fi
  done

  # WorldHTTPAgent
  is_first=1
  for wid in "${sorted_wid_list_arr[@]}"; do
    if (( is_first )); then
      echo "First WorldHTTPAgentID: ${wid}"
      is_first=0

      port="${HTTPA_PORT_NEXT}"
      OLD_ID="${wid}"
      OLD_PORT="${port}"

      rm -rf -- "$set_dir/WHTTPAServer${wid}1"
      cp -arf "$HOME/bin/test_merge_world_directory_template/WHTTPAServerTemplate1" "$set_dir/WHTTPAServer${wid}1"

      mv "$set_dir/WHTTPAServer${wid}1/WHTTPAServerTemplate1" "$set_dir/WHTTPAServer${wid}1/WHTTPAServer${wid}1"
      sed -i "s/WHTTPAServerTemplate1/WHTTPAServer${wid}1/" "$set_dir/WHTTPAServer${wid}1/auto_start"
      sed -i \
        "s/BillingGatewayIP=/BillingGatewayIP=${internal_ip}/;\
s/BillingGatewayPort=[0-9]\\+/BillingGatewayPort=${port}/" \
        "$set_dir/WHTTPAServer${wid}1/setup.ini"

      HTTPA_PORT_NEXT=$((HTTPA_PORT_NEXT + 1))
    else
      echo "Others WorldHTTPAgentID: ${wid}"
      NEW_ID="${wid}"
      NEW_PORT="${HTTPA_PORT_NEXT}"

      cp -arf "$set_dir/WHTTPAServer${OLD_ID}1" "$set_dir/WHTTPAServer${NEW_ID}1"
      mv "$set_dir/WHTTPAServer${NEW_ID}1/WHTTPAServer${OLD_ID}1" "$set_dir/WHTTPAServer${NEW_ID}1/WHTTPAServer${NEW_ID}1"
      sed -i "s/WHTTPAServer${OLD_ID}1/WHTTPAServer${NEW_ID}1/" "$set_dir/WHTTPAServer${NEW_ID}1/auto_start"
      sed -i "s/BillingGatewayPort=${OLD_PORT}/BillingGatewayPort=${NEW_PORT}/" \
        "$set_dir/WHTTPAServer${NEW_ID}1/setup.ini"

      OLD_ID="${NEW_ID}"
      OLD_PORT="${NEW_PORT}"
      HTTPA_PORT_NEXT=$((HTTPA_PORT_NEXT + 1))
    fi
  done

  # WWebSocketProxyServer
  is_first=1
  for wid in "${sorted_wid_list_arr[@]}"; do
    if (( is_first )); then
      echo "First WWebSocketProxyID: ${wid}"
      is_first=0

      port="${WSP_PORT_NEXT}"
      OLD_ID="${wid}"
      OLD_PORT="${port}"

      rm -rf -- "$set_dir/WWebSocketProxyServer${wid}1"
      cp -arf "$HOME/bin/test_merge_world_directory_template/WWebSocketProxyServerTemplate1" "$set_dir/WWebSocketProxyServer${wid}1"

      mv "$set_dir/WWebSocketProxyServer${wid}1/WWebSocketProxyServerTemplate1" \
         "$set_dir/WWebSocketProxyServer${wid}1/WWebSocketProxyServer${wid}1"
      sed -i "s/WWebSocketProxyServerTemplate1/WWebSocketProxyServer${wid}1/" \
        "$set_dir/WWebSocketProxyServer${wid}1/auto_start"
      sed -i \
        "s/WebSocketProxyServer=0.0.0.0:[0-9]\\+/WebSocketProxyServer=0.0.0.0:${port}/g" \
        "$set_dir/WWebSocketProxyServer${wid}1/setup.ini"

      WSP_PORT_NEXT=$((WSP_PORT_NEXT + 1))
    else
      echo "Others WWebSocketProxyID: ${wid}"
      NEW_ID="${wid}"
      NEW_PORT="${WSP_PORT_NEXT}"

      cp -arf "$set_dir/WWebSocketProxyServer${OLD_ID}1" "$set_dir/WWebSocketProxyServer${NEW_ID}1"
      mv "$set_dir/WWebSocketProxyServer${NEW_ID}1/WWebSocketProxyServer${OLD_ID}1" \
         "$set_dir/WWebSocketProxyServer${NEW_ID}1/WWebSocketProxyServer${NEW_ID}1"
      sed -i "s/WWebSocketProxyServer${OLD_ID}1/WWebSocketProxyServer${NEW_ID}1/" \
        "$set_dir/WWebSocketProxyServer${NEW_ID}1/auto_start"
      sed -i \
        "s/WebSocketProxyServer=0.0.0.0:${OLD_PORT}/WebSocketProxyServer=0.0.0.0:${NEW_PORT}/g" \
        "$set_dir/WWebSocketProxyServer${NEW_ID}1/setup.ini"

      OLD_ID="${NEW_ID}"
      OLD_PORT="${NEW_PORT}"
      WSP_PORT_NEXT=$((WSP_PORT_NEXT + 1))
    fi
  done
done

