#!/bin/bash

echo "=== 一键安装 XrayR + 配置 NewV2board Reality 节点 ==="

# 安装必要工具
echo "👉 检查依赖..."
for cmd in unzip wget jq yq; do
    if ! command -v $cmd >/dev/null 2>&1; then
        echo "安装 $cmd ..."
        apt update -y && apt install -y $cmd
    fi
done

# 创建目录
mkdir -p /etc/XrayR

# 下载 XrayR 最新 Linux 64 位二进制
echo "👉 下载 XrayR 最新版本..."
cd /tmp
XrayR_FILE="XrayR-linux.zip"
wget -O $XrayR_FILE https://github.com/XrayR-project/XrayR/releases/latest/download/XrayR-linux-64.zip

# 检查下载是否成功
if [ ! -f "$XrayR_FILE" ]; then
    echo "❌ XrayR 下载失败，请检查网络或链接"
    exit 1
fi

# 解压并移动到 /etc/XrayR
unzip -o $XrayR_FILE -d /etc/XrayR
chmod +x /etc/XrayR/XrayR

# 交互式配置节点
read -p "请输入 NodeID: " NODE_ID
read -p "请输入 XBoard API URL (默认 http://xapi.023021.xyz): " API_URL
API_URL=${API_URL:-http://xapi.023021.xyz}
read -p "请输入 XBoard API Key (默认 michaeltan057720，回车使用默认): " API_KEY
API_KEY=${API_KEY:-michaeltan057720}

# 手动输入 Reality 配置
echo "=== 请输入 Reality 配置 ==="
read -p "ServerName (伪装域名): " SERVER_NAME
read -p "PublicKey (XBoard 上生成的公钥): " PUBLIC_KEY
read -p "ShortID (XBoard 上生成的 ShortID): " SHORT_ID

# 生成 config.yml
echo "👉 正在生成 /etc/XrayR/config.yml ..."
cat >/etc/XrayR/config.yml <<EOF
Log:
  Level: info
  AccessPath: ""
  ErrorPath: ""

DnsConfigPath: ""

Nodes:
  - PanelType: "NewV2board"
    ApiConfig:
      ApiHost: "$API_URL"
      ApiKey: "$API_KEY"
      NodeID: $NODE_ID
      NodeType: Vless
      Timeout: 30
      EnableVless: true
      EnableREALITY: true
      VlessFlow: "xtls-rprx-vision"
      SpeedLimit: 0
      DeviceLimit: 0
      RuleListPath: ""
      RealityConfig:
        ServerName: "$SERVER_NAME"
        PublicKey: "$PUBLIC_KEY"
        ShortID: "$SHORT_ID"
    ControllerConfig:
      ListenIP: 0.0.0.0
      SendIP: 0.0.0.0
      UpdatePeriodic: 100
      EnableDNS: false
      CertConfig:
        CertMode: none
        CertDomain: ""
EOF

echo "✅ 配置文件生成完成！"

# 设置 systemd 服务
if [ ! -f /etc/systemd/system/XrayR.service ]; then
    echo "👉 创建 systemd 服务..."
    cat >/etc/systemd/system/XrayR.service <<EOL
[Unit]
Description=XrayR Service
After=network.target

[Service]
Type=simple
ExecStart=/etc/XrayR/XrayR -c /etc/XrayR/config.yml
Restart=on-failure
LimitNOFILE=65535

[Install]
WantedBy=multi-user.target
EOL
    systemctl daemon-reload
    systemctl enable XrayR
fi

echo "👉 启动 XrayR 服务..."
systemctl restart XrayR
systemctl status XrayR -l --no-pager
