#!/usr/bin/env bash
# Debian / Ubuntu：安装 Xray，并写入带账号密码与 UDP 的 SOCKS5 配置。
# 用法: sudo bash install-socks5.sh [--port 10808] [--user NAME] [--pass PASS]
set -euo pipefail

export LANG=C.UTF-8
export LC_ALL=C.UTF-8

JSON_PATH="/usr/local/etc/xray"
CONFIG="${JSON_PATH}/config.json"
XRAY="/usr/local/bin/xray"
CLASH_FILE="${JSON_PATH}/clash-verge.yaml"
ROCKET_FILE="${JSON_PATH}/shadowrocket.txt"
ROCKET_PNG="${JSON_PATH}/shadowrocket.png"
SUB_TOKEN_FILE="${JSON_PATH}/subscribe.token"
SUB_SERVER="/usr/local/lib/socks5-sub.py"
SUB_PORT=25500

PORT=""
USER_NAME=""
PASS=""
LISTEN=""
UPGRADE=0
FORCE=0
PORT_SET=0
USER_SET=0
PASS_SET=0
LISTEN_SET=0

usage() {
  cat <<'EOF'
用法: sudo bash install-socks5.sh [选项]

在 Debian 或 Ubuntu 上安装 Xray，并写入带账号密码和 UDP 的 SOCKS5 配置。
会放行代理端口的 TCP 和 UDP。启用系统防火墙前会先放行当前 SSH 端口。

选项:
  --port PORT     监听端口。省略时沿用已有配置，否则为 10808
  --user NAME     用户名。省略时沿用已有账号，没有则自动生成
  --pass PASS     密码。省略时沿用已有密码，没有则自动生成
  --listen ADDR   监听地址。省略时沿用已有配置，否则为 0.0.0.0
  --upgrade       已安装 Xray 时仍执行官方安装脚本以升级
  --force         现有配置不是单个 SOCKS 入站时仍覆盖（先备份）
  -h, --help      显示此说明

执行顺序：检查 Xray 是否已安装，未安装则安装；已安装但未配置则写入 SOCKS5；检查防火墙端口，未放行则放行；启动并设置开机自启；生成 Clash Verge 订阅并打印订阅地址。
要改账号、端口或升级 Xray 时，带上对应参数。
EOF
}

allow_firewall_port() {
  local port="$1"
  local ssh_port
  local seen=" "
  local ufw_state=""
  local -a ssh_ports=()
  local -a ssh_files=()

  if command -v firewall-cmd >/dev/null 2>&1 && systemctl is-active --quiet firewalld; then
    firewall-cmd --permanent --add-port="${port}/tcp"
    firewall-cmd --permanent --add-port="${port}/udp"
    firewall-cmd --reload
    echo "已在 firewalld 放行 ${port}/tcp 与 ${port}/udp。"
    return 0
  fi

  export DEBIAN_FRONTEND=noninteractive
  if ! command -v ufw >/dev/null 2>&1; then
    apt-get update -y
    apt-get install -y ufw
  fi

  ssh_ports+=(22)
  shopt -s nullglob
  ssh_files=(/etc/ssh/sshd_config /etc/ssh/sshd_config.d/*.conf)
  shopt -u nullglob
  if [[ "${#ssh_files[@]}" -gt 0 ]]; then
    while read -r ssh_port; do
      [[ -n "$ssh_port" ]] && ssh_ports+=("$ssh_port")
    done < <(awk 'tolower($1)=="port" {print $2}' "${ssh_files[@]}")
  fi
  if command -v ss >/dev/null 2>&1; then
    while read -r ssh_port; do
      [[ -n "$ssh_port" ]] && ssh_ports+=("$ssh_port")
    done < <(ss -H -lntp 2>/dev/null | awk '/sshd/ {n=$4; sub(/.*:/,"",n); print n}')
  fi

  for ssh_port in "${ssh_ports[@]}"; do
    [[ "$ssh_port" =~ ^[0-9]+$ ]] || continue
    [[ "$seen" == *" ${ssh_port} "* ]] && continue
    seen+="${ssh_port} "
    ufw allow "${ssh_port}/tcp" >/dev/null
  done

  ufw allow "${port}/tcp"
  ufw allow "${port}/udp"
  ufw_state="$(ufw status 2>/dev/null | head -n 1 || true)"
  if [[ "$ufw_state" == *inactive* ]]; then
    ufw --force enable
  fi
  ufw reload >/dev/null
  echo "已在 UFW 放行 ${port}/tcp 与 ${port}/udp。"
}

firewall_port_allowed() {
  local port="$1"
  local status=""

  if command -v firewall-cmd >/dev/null 2>&1 && systemctl is-active --quiet firewalld; then
    firewall-cmd --query-port="${port}/tcp" >/dev/null 2>&1 && firewall-cmd --query-port="${port}/udp" >/dev/null 2>&1
    return
  fi
  if ! command -v ufw >/dev/null 2>&1; then
    return 1
  fi
  status="$(ufw status 2>/dev/null || true)"
  [[ "$(printf '%s\n' "$status" | head -n 1)" == *inactive* ]] && return 1
  printf '%s\n' "$status" | grep -qE "^${port}/tcp([[:space:]]|\\()" \
    && printf '%s\n' "$status" | grep -qE "^${port}/udp([[:space:]]|\\()"
}

load_existing_socks() {
  local text=""
  local -a lines=()
  [[ -f "$CONFIG" ]] || return 1
  if ! text="$(python3 - "$CONFIG" <<'PY'
import json
import sys

with open(sys.argv[1], encoding="utf-8") as fh:
    cfg = json.load(fh)
inbounds = cfg.get("inbounds")
if not isinstance(inbounds, list) or len(inbounds) != 1 or not isinstance(inbounds[0], dict):
    sys.exit(1)
inbound = inbounds[0]
if inbound.get("protocol") != "socks":
    sys.exit(1)
settings = inbound.get("settings") if isinstance(inbound.get("settings"), dict) else {}
accounts = settings.get("accounts")
if not isinstance(accounts, list) or not accounts or not isinstance(accounts[0], dict):
    sys.exit(1)
user = accounts[0].get("user") or ""
password = accounts[0].get("pass") or ""
port = inbound.get("port")
if (
    not isinstance(user, str)
    or not isinstance(password, str)
    or not user
    or not password
    or any(ord(ch) < 32 for ch in user + password)
):
    sys.exit(1)
if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:
    sys.exit(1)
print(user)
print(password)
print(port)
PY
  )"; then
    return 1
  fi
  mapfile -t lines <<< "$text"
  [[ "${#lines[@]}" -ge 3 && -n "${lines[0]}" && -n "${lines[1]}" ]] || return 1
  USER_NAME="${lines[0]}"
  PASS="${lines[1]}"
  PORT="${lines[2]}"
}

tune_network() {
  local conf="/etc/sysctl.d/99-socks5-tune.conf"
  local cc=""

  modprobe tcp_bbr 2>/dev/null || true
  cat >"$conf" <<'EOF'
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
net.ipv4.udp_rmem_min = 16384
net.ipv4.udp_wmem_min = 16384
net.core.netdev_max_backlog = 16384
net.ipv4.tcp_fastopen = 3
net.ipv4.tcp_mtu_probing = 1
net.ipv4.tcp_slow_start_after_idle = 0
net.ipv4.tcp_notsent_lowat = 16384
EOF
  if ! grep -qw bbr /proc/sys/net/ipv4/tcp_available_congestion_control 2>/dev/null; then
    sed -i '/tcp_congestion_control/d' "$conf"
    echo "内核不支持 BBR，只应用 TCP 缓冲区参数。"
  fi
  sysctl -q -p "$conf" >/dev/null || true
  apply_fq_qdisc
  cc="$(sysctl -n net.ipv4.tcp_congestion_control 2>/dev/null || true)"
  echo "当前拥塞控制: ${cc:-unknown}，队列: $(sysctl -n net.core.default_qdisc 2>/dev/null || echo unknown)"
}

apply_fq_qdisc() {
  local iface=""
  iface="$(ip -4 route show default 2>/dev/null | awk '{for (i=1; i<=NF; i++) if ($i=="dev") {print $(i+1); exit}}' || true)"
  [[ -n "$iface" ]] || return 0
  if ! command -v tc >/dev/null 2>&1; then
    apt-get update -y
    apt-get install -y iproute2
  fi
  tc qdisc replace dev "$iface" root fq
  cat >/etc/systemd/system/fq-qdisc.service <<EOF
[Unit]
Description=Apply fq qdisc for BBR
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
ExecStart=/sbin/tc qdisc replace dev ${iface} root fq
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
EOF
  systemctl daemon-reload
  systemctl enable --now fq-qdisc.service >/dev/null
  echo "网卡 ${iface} 队列已切换为 fq。"
}

upgrade_existing_outbounds() {
  local tmp=""
  tmp="$(mktemp)"
  if ! python3 - "$CONFIG" "$tmp" <<'PY'
import json
import sys

src, dst = sys.argv[1], sys.argv[2]
with open(src, encoding="utf-8") as fh:
    cfg = json.load(fh)
outbounds = [
    {"tag": "direct", "protocol": "freedom", "settings": {"domainStrategy": "UseIPv4"}},
    {"tag": "block", "protocol": "blackhole"},
]
routing = {"rules": [{"type": "field", "ip": ["geoip:private"], "outboundTag": "block"}]}
if cfg.get("outbounds") == outbounds and cfg.get("routing") == routing:
    sys.exit(1)
cfg["outbounds"] = outbounds
cfg["routing"] = routing
with open(dst, "w", encoding="utf-8") as fh:
    json.dump(cfg, fh, indent=2, ensure_ascii=False)
    fh.write("\n")
PY
  then
    rm -f "$tmp"
    return 1
  fi
  if ! "$XRAY" run -test -config "$tmp" >/dev/null; then
    rm -f "$tmp"
    echo "优化后的出站配置未通过检查，保留原配置。"
    return 1
  fi
  cp -a "$CONFIG" "${CONFIG}.bak.$(date +%Y%m%d%H%M%S)"
  install -m 640 -o 0 -g xray "$tmp" "${CONFIG}.new"
  mv -f "${CONFIG}.new" "$CONFIG"
  rm -f "$tmp"
  echo "已更新出站配置：优先 IPv4，拒绝访问内网地址。"
}

start_xray() {
  local port="$1"
  local restart="$2"
  local listening=0
  local i

  if [[ ! -f /etc/systemd/system/xray.service ]]; then
    echo "未找到 xray 服务"
    exit 1
  fi

  systemctl daemon-reload
  systemctl enable xray
  if [[ "$restart" -eq 1 ]]; then
    systemctl restart xray
  elif ! systemctl is-active --quiet xray; then
    systemctl start xray
  fi
  if ! systemctl is-active --quiet xray; then
    systemctl status xray --no-pager -l || true
    journalctl -u xray -n 40 --no-pager || true
    echo "xray 服务未能启动"
    exit 1
  fi

  for ((i = 0; i < 25; i++)); do
    if ss -H -lntu sport = ":${port}" | grep -q .; then
      listening=1
      break
    fi
    sleep 0.2
  done
  if [[ "$listening" -ne 1 ]]; then
    systemctl status xray --no-pager -l || true
    echo "xray 已启动，但还没有看到 ${port} 端口处于监听状态"
    exit 1
  fi
  echo "xray 已启动，并已设置开机自启，正在监听 ${port}。"
}

allow_tcp_port() {
  local port="$1"
  if command -v firewall-cmd >/dev/null 2>&1 && systemctl is-active --quiet firewalld; then
    if ! firewall-cmd --query-port="${port}/tcp" >/dev/null 2>&1; then
      firewall-cmd --permanent --add-port="${port}/tcp"
      firewall-cmd --reload
    fi
    echo "已放行订阅端口 ${port}/tcp。"
    return 0
  fi
  if command -v ufw >/dev/null 2>&1; then
    if ! ufw status 2>/dev/null | grep -qE "^${port}/tcp([[:space:]]|\\()"; then
      ufw allow "${port}/tcp" >/dev/null
    fi
    echo "已放行订阅端口 ${port}/tcp。"
  fi
}

publish_clash_subscription() {
  local show_ip="$1"
  local token=""

  mkdir -p /usr/local/lib
  if [[ ! -s "$SUB_TOKEN_FILE" ]]; then
    token="$(python3 -c 'import secrets; print(secrets.token_hex(16))')"
    printf '%s\n' "$token" >"$SUB_TOKEN_FILE"
    chmod 600 "$SUB_TOKEN_FILE"
  fi
  token="$(tr -d '[:space:]' <"$SUB_TOKEN_FILE")"

  SHOW_IP="$show_ip" SOCKS_PORT="$PORT" SOCKS_USER="$USER_NAME" SOCKS_PASS="$PASS" CLASH_FILE="$CLASH_FILE" python3 - <<'PY'
import json
import os

server = os.environ["SHOW_IP"]
port = int(os.environ["SOCKS_PORT"])
user = json.dumps(os.environ["SOCKS_USER"], ensure_ascii=False)
password = json.dumps(os.environ["SOCKS_PASS"], ensure_ascii=False)
text = f"""mixed-port: 7897
allow-lan: false
mode: rule
log-level: info
ipv6: false
unified-delay: true

dns:
  enable: true
  ipv6: false
  respect-rules: true
  enhanced-mode: fake-ip
  fake-ip-range: 198.18.0.1/16
  fake-ip-filter:
    - "*.lan"
    - "*.local"
    - "+.msftconnecttest.com"
  default-nameserver:
    - 223.5.5.5
    - 119.29.29.29
  proxy-server-nameserver:
    - 223.5.5.5
    - 119.29.29.29
  nameserver:
    - https://dns.google/dns-query
    - 223.5.5.5

proxies:
  - name: socks5
    type: socks5
    server: {server}
    port: {port}
    username: {user}
    password: {password}
    udp: true

proxy-groups:
  - name: PROXY
    type: select
    proxies:
      - socks5
      - DIRECT

rules:
  - AND,((NETWORK,UDP),(DST-PORT,443)),REJECT
  - DOMAIN-SUFFIX,chatgpt.com,PROXY
  - DOMAIN-SUFFIX,openai.com,PROXY
  - DOMAIN-SUFFIX,oaistatic.com,PROXY
  - DOMAIN-SUFFIX,oaiusercontent.com,PROXY
  - DOMAIN-SUFFIX,sora.com,PROXY
  - DOMAIN-SUFFIX,featureassets.org,PROXY
  - DOMAIN-SUFFIX,google.com,PROXY
  - DOMAIN-SUFFIX,googleapis.com,PROXY
  - DOMAIN-SUFFIX,gstatic.com,PROXY
  - DOMAIN-SUFFIX,googleusercontent.com,PROXY
  - DOMAIN-SUFFIX,ggpht.com,PROXY
  - DOMAIN-SUFFIX,googlevideo.com,PROXY
  - DOMAIN-SUFFIX,youtube.com,PROXY
  - DOMAIN-SUFFIX,ytimg.com,PROXY
  - DOMAIN-SUFFIX,gmail.com,PROXY
  - DOMAIN-SUFFIX,recaptcha.net,PROXY
  - GEOSITE,openai,PROXY
  - GEOSITE,google,PROXY
  - MATCH,DIRECT
"""
with open(os.environ["CLASH_FILE"], "w", encoding="utf-8") as fh:
    fh.write(text)
os.chmod(os.environ["CLASH_FILE"], 0o600)
PY

  cat >/usr/local/lib/socks5-sub.py <<'PY'
#!/usr/bin/env python3
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

TOKEN = Path("/usr/local/etc/xray/subscribe.token").read_text(encoding="utf-8").strip()
YAML = Path("/usr/local/etc/xray/clash-verge.yaml")
PORT = 25500
SUB_PATH = f"/{TOKEN}/clash.yaml"


PNG = Path("/usr/local/etc/xray/shadowrocket.png")
QR_PATH = f"/{TOKEN}/shadowrocket"
PNG_PATH = f"/{TOKEN}/shadowrocket.png"


class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        path = self.path.split("?", 1)[0]
        if path == SUB_PATH and YAML.is_file():
            body = YAML.read_bytes()
            content_type = "text/yaml; charset=utf-8"
        elif path == PNG_PATH and PNG.is_file():
            body = PNG.read_bytes()
            content_type = "image/png"
        elif path == QR_PATH:
            body = (
                "<!doctype html><meta charset=utf-8><title>Shadowrocket</title>"
                "<body style=\"font-family:sans-serif;text-align:center;padding:32px\">"
                "<h1>Shadowrocket</h1>"
                f"<img alt=\"qr\" src=\"{PNG_PATH}\">"
                "<p>打开 Shadowrocket 扫描二维码</p></body>"
            ).encode()
            content_type = "text/html; charset=utf-8"
        else:
            self.send_response(404)
            self.end_headers()
            return
        self.send_response(200)
        self.send_header("Content-Type", content_type)
        self.send_header("Cache-Control", "no-store")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, fmt, *args):
        return


if __name__ == "__main__":
    ThreadingHTTPServer(("0.0.0.0", PORT), Handler).serve_forever()
PY
  chmod 755 /usr/local/lib/socks5-sub.py

  cat >/etc/systemd/system/socks5-sub.service <<EOF
[Unit]
Description=SOCKS5 Clash Verge subscription
After=network.target

[Service]
Type=simple
ExecStart=/usr/bin/python3 ${SUB_SERVER}
Restart=on-failure
RestartSec=2

[Install]
WantedBy=multi-user.target
EOF

  ROCKET_URI="$(SHOW_IP="$show_ip" SOCKS_PORT="$PORT" SOCKS_USER="$USER_NAME" SOCKS_PASS="$PASS" ROCKET_FILE="$ROCKET_FILE" python3 - <<'PY'
import base64
import os
from urllib.parse import quote

user = os.environ["SOCKS_USER"]
password = os.environ["SOCKS_PASS"]
host = os.environ["SHOW_IP"]
port = os.environ["SOCKS_PORT"]
auth = base64.b64encode(f"{user}:{password}".encode()).decode()
uri = f"socks://{auth}@{host}:{port}#{quote('SOCKS5')}"
path = os.environ["ROCKET_FILE"]
with open(path, "w", encoding="utf-8") as fh:
    fh.write(uri + "\n")
os.chmod(path, 0o600)
print(uri)
PY
)"
  if ! command -v qrencode >/dev/null 2>&1; then
    apt-get update -y
    apt-get install -y qrencode
  fi
  qrencode -o "$ROCKET_PNG" -s 8 -m 2 "$ROCKET_URI"
  chmod 600 "$ROCKET_PNG"

  allow_tcp_port "$SUB_PORT"
  systemctl daemon-reload
  systemctl enable socks5-sub
  systemctl restart socks5-sub
  if ! systemctl is-active --quiet socks5-sub; then
    systemctl status socks5-sub --no-pager -l || true
    echo "订阅服务未能启动"
    exit 1
  fi

  SUB_URL="http://${show_ip}:${SUB_PORT}/${token}/clash.yaml"
  ROCKET_PAGE="http://${show_ip}:${SUB_PORT}/${token}/shadowrocket"
}

print_default_info() {
  local public_ip="${1:-}" sub_url="${2:-}" rocket_page="${3:-}" show_ip proxy_url linux_cmd powershell_cmd
  local green=$'\033[32m' yellow=$'\033[33m' reset=$'\033[0m'
  local line='=================================================================='

  if [[ -z "$public_ip" ]] && command -v curl >/dev/null 2>&1; then
    public_ip="$(curl -4 -fsSL --max-time 8 https://ifconfig.me || curl -4 -fsSL --max-time 8 https://api.ipify.org || true)"
    public_ip="$(printf '%s' "$public_ip" | tr -d '[:space:]')"
  fi
  if [[ -z "$public_ip" ]] && command -v ip >/dev/null 2>&1; then
    public_ip="$(ip -4 route get 1.1.1.1 2>/dev/null | awk '{for (i=1; i<=NF; i++) if ($i=="src") {print $(i+1); exit}}' || true)"
  fi

  show_ip="${public_ip:-服务器IP}"
  proxy_url="socks5://${USER_NAME}:${PASS}@${show_ip}:${PORT}"
  linux_cmd="curl -x ${proxy_url} https://ifconfig.me"
  powershell_cmd="curl.exe -x ${proxy_url} https://ifconfig.me"

  printf '\n'
  printf '%s%s%s\n' "$green" "$line" "$reset"
  printf '%s%s%s\n' "$green" "SOCKS5 default info!" "$reset"
  printf '%s%s%s\n' "$green" "$line" "$reset"
  printf '连接地址: %s%s%s\n' "$yellow" "$proxy_url" "$reset"
  printf 'Linux 验证: %s%s%s\n' "$yellow" "$linux_cmd" "$reset"
  printf 'PowerShell 验证: %s%s%s\n' "$yellow" "$powershell_cmd" "$reset"
  if [[ -n "$sub_url" ]]; then
    printf '订阅地址: %s%s%s\n' "$yellow" "$sub_url" "$reset"
  fi
  if [[ -n "$rocket_page" ]]; then
    printf 'Shadowrocket 二维码: %s%s%s\n' "$yellow" "$rocket_page" "$reset"
  fi
  printf '%s%s%s\n' "$green" "$line" "$reset"
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --port)
      [[ $# -ge 2 ]] || { echo "缺少 --port 的值"; exit 1; }
      PORT="$2"
      PORT_SET=1
      shift 2
      ;;
    --user)
      [[ $# -ge 2 ]] || { echo "缺少 --user 的值"; exit 1; }
      USER_NAME="$2"
      USER_SET=1
      shift 2
      ;;
    --pass)
      [[ $# -ge 2 ]] || { echo "缺少 --pass 的值"; exit 1; }
      PASS="$2"
      PASS_SET=1
      shift 2
      ;;
    --listen)
      [[ $# -ge 2 ]] || { echo "缺少 --listen 的值"; exit 1; }
      LISTEN="$2"
      LISTEN_SET=1
      shift 2
      ;;
    --upgrade)
      UPGRADE=1
      shift
      ;;
    --force)
      FORCE=1
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "无法识别的参数: $1"
      usage
      exit 1
      ;;
  esac
done

if [[ "${EUID}" -ne 0 ]]; then
  echo "请用 root 运行: sudo bash $0"
  exit 1
fi

if [[ ! -f /etc/os-release ]]; then
  echo "无法确认操作系统，本脚本用于 Debian 或 Ubuntu"
  exit 1
fi
# shellcheck disable=SC1091
. /etc/os-release
case "${ID:-}" in
  debian|ubuntu) ;;
  *)
    echo "当前系统是 ${ID:-unknown}，本脚本用于 Debian 或 Ubuntu"
    exit 1
    ;;
esac

if [[ ! -d /run/systemd/system ]]; then
  echo "需要 systemd 才能安装并拉起 xray 服务"
  exit 1
fi

if [[ "$PORT_SET" -eq 1 ]]; then
  if [[ ! "$PORT" =~ ^[0-9]+$ ]] || ! (( 10#$PORT >= 1 && 10#$PORT <= 65535 )); then
    echo "端口需为 1 到 65535 的整数"
    exit 1
  fi
fi

if [[ "$USER_SET" -eq 1 && -z "$USER_NAME" ]]; then
  echo "--user 需要一个非空用户名"
  exit 1
fi
if [[ "$PASS_SET" -eq 1 && -z "$PASS" ]]; then
  echo "--pass 需要一个非空密码"
  exit 1
fi

export DEBIAN_FRONTEND=noninteractive
if ! command -v python3 >/dev/null 2>&1 || ! command -v curl >/dev/null 2>&1 || ! command -v ss >/dev/null 2>&1; then
  apt-get update -y
  apt-get install -y curl ca-certificates python3 iproute2
fi

echo "检查 Xray 是否已安装..."
if [[ -x "$XRAY" && -f /etc/systemd/system/xray.service && "$UPGRADE" -eq 0 ]]; then
  echo "Xray 已安装: $("$XRAY" version | head -n 1 || true)"
else
  echo "Xray 未安装，正在安装..."
  apt-get update -y
  apt-get install -y curl ca-certificates
  bash -c "$(curl -fsSL https://github.com/XTLS/Xray-install/raw/main/install-release.sh)" @ install
fi

if [[ ! -x "$XRAY" ]]; then
  echo "未找到 ${XRAY}"
  exit 1
fi
if ! getent group xray >/dev/null; then
  echo "未找到 xray 系统组，官方安装未完成"
  exit 1
fi

if [[ ! -d "$JSON_PATH" ]]; then
  install -d -m 750 -o root -g xray "$JSON_PATH"
fi

echo "检查 SOCKS5 是否已配置..."
CONFIGURED=0
RESTART_XRAY=1
backup=""
SOURCE="reused"
if [[ "$PORT_SET" -eq 0 && "$USER_SET" -eq 0 && "$PASS_SET" -eq 0 && "$LISTEN_SET" -eq 0 && "$FORCE" -eq 0 ]] && load_existing_socks; then
  CONFIGURED=1
  RESTART_XRAY=0
  echo "SOCKS5 已配置，端口 ${PORT}。"
  if upgrade_existing_outbounds; then
    RESTART_XRAY=1
  fi
fi

if [[ "$CONFIGURED" -eq 0 ]]; then
echo "SOCKS5 未配置，正在写入配置..."
work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT
tmp_config="${work}/config.json"
meta="${work}/meta.json"

SOCKS_CONFIG="$CONFIG" \
SOCKS_OUT="$tmp_config" \
SOCKS_META="$meta" \
SOCKS_FORCE="$FORCE" \
SOCKS_PORT_SET="$PORT_SET" \
SOCKS_USER_SET="$USER_SET" \
SOCKS_PASS_SET="$PASS_SET" \
SOCKS_LISTEN_SET="$LISTEN_SET" \
SOCKS_PORT="$PORT" \
SOCKS_USER="$USER_NAME" \
SOCKS_PASS="$PASS" \
SOCKS_LISTEN="$LISTEN" \
python3 - <<'PY'
import json
import os
import secrets
import string
import sys

config_path = os.environ["SOCKS_CONFIG"]
out_path = os.environ["SOCKS_OUT"]
meta_path = os.environ["SOCKS_META"]
force = os.environ.get("SOCKS_FORCE") == "1"
port_set = os.environ.get("SOCKS_PORT_SET") == "1"
user_set = os.environ.get("SOCKS_USER_SET") == "1"
pass_set = os.environ.get("SOCKS_PASS_SET") == "1"
listen_set = os.environ.get("SOCKS_LISTEN_SET") == "1"


def fail(msg: str) -> None:
    print(msg, file=sys.stderr)
    sys.exit(1)


def bad_secret(value: str, label: str) -> None:
    if value == "":
        fail(f"{label}不能为空")
    if any(ord(ch) < 32 or ch == "\x7f" for ch in value):
        fail(f"{label}含有控制字符")


def random_alnum(length: int) -> str:
    alphabet = string.ascii_letters + string.digits
    return "".join(secrets.choice(alphabet) for _ in range(length))


kind = "missing"
cfg: dict = {}
if os.path.isfile(config_path):
    with open(config_path, encoding="utf-8") as fh:
        raw = fh.read().strip()
    if raw in ("", "{}"):
        kind = "empty"
    else:
        try:
            loaded = json.loads(raw)
        except json.JSONDecodeError:
            kind = "invalid"
        else:
            if not isinstance(loaded, dict):
                kind = "invalid"
            else:
                kind = "json"
                cfg = loaded

inbounds = cfg.get("inbounds") if isinstance(cfg.get("inbounds"), list) else []
if kind == "invalid":
    if not force:
        fail(f"现有配置无法解析。确认替换请加 --force。配置路径: {config_path}")
    kind = "replace"
elif kind == "json":
    if not inbounds:
        kind = "empty"
    elif len(inbounds) == 1 and isinstance(inbounds[0], dict) and inbounds[0].get("protocol") == "socks":
        kind = "socks"
    elif not force:
        fail(f"现有配置不是单个 SOCKS 入站。确认替换请加 --force。配置路径: {config_path}")
    else:
        kind = "replace"

existing_user = None
existing_pass = None
existing_port = None
existing_listen = None
if kind == "socks":
    inbound = inbounds[0]
    existing_port = inbound.get("port")
    existing_listen = inbound.get("listen")
    try:
        account = inbound["settings"]["accounts"][0]
    except (KeyError, IndexError, TypeError):
        account = None
    if isinstance(account, dict):
        existing_user = account.get("user") or None
        existing_pass = account.get("pass") or None

if user_set:
    user = os.environ["SOCKS_USER"]
    bad_secret(user, "用户名")
    source_user = "provided"
elif isinstance(existing_user, str) and existing_user:
    user = existing_user
    source_user = "reused"
else:
    user = random_alnum(6)
    source_user = "generated"

if pass_set:
    password = os.environ["SOCKS_PASS"]
    bad_secret(password, "密码")
    if len(password) < 8:
        fail("密码至少 8 位")
    source_pass = "provided"
elif (
    isinstance(existing_pass, str)
    and existing_pass
    and (not user_set or user == existing_user)
):
    password = existing_pass
    source_pass = "reused"
else:
    password = random_alnum(32)
    source_pass = "generated"

if len(user) > 64 or len(password) > 128:
    fail("用户名最长 64 位，密码最长 128 位")

if port_set:
    port = int(os.environ["SOCKS_PORT"])
elif isinstance(existing_port, int) and not isinstance(existing_port, bool) and 1 <= existing_port <= 65535:
    port = existing_port
else:
    port = 10808

if listen_set:
    listen = os.environ["SOCKS_LISTEN"]
elif isinstance(existing_listen, str) and existing_listen:
    listen = existing_listen
else:
    listen = "0.0.0.0"

if not listen or any(ch.isspace() for ch in listen):
    fail("监听地址无效")

if source_user == "generated" or source_pass == "generated":
    source = "generated"
elif source_user == "provided" or source_pass == "provided":
    source = "provided"
else:
    source = "reused"

document = {
    "log": {"loglevel": "warning"},
    "inbounds": [
        {
            "listen": listen,
            "port": port,
            "protocol": "socks",
            "settings": {
                "auth": "password",
                "accounts": [{"user": user, "pass": password}],
                "udp": True,
                "ip": listen,
            },
        }
    ],
    "outbounds": [
        {"tag": "direct", "protocol": "freedom", "settings": {"domainStrategy": "UseIPv4"}},
        {"tag": "block", "protocol": "blackhole"},
    ],
    "routing": {
        "rules": [{"type": "field", "ip": ["geoip:private"], "outboundTag": "block"}],
    },
}

with open(out_path, "w", encoding="utf-8") as fh:
    json.dump(document, fh, indent=2, ensure_ascii=False)
    fh.write("\n")
with open(meta_path, "w", encoding="utf-8") as fh:
    json.dump(
        {"user": user, "pass": password, "port": port, "listen": listen, "source": source},
        fh,
        ensure_ascii=False,
    )
    fh.write("\n")
os.chmod(out_path, 0o600)
os.chmod(meta_path, 0o600)
PY

echo "正在检查配置语法..."
"$XRAY" run -test -config "$tmp_config"

backup=""
if [[ -f "$CONFIG" ]]; then
  backup="${CONFIG}.bak.$(date +%Y%m%d%H%M%S)"
  cp -a "$CONFIG" "$backup"
fi
install -m 640 -o 0 -g xray "$tmp_config" "${CONFIG}.new"
mv -f "${CONFIG}.new" "$CONFIG"

mapfile -t meta_lines < <(python3 - "$meta" <<'PY'
import json
import sys
from urllib.parse import quote

with open(sys.argv[1], encoding="utf-8") as fh:
    meta = json.load(fh)
print(quote(meta["user"], safe=""))
print(quote(meta["pass"], safe=""))
print(meta["port"])
print(meta["listen"])
print(meta["source"])
print(meta["user"])
print(meta["pass"])
PY
)
enc_user="${meta_lines[0]}"
enc_pass="${meta_lines[1]}"
PORT="${meta_lines[2]}"
LISTEN="${meta_lines[3]}"
SOURCE="${meta_lines[4]}"
USER_NAME="${meta_lines[5]}"
PASS="${meta_lines[6]}"
fi

echo "检查防火墙端口 ${PORT} 是否放行..."
if firewall_port_allowed "$PORT"; then
  echo "防火墙已放行 ${PORT}/tcp 与 ${PORT}/udp。"
else
  echo "防火墙未放行 ${PORT}，正在放行..."
  allow_firewall_port "$PORT"
fi

echo "优化网络参数（BBR 与 TCP 缓冲区）..."
tune_network

echo "启动 Xray 并设置开机自启..."
start_xray "$PORT" "$RESTART_XRAY"

public_ip="$(curl -4 -fsSL --max-time 8 https://ifconfig.me || curl -4 -fsSL --max-time 8 https://api.ipify.org || true)"
public_ip="$(printf '%s' "$public_ip" | tr -d '[:space:]')"
if [[ -z "$public_ip" ]]; then
  public_ip="$(ip -4 route get 1.1.1.1 2>/dev/null | awk '{for (i=1; i<=NF; i++) if ($i=="src") {print $(i+1); exit}}' || true)"
fi
if [[ -z "${enc_user:-}" || -z "${enc_pass:-}" ]]; then
  mapfile -t enc_lines < <(SOCKS_USER="$USER_NAME" SOCKS_PASS="$PASS" python3 - <<'PY'
import os
from urllib.parse import quote
print(quote(os.environ["SOCKS_USER"], safe=""))
print(quote(os.environ["SOCKS_PASS"], safe=""))
PY
)
  enc_user="${enc_lines[0]}"
  enc_pass="${enc_lines[1]}"
fi
via_ip="$(curl -4 -fsSL --max-time 20 -x "socks5://${enc_user}:${enc_pass}@127.0.0.1:${PORT}" https://ifconfig.me || true)"
via_ip="$(printf '%s' "$via_ip" | tr -d '[:space:]')"

case "$SOURCE" in
  generated) echo "已生成并写入新的账号密码。" ;;
  provided) echo "已写入本次指定的账号密码。" ;;
  reused) echo "已沿用配置中的账号密码。" ;;
esac
if [[ -n "$backup" ]]; then
  echo "旧配置已备份到 ${backup}"
fi
if [[ -n "$via_ip" && -n "$public_ip" && "$via_ip" == "$public_ip" ]]; then
  echo "本机经代理访问 https://ifconfig.me 返回 ${via_ip}，与服务器出口地址一致。"
elif [[ -n "$via_ip" ]]; then
  echo "本机经代理访问 https://ifconfig.me 返回 ${via_ip}。"
else
  echo "服务已在监听。本机经代理访问 https://ifconfig.me 没有返回地址，请在客户端再试一次。"
fi

if [[ -z "$public_ip" ]]; then
  echo "未得到公网 IP，订阅地址里请改成服务器公网 IP。"
  public_ip="服务器IP"
fi
publish_clash_subscription "$public_ip"
echo "已写入 Clash Verge 配置，Google 与 ChatGPT 走代理。"
print_default_info "$public_ip" "$SUB_URL" "${ROCKET_PAGE:-}"
if [[ -n "${ROCKET_URI:-}" ]] && command -v qrencode >/dev/null 2>&1; then
  echo "用 Shadowrocket 扫描下面的二维码："
  qrencode -t UTF8 -m 1 "$ROCKET_URI"
fi
