#!/bin/bash
set -euo pipefail

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

merge_filename="$1"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
file="${SCRIPT_DIR}/merge_n1/test/${merge_filename}"

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

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

# 動態組 worlds 重置的 SET 句
# - 固定 5 個欄位永遠都 set
# - world_info / set_info / region_info 只在 worlds 表確實有該欄位時才加
build_worlds_reset_set() {
    local parts=(
        "wsproxy = NULL"
        "nochar_block_login = NULL"
        "online_user = 0"
        "time_zone = 'MERGE_'||time_zone"
        "state = 0"
    )
    local col
    for col in world_info set_info region_info; do
        local exists
        exists=$(psql -U postgres -tAc \
            "SELECT 1 FROM information_schema.columns WHERE table_schema='public' AND table_name='worlds' AND column_name='${col}'" \
            N1Account)
        if [[ "${exists}" == "1" ]]; then
            parts+=("${col} = NULL")
        fi
    done
    local IFS=,
    echo "${parts[*]}"
}

WORLDS_RESET_SET=$(build_worlds_reset_set)
echo "[test_merge_update_worlds_n1] worlds 重置 SET: ${WORLDS_RESET_SET}"

case "${MERGE_MODE:-single}" in
  single)
    # Single: 一台 MERGE 機，取一組 IP，全域 port 序列
    MERGE_EXTERNAL_IP=$(ssh -o StrictHostKeyChecking=no MERGE "curl -s icanhazip.com")
    MERGE_INTERNAL_IP=$(ssh -o StrictHostKeyChecking=no MERGE "ip -4 addr show | grep -v '127.0.0.1' | grep 'inet ' | head -1 | awk '{print \$2}' | cut -d/ -f1")

    psql -U postgres N1Account -c "UPDATE worlds SET ${WORLDS_RESET_SET};"
    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 = '${MERGE_EXTERNAL_IP}', int_ip = '${MERGE_INTERNAL_IP}';"
    psql -U postgres N1Account -c "WITH ordered AS (
        SELECT
            id,
            row_number() OVER (ORDER BY id) - 1 AS n
        FROM worlds
    )
    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;"
    ;;

  multiple)
    # Multiple: 3 台地區機，各自取 IP，各區間獨立 port 序列
    MERGE_ASIA_EXTERNAL_IP=$(ssh -o StrictHostKeyChecking=no MERGE_ASIA "curl -s icanhazip.com")
    MERGE_US_EXTERNAL_IP=$(ssh -o StrictHostKeyChecking=no MERGE_US "curl -s icanhazip.com")
    MERGE_EU_EXTERNAL_IP=$(ssh -o StrictHostKeyChecking=no MERGE_EU "curl -s icanhazip.com")
    MERGE_ASIA_INTERNAL_IP=$(ssh -o StrictHostKeyChecking=no MERGE_ASIA "ip -4 addr show | grep -v '127.0.0.1' | grep 'inet ' | head -1 | awk '{print \$2}' | cut -d/ -f1")
    MERGE_US_INTERNAL_IP=$(ssh -o StrictHostKeyChecking=no MERGE_US "ip -4 addr show | grep -v '127.0.0.1' | grep 'inet ' | head -1 | awk '{print \$2}' | cut -d/ -f1")
    MERGE_EU_INTERNAL_IP=$(ssh -o StrictHostKeyChecking=no MERGE_EU "ip -4 addr show | grep -v '127.0.0.1' | grep 'inet ' | head -1 | awk '{print \$2}' | cut -d/ -f1")

    psql -U postgres N1Account -c "UPDATE worlds SET ${WORLDS_RESET_SET};"
    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 = '${MERGE_ASIA_EXTERNAL_IP}', int_ip = '${MERGE_ASIA_INTERNAL_IP}' WHERE id BETWEEN 1000 AND 2000;"
    psql -U postgres N1Account -c "UPDATE worlds SET ip = '${MERGE_US_EXTERNAL_IP}', int_ip = '${MERGE_US_INTERNAL_IP}' WHERE id BETWEEN 2000 AND 3000;"
    psql -U postgres N1Account -c "UPDATE worlds SET ip = '${MERGE_EU_EXTERNAL_IP}', int_ip = '${MERGE_EU_INTERNAL_IP}' 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
        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
        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
        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;"
    ;;

  *)
    echo "Error: unknown MERGE_MODE '${MERGE_MODE}'" >&2
    exit 1
    ;;
esac
