#!/bin/bash
set -euo pipefail

# 檢查參數數量
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

total=$(cat $HOME/bin/merge_n1/test/${merge_filename} | tr '\n' ' ')
comman_separated_sorted_total=$(printf '%s\n' ${total} | sort -n | xargs | sed 's/ /,/g')

psql -U postgres N1Account -c "UPDATE worlds SET wsproxy = NULL, nochar_block_login = NULL, world_info = NULL, set_info = NULL, region_info = NULL, online_user = 0, time_zone = 'MERGE_'||time_zone, state = 0;"
psql -U postgres N1Account -c "DELETE FROM worlds WHERE id NOT IN (${comman_separated_sorted_total});"
psql -U postgres N1Account -c "UPDATE worlds SET ip = '35.185.134.65', int_ip = '10.8.71.8' WHERE id BETWEEN 1000 AND 2000;"
psql -U postgres N1Account -c "UPDATE worlds SET ip = '34.60.71.37', int_ip = '10.8.72.8' WHERE id BETWEEN 2000 AND 3000;"
psql -U postgres N1Account -c "UPDATE worlds SET ip = '34.147.80.126', int_ip = '10.8.73.8' WHERE id BETWEEN 3000 AND 4000;"
psql -U postgres N1Account -c "WITH ordered AS (
    SELECT
        id,
        row_number() OVER (ORDER BY id) - 1 AS n  -- 只針對 1000~2000 編 n = 0,1,2,...
    FROM worlds
    WHERE id BETWEEN 1000 AND 2000
)
UPDATE worlds t
SET
    port = 5567 + o.n * 3,
    int_port = 5568 + o.n * 3,
    sub_port = 5569 + o.n * 3
FROM ordered o
WHERE t.id = o.id;"
psql -U postgres N1Account -c "WITH ordered AS (
    SELECT
        id,
        row_number() OVER (ORDER BY id) - 1 AS n  -- 只針對 2000~3000 編 n = 0,1,2,...
    FROM worlds
    WHERE id BETWEEN 2000 AND 3000
)
UPDATE worlds t
SET
    port = 5567 + o.n * 3,
    int_port = 5568 + o.n * 3,
    sub_port = 5569 + o.n * 3
FROM ordered o
WHERE t.id = o.id;"
psql -U postgres N1Account -c "WITH ordered AS (
    SELECT
        id,
        row_number() OVER (ORDER BY id) - 1 AS n  -- 只針對 3000~4000 編 n = 0,1,2,...
    FROM worlds
    WHERE id BETWEEN 3000 AND 4000
)
UPDATE worlds t
SET
    port = 5567 + o.n * 3,
    int_port = 5568 + o.n * 3,
    sub_port = 5569 + o.n * 3
FROM ordered o
WHERE t.id = o.id;"


