#!/usr/bin/env bash
# GBS 本地开发 Dubbo 代理刷新脚本（方案 C）
# 在 192.168.20.100 上运行：将固定端口转发到当前 Pod IP:20880
# 不修改 K8s / Nacos 注册，仅做主机级 TCP 代理

set -euo pipefail

NAMESPACE="${NAMESPACE:-jjb-dragon}"
BIND_ADDR="${BIND_ADDR:-0.0.0.0}"
MAP_FILE="${MAP_FILE:-/opt/dubbo-dev-proxy/dubbo-proxy.map}"
PID_DIR="${PID_DIR:-/var/run/dubbo-dev-proxy}"
LOG_DIR="${LOG_DIR:-/var/log/dubbo-dev-proxy}"
KUBECTL="${KUBECTL:-kubectl}"

mkdir -p "$PID_DIR" "$LOG_DIR"

if ! command -v socat >/dev/null 2>&1; then
  echo "[ERROR] socat 未安装，请先执行 dubbo-proxy-install.sh" >&2
  exit 1
fi

if [[ ! -f "$MAP_FILE" ]]; then
  echo "[ERROR] 映射文件不存在: $MAP_FILE" >&2
  exit 1
fi

stop_one() {
  local port="$1"
  local pid_file="${PID_DIR}/${port}.pid"
  if [[ -f "$pid_file" ]]; then
    local pid
    pid="$(cat "$pid_file" 2>/dev/null || true)"
    if [[ -n "$pid" ]] && kill -0 "$pid" 2>/dev/null; then
      kill "$pid" 2>/dev/null || true
      sleep 0.2
      kill -9 "$pid" 2>/dev/null || true
    fi
    rm -f "$pid_file"
  fi
}

start_one() {
  local port="$1"
  local pod_label="$2"
  local target_port="$3"

  local pod_ip
  pod_ip="$($KUBECTL get pods -n "$NAMESPACE" -l "app=${pod_label}" \
    --field-selector=status.phase=Running \
    -o jsonpath='{.items[0].status.podIP}' 2>/dev/null || true)"

  if [[ -z "$pod_ip" ]]; then
    echo "[WARN] ${pod_label} 无 Running Pod，跳过端口 ${port}"
    stop_one "$port"
    return 0
  fi

  stop_one "$port"

  nohup socat \
    "TCP-LISTEN:${port},bind=${BIND_ADDR},fork,reuseaddr" \
    "TCP:${pod_ip}:${target_port}" \
    >> "${LOG_DIR}/${port}.log" 2>&1 &

  echo $! > "${PID_DIR}/${port}.pid"
  echo "[OK] ${port} -> ${pod_ip}:${target_port} (${pod_label})"
}

echo "=== dubbo-dev-proxy refresh $(date '+%F %T') ==="

while IFS= read -r line || [[ -n "$line" ]]; do
  [[ -z "$line" || "$line" =~ ^[[:space:]]*# ]] && continue
  IFS='|' read -r local_port pod_label target_port <<< "$line"
  [[ -z "$local_port" || -z "$pod_label" || -z "$target_port" ]] && continue
  start_one "$local_port" "$pod_label" "$target_port"
done < "$MAP_FILE"

echo "=== done ==="
