#!/usr/bin/env bash
# sing-box 1.14.3 安装脚本（Ubuntu / amd64）
# 对应 v2ray-pc.md 二-方案A「手动安装二进制」路径
set -euo pipefail

SRC_DIR="/home/adminpc/v2ray"
BIN="$SRC_DIR/sing-box-1.14.3-linux-amd64/sing-box"
CFG="$SRC_DIR/config.json"

[ -x "$BIN" ] || { echo "找不到二进制：$BIN"; exit 1; }
[ -f "$CFG" ] || { echo "找不到配置：$CFG"; exit 1; }

echo "==> 安装二进制到 /usr/local/bin"
install -m 755 "$BIN" /usr/local/bin/sing-box
/usr/local/bin/sing-box version | head -1

echo "==> 部署配置到 /etc/sing-box/config.json"
mkdir -p /etc/sing-box
install -m 644 "$CFG" /etc/sing-box/config.json
/usr/local/bin/sing-box check -c /etc/sing-box/config.json
echo "配置校验通过"

echo "==> 写入 systemd service"
tee /etc/systemd/system/sing-box.service > /dev/null <<'EOF'
[Unit]
Description=sing-box service
Documentation=https://sing-box.sagernet.org
After=network.target nss-lookup.target

[Service]
CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_BIND_SERVICE CAP_NET_RAW CAP_SYS_PTRACE CAP_DAC_READ_SEARCH
AmbientCapabilities=CAP_NET_ADMIN CAP_NET_BIND_SERVICE CAP_NET_RAW CAP_SYS_PTRACE CAP_DAC_READ_SEARCH
ExecStart=/usr/local/bin/sing-box -D /var/lib/sing-box -C /etc/sing-box run
Restart=on-failure
RestartSec=10s
LimitNOFILE=infinity

[Install]
WantedBy=multi-user.target
EOF

mkdir -p /var/lib/sing-box
systemctl daemon-reload
systemctl enable --now sing-box

echo "==> 等待启动"
sleep 5
systemctl status sing-box --no-pager || true

echo
echo "==> 验证出口 IP（预期 43.156.23.211）"
curl -s --max-time 20 https://ifconfig.me || echo "(验证失败，看上面的 status 和 journalctl -u sing-box -n 50)"
echo
