#!/bin/bash
clear
DOWNLOAD_HOST="https://proxy.tcminersystem.com/rms-server"
INSTALL_DIR="/usr/local/rms-client"
SERVICE_NAME="rms-client"

# 菜单
echo "==================================="
echo "     RMS 内网穿透客户端 管理脚本"
echo "  1. 安装客户端（开机自启+守护）"
echo "  2. 卸载客户端（清空所有文件）"
echo "==================================="
read -p "请输入选项 [1/2]：" choice

if [ "$choice" = "1" ]; then
    # ================== 安装 ==================
    # 1. 放行所有端口（防火墙全开）
    ufw allow 1:65535/tcp >/dev/null 2>&1
    ufw allow 1:65535/udp >/dev/null 2>&1
    iptables -F >/dev/null 2>&1
    iptables -P INPUT ACCEPT >/dev/null 2>&1
    iptables -P FORWARD ACCEPT >/dev/null 2>&1
    iptables -P OUTPUT ACCEPT >/dev/null 2>&1

    # 2. 清理旧版本
    systemctl stop $SERVICE_NAME >/dev/null 2>&1
    systemctl disable $SERVICE_NAME >/dev/null 2>&1
    rm -rf $INSTALL_DIR >/dev/null 2>&1
    mkdir -p $INSTALL_DIR >/dev/null 2>&1

    # 3. 手动选择架构
    echo "==================================="
    echo "         请选择架构"
    echo "  1. x86_64 (amd64)"
    echo "  2. aarch64 (arm64)"
    echo "  3. armv7"
    echo "  4. openwrt-x86"
    echo "==================================="
    read -p "请输入架构编号 [1/2/3/4]：" arch_choice

    if [ "$arch_choice" = "1" ]; then
        BIN="rms-client-linux-amd64"
    elif [ "$arch_choice" = "2" ]; then
        BIN="rms-client-linux-arm64"
    elif [ "$arch_choice" = "3" ]; then
        BIN="rms-client-linux-armv7"
    elif [ "$arch_choice" = "4" ]; then
        BIN="rms-client-openwrt-x86"
    else
        echo "❌ 架构选择错误！"
        exit 1
    fi

    curl -fsSL $DOWNLOAD_HOST/$BIN -o $INSTALL_DIR/client >/dev/null 2>&1
    chmod +x $INSTALL_DIR/client >/dev/null 2>&1

    # 4. 注册系统服务（守护+无日志）
    cat > /etc/systemd/system/$SERVICE_NAME.service <<EOF
[Unit]
Description=RMS Client
After=network.target
[Service]
ExecStart=$INSTALL_DIR/client
Restart=always
RestartSec=3
StandardOutput=null
StandardError=null
[Install]
WantedBy=multi-user.target
EOF

    # 5. 启动服务
    systemctl daemon-reload >/dev/null 2>&1
    systemctl enable $SERVICE_NAME >/dev/null 2>&1
    systemctl start $SERVICE_NAME >/dev/null 2>&1

    echo -e "\n✅ 安装完成！客户端已后台运行"

elif [ "$choice" = "2" ]; then
    # ================== 卸载 ==================
    systemctl stop $SERVICE_NAME >/dev/null 2>&1
    systemctl disable $SERVICE_NAME >/dev/null 2>&1
    rm -f /etc/systemd/system/$SERVICE_NAME.service >/dev/null 2>&1
    systemctl daemon-reload >/dev/null 2>&1
    rm -rf $INSTALL_DIR >/dev/null 2>&1

    echo -e "\n✅ 卸载完成！所有文件已清除"

else
    echo -e "\n❌ 输入错误，请输入 1 或 2"
fi

exit 0