#!/bin/bash

# 定义变量
INSTALL_DIR="/var/mobile/vless-proxy"
CONFIG_FILE="$INSTALL_DIR/config.json"
SERVICE_NAME="com.vless.proxy"
UUID=$(uuidgen)
PORT=443

# 安装依赖
echo "[1/4] 安装依赖..."
apt update
apt install -y wget curl jq openssl

# 下载适配 arm64e 的 sing-box（需确认可用性！）
echo "[2/4] 下载代理内核..."
# 方法1：直接使用官方预编译的 arm64e 版本（若存在）
wget -O $INSTALL_DIR/xray "https://github.com/XTLS/Xray-core/releases/download/v1.8.6/Xray-ios-arm64e-v8a.zip"
chmod +x $INSTALL_DIR/sing-box

# 生成配置文件（与之前相同）
echo "[3/4] 生成配置文件..."
cat > $CONFIG_FILE << EOF
{
  "inbounds": [{
    "type": "vless",
    "listen": "0.0.0.0",
    "port": $PORT,
    "settings": {
      "clients": [{ "id": "$UUID" }],
      "decryption": "none"
    },
    "streamSettings": {
      "network": "tcp",
      "security": "reality",
      "realitySettings": {
        "dest": "gateway.icloud.com:443",
        "serverNames": ["gateway.icloud.com"]
      }
    }
  }]
}
EOF

# 创建启动服务（与之前相同）
echo "[4/4] 创建服务..."
cat > /Library/LaunchDaemons/$SERVICE_NAME.plist << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>$SERVICE_NAME</string>
  <key>ProgramArguments</key>
  <array>
    <string>$INSTALL_DIR/sing-box</string>
    <string>run</string>
    <string>-c</string>
    <string>$CONFIG_FILE</string>
  </array>
  <key>KeepAlive</key>
  <true/>
</dict>
</plist>
EOF

# 加载服务
launchctl load /Library/LaunchDaemons/$SERVICE_NAME.plist
launchctl start $SERVICE_NAME

# 输出配置信息
echo "VLESS节点已启动！配置如下："
echo "地址：$(ifconfig | grep 'inet ' | grep -v 127.0.0.1 | awk '{print $2}')"
echo "端口：$PORT"
echo "UUID：$UUID"
echo "传输协议：tcp + Reality"