#!/bin/bash
#
# MTG Fake-TLS 一键管理脚本（交互版）【已修改：安装前置询问自定义接入域名】
# 支持: 安装 / 配置域名 / 查看状态 / 卸载
# 下载源: ipan.mbvpn.cn 私有镜像
#
set -e
# ============================================================
# 颜色与全局变量
# ============================================================
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;36m'
CYAN='\033[1;36m'
NC='\033[0m'
INSTALL_DIR="/etc/mtg"
CONFIG_FILE="${INSTALL_DIR}/config.toml"
META_FILE="${INSTALL_DIR}/meta.env"
SERVICE_NAME="mtg"
MTG_VERSION="2.2.8"
MIRROR_BASE="http://ipan.mbvpn.cn/mtg-master"
# ============================================================
# 工具函数
# ============================================================
print_banner() {
    clear
    echo -e "${CYAN}"
    echo "╔══════════════════════════════════════════╗"
    echo "║     MTG Fake-TLS 代理 管理脚本 v2       ║"
    echo "║     版本: ${MTG_VERSION}  |  源: 私有镜像      ║"
    echo "╚══════════════════════════════════════════╝"
    echo -e "${NC}"
}
is_installed() {
    [[ -f "${CONFIG_FILE}" && -f "${INSTALL_DIR}/mtg" ]]
}
read_input() {
    local prompt="$1"
    local default="$2"
    local value
    if [[ -n "${default}" ]]; then
        echo -ne "${YELLOW}${prompt}${NC} [${default}]: " >&2
        read -r value
        echo "${value:-$default}"
    else
        echo -ne "${YELLOW}${prompt}${NC}: " >&2
        read -r value
        echo "${value}"
    fi
}
pause() {
    echo "" >&2
    read -n 1 -s -r -p "按任意键继续..."
    echo "" >&2
}
# ============================================================
# 系统与网络检测
# ============================================================
detect_arch() {
    local arch_raw
    arch_raw=$(uname -m)
    case "${arch_raw}" in
        x86_64|amd64)    echo "amd64" ;;
        aarch64|arm64)   echo "arm64" ;;
        armv7l|armhf)    echo "armv7" ;;
        armv6l)          echo "armv6" ;;
        i386|i686)       echo "386" ;;
        *)               echo "unknown" ;;
    esac
}
detect_os() {
    if [[ -f /etc/os-release ]]; then
        . /etc/os-release
        echo "${ID,,}"
    elif [[ -f /etc/redhat-release ]]; then
        echo "centos"
    elif [[ -f /etc/alpine-release ]]; then
        echo "alpine"
    else
        echo "unknown"
    fi
}
detect_ips() {
    IPV4_ADDR=""
    IPV6_ADDR=""
    IPV4_ADDR=$(curl -4 -s --connect-timeout 5 --max-time 8 ifconfig.me 2>/dev/null || true)
    IPV6_ADDR=$(curl -6 -s --connect-timeout 5 --max-time 8 ifconfig.me 2>/dev/null || true)
}
print_ip_info() {
    detect_ips
    echo -e "${BLUE}🌐 网络检测:${NC}"
    if [[ -n "${IPV4_ADDR}" ]]; then
        echo -e "   IPv4: ${GREEN}${IPV4_ADDR}${NC}"
    else
        echo -e "   IPv4: ${RED}无${NC}"
    fi
    if [[ -n "${IPV6_ADDR}" ]]; then
        echo -e "   IPv6: ${GREEN}${IPV6_ADDR}${NC}"
    else
        echo -e "   IPv6: ${RED}无${NC}"
    fi
    if [[ -n "${IPV4_ADDR}" && -n "${IPV6_ADDR}" ]]; then
        echo -e "   状态: ${GREEN}双栈网络${NC}"
    elif [[ -n "${IPV4_ADDR}" ]]; then
        echo -e "   状态: ${YELLOW}仅 IPv4${NC}"
    elif [[ -n "${IPV6_ADDR}" ]]; then
        echo -e "   状态: ${RED}仅 IPv6（IPv4 用户连不上）${NC}"
    fi
}
# ============================================================
# 读取现有配置
# ============================================================
read_current_config() {
    CURRENT_SECRET=""
    CURRENT_PORT=""
    CURRENT_DOMAIN=""
    CURRENT_CUSTOM_DOMAIN=""
    if [[ -f "${CONFIG_FILE}" ]]; then
        CURRENT_SECRET=$(grep '^secret' "${CONFIG_FILE}" 2>/dev/null | sed 's/.*= "//;s/"//')
        CURRENT_PORT=$(grep '^bind-to' "${CONFIG_FILE}" 2>/dev/null | sed 's/.*://;s/"//g')
    fi
    if [[ -f "${META_FILE}" ]]; then
        CURRENT_DOMAIN=$(grep '^FAKE_TLS_DOMAIN=' "${META_FILE}" 2>/dev/null | cut -d= -f2)
        CURRENT_CUSTOM_DOMAIN=$(grep '^CUSTOM_DOMAIN=' "${META_FILE}" 2>/dev/null | cut -d= -f2)
    fi
    # 全部改成 if 语句，避免 [[ ]] && 返回 1 触发 set -e
    if [[ -z "${CURRENT_PORT}" ]]; then
        CURRENT_PORT="9888"
    fi
    if [[ -z "${CURRENT_DOMAIN}" ]]; then
        CURRENT_DOMAIN="www.microsoft.com"
    fi
}
print_current_config() {
    read_current_config
    local status
    status=$(systemctl is-active ${SERVICE_NAME} 2>/dev/null || echo "未运行")
    echo ""
    echo -e "${CYAN}━━━━━━━━━━ 当前配置 ━━━━━━━━━━${NC}"
    if [[ "${status}" == "active" ]]; then
        echo -e "  服务状态: ${GREEN}运行中${NC}"
    else
        echo -e "  服务状态: ${RED}${status}${NC}"
    fi
    echo -e "  监听端口: ${CURRENT_PORT}"
    echo -e "  伪装TLS域名: ${CURRENT_DOMAIN}"
    echo -e "  自定义接入域名: ${CURRENT_CUSTOM_DOMAIN:-无}"
    echo -e "  密钥: ${CURRENT_SECRET:0:20}..."
    print_ip_info
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
}
# ============================================================
# 安装流程
# ============================================================
install_deps() {
    local os_id
    os_id=$(detect_os)
    echo -e "${BLUE}📦 安装依赖...${NC}"
    case "${os_id}" in
        debian|ubuntu|linuxmint|kali)
            export DEBIAN_FRONTEND=noninteractive
            apt-get update -y > /dev/null 2>&1
            apt-get install -y wget curl tar systemd procps > /dev/null 2>&1 || true
            ;;
        centos|rocky|almalinux|rhel|fedora|opencloudos|tencentos|alinux|anolis|ctyunos)
            yum install -y wget curl tar procps-ng > /dev/null 2>&1 || \
            dnf install -y wget curl tar procps-ng > /dev/null 2>&1 || true
            ;;
        alpine)
            apk add --no-cache wget curl tar openrc > /dev/null 2>&1 || true
            ;;
    esac
    for cmd in wget curl tar; do
        command -v ${cmd} &> /dev/null || { echo -e "${RED}❌ ${cmd} 安装失败${NC}"; exit 1; }
    done
    echo -e "${GREEN}✅ 依赖安装完成${NC}"
}
download_binary() {
    local arch
    arch=$(detect_arch)
    if [[ "${arch}" == "unknown" ]]; then
        echo -e "${RED}❌ 不支持的架构${NC}"
        exit 1
    fi
    local filename="mtg-${MTG_VERSION}-linux-${arch}.tar.gz"
    local dl_url="${MIRROR_BASE}/${filename}"
    local dl_file="${INSTALL_DIR}/${filename}"
    mkdir -p "${INSTALL_DIR}"
    echo -e "${BLUE}⬇️  下载 MTG ${MTG_VERSION} (${arch})...${NC}"
    echo "   ${dl_url}"
    if ! wget --dns-timeout=5 --connect-timeout=10 --read-timeout=60 --tries=2 -O "${dl_file}" "${dl_url}"; then
        echo -e "${RED}❌ 下载失败，请确认文件存在于镜像源${NC}"
        rm -f "${dl_file}"
        exit 1
    fi
    if [[ ! -s "${dl_file}" ]]; then
        echo -e "${RED}❌ 文件为空${NC}"
        exit 1
    fi
    echo -e "${BLUE}📤 解压中...${NC}"
    tar -xzf "${dl_file}" -C "${INSTALL_DIR}"
    local found_bin
    found_bin=$(find "${INSTALL_DIR}" -maxdepth 2 -type f -name "mtg" -executable 2>/dev/null | head -1)
    if [[ -z "${found_bin}" ]]; then
        echo -e "${RED}❌ 未找到 mtg 二进制${NC}"
        exit 1
    fi
    mv -f "${found_bin}" "${INSTALL_DIR}/mtg"
    chmod +x "${INSTALL_DIR}/mtg"
    rm -f "${dl_file}"
    echo -e "${GREEN}✅ MTG 就绪${NC}"
}
check_port_available() {
    local port="$1"
    if command -v ss &> /dev/null; then
        if ss -tulnp | grep -q ":${port} "; then
            echo -e "${RED}❌ 端口 ${port} 已被占用:${NC}"
            ss -tulnp | grep ":${port} "
            return 1
        fi
    fi
    return 0
}
setup_firewall() {
    local port="$1"
    echo -e "${BLUE}🔥 配置防火墙放行 ${port}/tcp...${NC}"
    if command -v firewall-cmd &> /dev/null && systemctl is-active --quiet firewalld 2>/dev/null; then
        firewall-cmd --permanent --add-port=${port}/tcp > /dev/null 2>&1 || true
        firewall-cmd --reload > /dev/null 2>&1 || true
    fi
    if command -v ufw &> /dev/null && ufw status 2>/dev/null | grep -q "active"; then
        ufw allow ${port}/tcp > /dev/null 2>&1 || true
    fi
    if command -v iptables &> /dev/null; then
        iptables -I INPUT -p tcp --dport ${port} -j ACCEPT 2>/dev/null || true
    fi
}
install_service() {
    local secret="$1"
    local port="$2"
    local domain="$3"
    local custom_domain="$4"
    cat > "${CONFIG_FILE}" << EOF
secret = "${secret}"
bind-to = "0.0.0.0:${port}"
EOF
    cat > "${META_FILE}" << EOF
FAKE_TLS_DOMAIN=${domain}
MTG_PORT=${port}
CUSTOM_DOMAIN=${custom_domain}
EOF
    cat > /etc/systemd/system/${SERVICE_NAME}.service << 'EOF'
[Unit]
Description=MTProto Fake-TLS Proxy (mtg)
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
WorkingDirectory=/etc/mtg
ExecStart=/etc/mtg/mtg run /etc/mtg/config.toml
Restart=always
RestartSec=5
LimitNOFILE=65536
[Install]
WantedBy=multi-user.target
EOF
    systemctl daemon-reload
    systemctl enable ${SERVICE_NAME} > /dev/null 2>&1
    systemctl restart ${SERVICE_NAME}
    sleep 2
    if systemctl is-active --quiet ${SERVICE_NAME}; then
        echo -e "${GREEN}✅ 服务启动成功${NC}"
    else
        echo -e "${RED}❌ 启动失败，日志:${NC}"
        journalctl -u mtg -n 20 --no-pager || true
        exit 1
    fi
}
do_install() {
    echo ""
    echo -e "${CYAN}━━━━━━━━━━ 安装 MTG ━━━━━━━━━━${NC}"
    if [[ $EUID -ne 0 ]]; then
        echo -e "${RED}❌ 请用 root 运行${NC}"
        pause
        return
    fi
    if is_installed; then
        echo -e "${YELLOW}⚠️  检测到已安装 MTG${NC}"
        print_current_config
        echo ""
        local overwrite
        overwrite=$(read_input "是否覆盖重装？输入 y 确认，其他取消" "n")
        if [[ "${overwrite,,}" != "y" ]]; then
            echo "已取消"
            pause
            return
        fi
        do_uninstall force
    fi
    echo ""
    # ===== 修改点：安装前置询问自定义接入域名 =====
    local custom_domain
    custom_domain=$(read_input "自定义接入域名（无则留空，如 tg.xxx.com）" "")
    local port domain
    # 默认 9888：避开云厂商对 443 的特殊限制/占用；伪装用微软，海内外都较稳
    port=$(read_input "监听端口" "9888")
    domain=$(read_input "伪装TLS域名 (Fake-TLS，推荐 www.microsoft.com)" "www.microsoft.com")
    if ! check_port_available "${port}"; then
        pause
        return
    fi
    echo ""
    install_deps
    download_binary
    echo -e "${BLUE}🔑 生成密钥...${NC}"
    local secret
    # mtg 2.x 默认输出 base64；Telegram 各端对 ee...hex 兼容最好（参考 tele.sh）
    secret=$("${INSTALL_DIR}/mtg" generate-secret --hex "${domain}" 2>/dev/null | tr -d '\r\n')
    if [[ -z "${secret}" ]]; then
        secret=$("${INSTALL_DIR}/mtg" generate-secret "${domain}" 2>/dev/null | tr -d '\r\n')
    fi
    if [[ -z "${secret}" ]]; then
        echo -e "${RED}❌ 密钥生成失败${NC}"
        pause
        return
    fi
    echo -e "${GREEN}✅ 密钥生成完成${NC}"
    setup_firewall "${port}"
    install_service "${secret}" "${port}" "${domain}" "${custom_domain}"
    # 安装后必须确认端口在听，否则 Telegram 会一直「检查中」
    sleep 1
    if ! ss -lntup 2>/dev/null | grep -q ":${port} "; then
        echo -e "${RED}❌ 安装后端口 ${port} 未监听，请检查 journalctl -u mtg${NC}"
        journalctl -u mtg -n 30 --no-pager || true
        pause
        return
    fi
    echo -e "${GREEN}✅ 已确认监听 0.0.0.0:${port}${NC}"
    echo ""
    # 打印IP链接 + 若填了域名则打印DNS和域名链接
    print_links "${secret}" "${port}" "${custom_domain}"
    echo ""
    pause
}
# ============================================================
# 生成代理链接（新增自定义域名参数）
# ============================================================
print_links() {
    local secret="$1"
    local port="$2"
    local custom_domain="$3"
    detect_ips
    echo ""
    echo -e "${GREEN}━━━━━━━━━━ 代理链接 ━━━━━━━━━━${NC}"
    if [[ -n "${IPV4_ADDR}" ]]; then
        echo -e "  ${BLUE}IPv4:${NC}"
        echo "  tg://proxy?server=${IPV4_ADDR}&port=${port}&secret=${secret}"
        echo ""
    fi
    if [[ -n "${IPV6_ADDR}" ]]; then
        echo -e "  ${BLUE}IPv6:${NC}"
        echo "  tg://proxy?server=${IPV6_ADDR}&port=${port}&secret=${secret}"
        echo ""
    fi
    # 有自定义域名则输出DNS与域名链接
    if [[ -n "${custom_domain}" ]]; then
        echo -e "${CYAN}自定义域名接入（DNS解析后可用）${NC}"
        echo -e "${YELLOW}DNS配置记录:${NC}"
        if [[ -n "${IPV4_ADDR}" ]]; then
            echo "   A    记录值: ${IPV4_ADDR}"
        fi
        if [[ -n "${IPV6_ADDR}" ]]; then
            echo "   AAAA 记录值: ${IPV6_ADDR}"
        fi
        echo ""
        echo "域名链接：tg://proxy?server=${custom_domain}&port=${port}&secret=${secret}"
    fi
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
}
# ============================================================
# 域名配置（独立菜单，可随时修改）
# ============================================================
setup_domain() {
    echo ""
    echo -e "${CYAN}━━━━━━━━━━ 配置自定义域名 ━━━━━━━━━━${NC}"
    read_current_config
    detect_ips
    echo ""
    echo -e "${YELLOW}💡 将域名解析到这台服务器后，Telegram 里会显示域名而不是 IP${NC}"
    echo "当前已有域名：${CURRENT_CUSTOM_DOMAIN:-无}"
    echo ""
    local domain
    domain=$(read_input "请输入你的域名（清空留空则取消域名）" "${CURRENT_CUSTOM_DOMAIN}")
    # 更新meta里的自定义域名
    sed -i "s/^CUSTOM_DOMAIN=.*/CUSTOM_DOMAIN=${domain}/" "${META_FILE}"
    # 刷新变量
    read_current_config
    echo ""
    echo -e "${YELLOW}📋 DNS 配置记录:${NC}"
    echo "   在域名 DNS 管理面板添加以下记录："
    echo ""
    if [[ -n "${IPV4_ADDR}" ]]; then
        echo -e "   类型: ${GREEN}A${NC}    记录值: ${IPV4_ADDR}"
    fi
    if [[ -n "${IPV6_ADDR}" ]]; then
        echo -e "   类型: ${GREEN}AAAA${NC} 记录值: ${IPV6_ADDR}"
    fi
    echo ""
    echo "   主机记录填你设置的前缀（如 tg）"
    echo "   等待 DNS 生效（几分钟到几小时）"
    echo ""
    echo -e "${BLUE}🔗 最终代理链接（DNS 生效后可用）:${NC}"
    if [[ -n "${domain}" ]]; then
        echo "   tg://proxy?server=${domain}&port=${CURRENT_PORT}&secret=${CURRENT_SECRET}"
    else
        echo "   已清空自定义域名，仅使用IP连接"
    fi
    echo ""
    pause
}
# ============================================================
# 查看状态
# ============================================================
show_status() {
    echo ""
    echo -e "${CYAN}━━━━━━━━━━ 状态与链接 ━━━━━━━━━━${NC}"
    if ! is_installed; then
        echo -e "${YELLOW}未检测到 MTG 安装${NC}"
        pause
        return
    fi
    read_current_config
    print_current_config
    print_links "${CURRENT_SECRET}" "${CURRENT_PORT}" "${CURRENT_CUSTOM_DOMAIN}"
    local conn_count
    conn_count=$(journalctl -u mtg --since "1 hour ago" 2>/dev/null | grep -ci "connect" || echo 0)
    echo -e "   近1小时连接事件: ${conn_count} 次"
    pause
}
# ============================================================
# 卸载（彻底：停服务、杀进程、清防火墙、删文件）
# ============================================================
do_uninstall() {
    local force="$1"
    if [[ "${force}" != "force" ]]; then
        echo ""
        echo -e "${RED}━━━━━━━━━━ 卸载 MTG ━━━━━━━━━━${NC}"
        echo -e "${YELLOW}⚠️  将彻底删除 MTG、配置、残留进程与相关防火墙规则！${NC}"
        local confirm
        confirm=$(read_input "确认卸载？输入 y 或 yes 确认" "n")
        confirm="${confirm,,}"
        if [[ "${confirm}" != "y" && "${confirm}" != "yes" ]]; then
            echo "已取消"
            pause
            return
        fi
    fi

    # 先读端口，方便清防火墙（目录删掉前）
    local old_port=""
    if [[ -f "${CONFIG_FILE}" ]]; then
        old_port=$(grep '^bind-to' "${CONFIG_FILE}" 2>/dev/null | sed 's/.*://;s/"//g' || true)
    fi
    if [[ -z "${old_port}" && -f "${META_FILE}" ]]; then
        old_port=$(grep '^MTG_PORT=' "${META_FILE}" 2>/dev/null | cut -d= -f2 || true)
    fi

    echo -e "${BLUE}🗑️  停止 systemd 服务...${NC}"
    systemctl stop ${SERVICE_NAME} 2>/dev/null || true
    systemctl disable ${SERVICE_NAME} 2>/dev/null || true
    systemctl stop mtproto 2>/dev/null || true
    systemctl disable mtproto 2>/dev/null || true
    systemctl stop mtproxy 2>/dev/null || true
    systemctl disable mtproxy 2>/dev/null || true

    echo -e "${BLUE}🗑️  强制结束残留进程...${NC}"
    # 按单元杀
    systemctl kill -s SIGKILL ${SERVICE_NAME} 2>/dev/null || true
    # 按进程名/路径杀（覆盖手动启动、旧路径）
    pkill -9 -f '/etc/mtg/mtg' 2>/dev/null || true
    pkill -9 -f '/usr/local/mtg/mtg' 2>/dev/null || true
    pkill -9 -f '/opt/mtg/mtg' 2>/dev/null || true
    pkill -9 -x mtg 2>/dev/null || true
    pkill -9 -f 'mtg run' 2>/dev/null || true
    pkill -9 -f 'mtproto-proxy' 2>/dev/null || true
    pkill -9 -f 'mtprotoproxy' 2>/dev/null || true
    # 占用 443/9888 且命令行含 mtg 的进程
    for p in 443 9888 ${old_port}; do
        [[ -z "${p}" ]] && continue
        local pids
        pids=$(ss -lntup "sport = :${p}" 2>/dev/null | grep -oP 'pid=\K[0-9]+' | sort -u || true)
        for pid in ${pids}; do
            local cmd
            cmd=$(ps -p "${pid}" -o args= 2>/dev/null || true)
            if echo "${cmd}" | grep -qiE 'mtg|mtproto|mtproxy'; then
                kill -9 "${pid}" 2>/dev/null || true
            fi
        done
    done
    sleep 1

    echo -e "${BLUE}🗑️  删除 systemd 单元...${NC}"
    rm -f /etc/systemd/system/${SERVICE_NAME}.service
    rm -f /etc/systemd/system/mtproto.service
    rm -f /etc/systemd/system/mtproxy.service
    rm -f /lib/systemd/system/${SERVICE_NAME}.service 2>/dev/null || true
    rm -rf /etc/systemd/system/${SERVICE_NAME}.service.d 2>/dev/null || true
    systemctl daemon-reload 2>/dev/null || true
    systemctl reset-failed ${SERVICE_NAME} 2>/dev/null || true

    echo -e "${BLUE}🗑️  清理防火墙规则...${NC}"
    for p in ${old_port} 443 9888; do
        [[ -z "${p}" ]] && continue
        if command -v firewall-cmd &> /dev/null; then
            firewall-cmd --permanent --remove-port=${p}/tcp > /dev/null 2>&1 || true
        fi
        if command -v ufw &> /dev/null; then
            ufw delete allow ${p}/tcp > /dev/null 2>&1 || true
        fi
        if command -v iptables &> /dev/null; then
            while iptables -D INPUT -p tcp --dport ${p} -j ACCEPT 2>/dev/null; do :; done
        fi
    done
    if command -v firewall-cmd &> /dev/null && systemctl is-active --quiet firewalld 2>/dev/null; then
        firewall-cmd --reload > /dev/null 2>&1 || true
    fi

    echo -e "${BLUE}🗑️  删除安装目录与常见残留...${NC}"
    rm -rf "${INSTALL_DIR}"
    rm -rf /usr/local/mtg /opt/mtg /root/mtg /root/mtg-* 2>/dev/null || true
    rm -f /usr/local/bin/mtg /usr/bin/mtg 2>/dev/null || true

    # 最终确认
    local still
    still=$(ss -lntup 2>/dev/null | grep -E 'mtg|mtproto' || true)
    if [[ -n "${still}" ]]; then
        echo -e "${YELLOW}⚠️  仍检测到相关监听，尝试再次强杀...${NC}"
        echo "${still}"
        pkill -9 -f mtg 2>/dev/null || true
        sleep 1
    fi
    if ss -lntup 2>/dev/null | grep -qE 'users:\(\("mtg"'; then
        echo -e "${RED}❌ 仍有 mtg 在监听，请手动: ss -lntup | grep mtg 后 kill -9${NC}"
    else
        echo -e "${GREEN}✅ 卸载完成（已确认无 mtg 监听）${NC}"
    fi
    if [[ "${force}" != "force" ]]; then
        pause
    fi
}
# ============================================================
# 主菜单
# ============================================================
show_menu() {
    echo ""
    echo -e "${CYAN}请选择操作:${NC}"
    echo ""
    if is_installed; then
        echo -e "  ${GREEN}1.${NC} 重新安装（覆盖）"
        echo -e "  ${GREEN}2.${NC} 配置自定义域名"
        echo -e "  ${GREEN}3.${NC} 查看状态与代理链接"
        echo -e "  ${GREEN}4.${NC} 卸载 MTG"
    else
        echo -e "  ${GREEN}1.${NC} 安装 MTG Fake-TLS"
    fi
    echo -e "  ${GREEN}0.${NC} 退出"
    echo ""
}
main() {
    print_banner
    if [[ $EUID -ne 0 ]]; then
        echo -e "${RED}❌ 请使用 root 用户运行此脚本${NC}"
        echo "执行: sudo bash $0"
        exit 1
    fi
    if is_installed; then
        print_current_config
    else
        detect_ips
        print_ip_info
        echo ""
        echo -e "${YELLOW}💡 未检测到 MTG 安装${NC}"
    fi
    while true; do
        show_menu
        local choice
        choice=$(read_input "输入选项编号" "0")
        case "${choice}" in
            1)
                do_install
                print_banner
                if is_installed; then
                    print_current_config
                fi
                ;;
            2)
                if is_installed; then
                    setup_domain
                else
                    echo -e "${RED}请先安装${NC}"
                fi
                ;;
            3)
                show_status
                ;;
            4)
                do_uninstall
                print_banner
                ;;
            0|q|quit|exit)
                echo ""
                echo -e "${GREEN}👋 再见${NC}"
                exit 0
                ;;
            *)
                echo -e "${RED}无效选项${NC}"
                sleep 1
                ;;
        esac
    done
}
main "$@"