#!/bin/bash
# ==================================================
# Ubuntu 桌面环境一键安装脚本（多桌面 + VNC + noVNC + 应用安装）
# 版本: 8.0 (修复r返回上一题循环卡死问题 + 状态机架构)
# 说明: 所有提问支持r返回上一题，Edge直接下载deb，用户名必填，密码可空
# ==================================================

# -------------------- 自动安装默认参数配置 --------------------
AUTO_DESKTOP_TYPE="xfce4"               # 自动安装的桌面环境
AUTO_BROWSER_CHOICE="firefox"           # 自动安装的浏览器
AUTO_INSTALL_COMMON_SOFT="n"            # 是否安装常用基础软件
AUTO_INSTALL_VNC="y"                     # 是否安装VNC服务
AUTO_VNC_PORT="5901"                     # VNC端口号
AUTO_VNC_GEOMETRY="1280x800"             # VNC分辨率
AUTO_VNC_DEPTH="16"                       # VNC色彩深度
AUTO_VNC_ZLIB="9"                         # VNC压缩级别(0-9)
AUTO_VNC_LOCALHOST="no"                   # 是否仅允许本地访问VNC
AUTO_VNC_PASSWORD="123456"                # VNC默认密码
AUTO_VNC_START_NOW="y"                    # 是否立即启动VNC服务
AUTO_INSTALL_LANG="y"                      # 是否安装中文语言包和字体
AUTO_INSTALL_NOVNC="y"                     # 是否安装noVNC(Web端VNC)

# -------------------- 全局变量 & 颜色定义 --------------------
RED='\033[1;31m'
GREEN='\033[1;32m'
YELLOW='\033[1;33m'
BLUE='\033[1;34m'
PURPLE='\033[1;35m'
CYAN='\033[1;36m'
WHITE='\033[1;37m'
NC='\033[0m'

# 全局变量
declare -a QUESTION_STACK
declare -g CURRENT_STEP=""
declare -g BACK_TO_PREV=0
declare -g CURRENT_USER=$(whoami)
declare -g CURRENT_HOME=$HOME
declare -g TARGET_USER=""
declare -g TARGET_HOME=""
declare -g LOCKFILE=""
declare -g DESKTOP_TYPE=""
declare -g DESKTOP_CMD=""
declare -g BROWSER_CHOICE=""
declare -g INSTALL_COMMON_SOFT=""
declare -g INSTALL_VNC=""
declare -g VNC_PORT=""
declare -g VNC_DISPLAY=""
declare -g VNC_GEOMETRY=""
declare -g VNC_DEPTH=""
declare -g VNC_ZLIB=""
declare -g VNC_LOCALHOST=""
declare -g VNC_PASSWORD=""
declare -g VNC_START_NOW=""
declare -g INSTALL_LANG=""
declare -g INSTALL_NOVNC=""

# -------------------- 工具函数 --------------------
print_info() { echo -e "${GREEN}[信息]${NC} $1"; }
print_warn() { echo -e "${YELLOW}[警告]${NC} $1"; }
print_error() { echo -e "${RED}[错误]${NC} $1"; }
print_success() { echo -e "${GREEN}[成功]${NC} $1"; }
print_title() { echo -e "\n${CYAN}========== $1 ==========${NC}\n"; }

# 清空问题栈
reset_question_stack() {
    QUESTION_STACK=()
    CURRENT_STEP=""
    BACK_TO_PREV=0
}

# 压入当前问题
push_question() {
    local qid="$1"
    if [[ "$CURRENT_STEP" != "" ]]; then
        QUESTION_STACK+=("$CURRENT_STEP")
    fi
    CURRENT_STEP="$qid"
}

# 弹出上一个问题
pop_question() {
    if [[ ${#QUESTION_STACK[@]} -gt 0 ]]; then
        CURRENT_STEP="${QUESTION_STACK[-1]}"
        unset 'QUESTION_STACK[-1]'
    else
        CURRENT_STEP=""
    fi
}

# 获取上一个问题
get_prev_step() {
    if [[ ${#QUESTION_STACK[@]} -gt 0 ]]; then
        echo "${QUESTION_STACK[-1]}"
    else
        echo ""
    fi
}

clear_screen() {
    clear
    echo -e "${PURPLE}"
    echo "╔══════════════════════════════════════════════════════════╗"
    echo "║         Ubuntu 桌面环境安装工具 (多桌面+VNC+应用)        ║"
    echo "║               QQ/微信/FinalShell/Cursor 全支持           ║"
    echo "╚══════════════════════════════════════════════════════════╝"
    echo -e "${NC}"
}

# 核心：支持y/n/r的询问
ask_yes_no() {
    local prompt="$1 (y/n/r) [默认: y]: "
    local qid="$2"
    local default="y"
    local answer
    
    push_question "$qid"
    while true; do
        read -p "$prompt" -r answer
        answer=${answer:-$default}
        
        if [[ "$answer" =~ ^[Rr]$ ]]; then
            pop_question
            echo "返回上一个问题..."
            BACK_TO_PREV=1
            return 1
        fi
        
        if [[ "$answer" =~ ^[YyNn]$ ]]; then
            break
        else
            print_error "无效输入！请输入 y (是) / n (否) / r (返回上一题)。"
        fi
    done
    
    [[ "$answer" =~ ^[Yy]$ ]] && return 0 || return 2
}

# 核心：支持输入+返回上一题的询问
ask_input() {
    local prompt="$1"
    local qid="$2"
    local default="$3"
    local answer
    
    push_question "$qid"
    while true; do
        if [[ -n "$default" ]]; then
            read -p "$prompt [默认: $default]: " -r answer
        else
            read -p "$prompt: " -r answer
        fi
        answer=${answer:-$default}
        
        if [[ "$answer" =~ ^[Rr]$ ]]; then
            pop_question
            echo "返回上一个问题..."
            BACK_TO_PREV=1
            return 1
        fi
        
        if [[ -z "$answer" && "$qid" =~ "username" ]]; then
            print_error "该选项不能为空，请重新输入！"
        else
            break
        fi
    done
    
    echo "$answer"
    return 0
}

# 确认操作
confirm_action() {
    local prompt="$1 [y/n/r]: "
    local qid="$2"
    local answer
    
    push_question "$qid"
    while true; do
        read -p "$prompt" -r answer
        answer=${answer:-n}
        
        if [[ "$answer" =~ ^[Rr]$ ]]; then
            pop_question
            echo "返回上一个问题..."
            BACK_TO_PREV=1
            return 1
        fi
        
        if [[ "$answer" =~ ^[YyNn]$ ]]; then
            break
        else
            print_error "无效输入！请输入 y (是) / n (否) / r (返回上一题)。"
        fi
    done
    
    [[ "$answer" =~ ^[Yy]$ ]] && return 0 || return 2
}

is_root() { [[ $EUID -eq 0 ]]; }
has_sudo() { sudo -n true 2>/dev/null; }

run_cmd() {
    local cmd="$1"
    if [[ -n "$TARGET_USER" && "$TARGET_USER" != "root" ]]; then
        cmd="${cmd//\/root\//\/home\/$TARGET_USER\/}"
    fi
    if ! is_root; then
        if [[ ! "$cmd" =~ ^sudo[[:space:]] ]]; then
            if [[ "$cmd" =~ ^(apt|apt-get|dpkg|systemctl|useradd|chpasswd|usermod|mkdir|cat|tee|rm|chmod|add-apt-repository|locale-gen|update-locale|curl|wget|dpkg) ]]; then
                cmd="sudo $cmd"
            fi
        fi
    else
        cmd="${cmd#sudo }"
    fi
    eval "$cmd"
    return $?
}

is_pkg_installed() { dpkg -l "$1" 2>/dev/null | grep -q ^ii; }
is_cmd_installed() { command -v "$1" >/dev/null 2>&1; }

check_desktop_installed() {
    local desktop_pkgs=("xfce4" "ubuntu-desktop" "xubuntu-desktop" "kde-plasma-desktop" "mate-desktop" "lxqt" "gnome-session")
    local installed=()
    for pkg in "${desktop_pkgs[@]}"; do
        if is_pkg_installed "$pkg"; then
            installed+=("$pkg")
        fi
    done
    if [[ ${#installed[@]} -eq 0 ]]; then
        print_warn "未检测到已安装的桌面环境，部分图形应用可能无法正常使用。"
        print_info "你可以先运行选项 1 或 2 安装桌面环境。"
    else
        print_info "检测到已安装桌面环境: ${installed[*]}"
    fi
}

check_lockfile() { [[ -f "$LOCKFILE" ]]; }

generate_lockfile() {
    local install_time=$(date '+%Y-%m-%d %H:%M:%S')
    cat > "$LOCKFILE" <<EOF
{
    "install_time": "$install_time",
    "install_user": "$TARGET_USER",
    "desktop": "$DESKTOP_TYPE",
    "vnc_port": ${VNC_PORT:-null},
    "vnc_password_set": ${VNC_PASSWORD:+true},
    "browser": "${BROWSER_CHOICE:-none}",
    "common_software": ${INSTALL_COMMON_SOFT:-false},
    "language_pack": ${INSTALL_LANG:-false},
    "novnc": ${INSTALL_NOVNC:-false}
}
EOF
    chown "$TARGET_USER":"$TARGET_USER" "$LOCKFILE" 2>/dev/null || true
}

read_lockfile() {
    if [[ -f "$LOCKFILE" ]]; then
        DESKTOP_TYPE=$(grep -Po '"desktop": *"\K[^"]*' "$LOCKFILE" 2>/dev/null)
        VNC_PORT=$(grep -Po '"vnc_port": *\K[0-9]+' "$LOCKFILE" 2>/dev/null)
        BROWSER_CHOICE=$(grep -Po '"browser": *"\K[^"]*' "$LOCKFILE" 2>/dev/null)
    fi
}

port_to_display() { echo $(($1 - 5900)); }

get_public_ip() {
    curl -s --max-time 2 ifconfig.me || curl -s --max-time 2 icanhazip.com || echo "无法获取公网IP"
}

# -------------------- 用户权限设置 --------------------
setup_user_permissions() {
    print_title "用户权限设置"
    reset_question_stack
    
    if is_root; then
        print_warn "当前是 root 用户，强烈建议使用普通用户运行桌面环境！"
        ask_yes_no "是否切换到普通用户" "switch_user"
        local res=$?
        if [[ $res -eq 1 ]]; then
            BACK_TO_PREV=0
            return 1  # 需要回退
        elif [[ $res -eq 0 ]]; then
            # 选择切换普通用户
            while true; do
                new_user=$(ask_input "请输入要使用的用户名" "input_username" "")
                if [[ $? -eq 1 ]]; then
                    BACK_TO_PREV=0
                    continue
                fi
                
                if id "$new_user" &>/dev/null; then
                    print_warn "用户 $new_user 已存在。"
                    ask_yes_no "是否使用该用户" "use_exist_user"
                    local use_res=$?
                    if [[ $use_res -eq 1 ]]; then
                        BACK_TO_PREV=0
                        continue
                    elif [[ $use_res -eq 0 ]]; then
                        TARGET_USER="$new_user"
                        TARGET_HOME="/home/$new_user"
                        LOCKFILE="$TARGET_HOME/vncinstall.lock"
                        run_cmd "usermod -aG sudo $TARGET_USER"
                        print_success "已将 $TARGET_USER 添加到 sudo 组。"
                        break
                    fi
                else
                    while true; do
                        read -s -p "设置密码 (留空则默认 123456): " new_pass
                        echo
                        new_pass=${new_pass:-123456}
                        if [[ -z "$new_pass" ]]; then
                            print_error "密码不能为空，请重新输入！"
                            continue
                        fi
                        run_cmd "useradd -m -s /bin/bash $new_user"
                        echo "$new_user:$new_pass" | run_cmd "chpasswd"
                        run_cmd "usermod -aG sudo $new_user"
                        TARGET_USER="$new_user"
                        TARGET_HOME="/home/$new_user"
                        LOCKFILE="$TARGET_HOME/vncinstall.lock"
                        print_success "用户 $TARGET_USER 创建完成并已加入 sudo 组。"
                        break 2
                    done
                fi
            done
        else
            print_info "继续使用 root 用户安装。"
            TARGET_USER="root"
            TARGET_HOME="/root"
            LOCKFILE="/root/vncinstall.lock"
        fi
    else
        if has_sudo; then
            print_info "当前用户: $CURRENT_USER (拥有 sudo 权限)"
            ask_yes_no "是否使用当前用户 $CURRENT_USER 进行安装" "use_current_user"
            local res=$?
            if [[ $res -eq 1 ]]; then
                BACK_TO_PREV=0
                return 1
            elif [[ $res -eq 0 ]]; then
                TARGET_USER="$CURRENT_USER"
                TARGET_HOME="$HOME"
                LOCKFILE="$HOME/vncinstall.lock"
            else
                # 不使用当前用户，创建新用户
                while true; do
                    new_user=$(ask_input "请输入要使用的用户名" "input_new_username" "")
                    if [[ $? -eq 1 ]]; then
                        BACK_TO_PREV=0
                        continue
                    fi
                    
                    if id "$new_user" &>/dev/null; then
                        print_warn "用户 $new_user 已存在。"
                        ask_yes_no "是否使用该用户" "use_exist_user2"
                        local use_res=$?
                        if [[ $use_res -eq 1 ]]; then
                            BACK_TO_PREV=0
                            continue
                        elif [[ $use_res -eq 0 ]]; then
                            TARGET_USER="$new_user"
                            TARGET_HOME="/home/$new_user"
                            LOCKFILE="$TARGET_HOME/vncinstall.lock"
                            run_cmd "usermod -aG sudo $TARGET_USER"
                            print_success "已将 $TARGET_USER 添加到 sudo 组。"
                            break
                        fi
                    else
                        while true; do
                            read -s -p "设置密码 (留空则默认 123456): " new_pass
                            echo
                            new_pass=${new_pass:-123456}
                            run_cmd "useradd -m -s /bin/bash $new_user"
                            echo "$new_user:$new_pass" | run_cmd "chpasswd"
                            run_cmd "usermod -aG sudo $new_user"
                            TARGET_USER="$new_user"
                            TARGET_HOME="/home/$new_user"
                            LOCKFILE="$TARGET_HOME/vncinstall.lock"
                            print_success "用户 $TARGET_USER 创建完成并已加入 sudo 组。"
                            break 2
                        done
                    fi
                done
            fi
        else
            print_error "当前用户无 sudo 权限，无法继续。"
            exit 1
        fi
    fi
    
    export TARGET_USER TARGET_HOME LOCKFILE
    return 0
}

# -------------------- 安装函数 --------------------
install_base() {
    print_info "更新系统并安装基础软件包..."
    run_cmd "DEBIAN_FRONTEND=noninteractive apt update"
    run_cmd "DEBIAN_FRONTEND=noninteractive apt upgrade -y"
    run_cmd "apt install -y wget curl nano net-tools htop git ca-certificates software-properties-common"
}

install_desktop() {
    print_title "安装桌面环境: $DESKTOP_TYPE"
    case "$DESKTOP_TYPE" in
        xfce4)
            run_cmd "apt install -y xfce4 xfce4-goodies xfce4-terminal"
            DESKTOP_CMD="startxfce4"
            ;;
        xubuntu)
            run_cmd "apt install xubuntu-desktop -y"
            DESKTOP_CMD="startxfce4"
            ;;
        xfce-lite)
            run_cmd "apt install -y --no-install-recommends xfce4 xfce4-terminal"
            DESKTOP_CMD="startxfce4"
            ;;
        lxqt)
            run_cmd "add-apt-repository ppa:lxqt/stable -y"
            run_cmd "apt update"
            run_cmd "apt install lxqt -y"
            DESKTOP_CMD="startlxqt"
            ;;
        kde-full)
            run_cmd "apt install kde-full -y"
            DESKTOP_CMD="startkde"
            ;;
        kde-standard)
            run_cmd "apt install kde-standard -y"
            DESKTOP_CMD="startkde"
            ;;
        kde-plasma)
            run_cmd "apt install kde-plasma-desktop -y"
            DESKTOP_CMD="startkde"
            ;;
        mate-core)
            run_cmd "apt update && apt install mate-desktop-environment-core -y"
            DESKTOP_CMD="mate-session"
            ;;
        mate-full)
            run_cmd "apt install mate-desktop-environment-extras -y"
            DESKTOP_CMD="mate-session"
            ;;
        gnome-ubuntu)
            run_cmd "apt install ubuntu-gnome-desktop -y"
            DESKTOP_CMD="gnome-session"
            ;;
        gnome-core)
            run_cmd "apt install ubuntu-desktop -y"
            DESKTOP_CMD="gnome-session"
            ;;
        *)
            print_error "未知的桌面类型"
            exit 1
            ;;
    esac
    run_cmd "apt-get install -y dbus-x11"
}

# 浏览器安装
install_browser_google() {
    print_info "安装 Google Chrome..."
    run_cmd "wget -O chrome.deb \"https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb\""
    run_cmd "apt install -f -y"
    run_cmd "dpkg -i chrome.deb"
    run_cmd "apt --fix-broken install -y"
    run_cmd "rm chrome.deb"
}

install_browser_edge() {
    print_info "安装 Microsoft Edge (直接下载 deb)..."
    local url="https://packages.microsoft.com/repos/edge/pool/main/m/microsoft-edge-stable/microsoft-edge-stable_125.0.2535.51-1_amd64.deb"
    local deb_file="/tmp/edge.deb"
    run_cmd "wget -O $deb_file $url"
    run_cmd "dpkg -i $deb_file"
    run_cmd "apt --fix-broken install -y"
    run_cmd "rm -f $deb_file"
    print_success "Microsoft Edge 安装完成"
}

install_browser_firefox() {
    print_info "安装 Firefox (官方仓库版)..."
    run_cmd "install -d -m 0755 /etc/apt/keyrings"
    run_cmd "wget -q https://packages.mozilla.org/apt/repo-signing-key.gpg -O- | tee /etc/apt/keyrings/packages.mozilla.org.asc > /dev/null"
    run_cmd "cat <<EOF | tee /etc/apt/sources.list.d/mozilla.sources
Types: deb
URIs: https://packages.mozilla.org/apt
Suites: mozilla
Components: main
Signed-By: /etc/apt/keyrings/packages.mozilla.org.asc
EOF"
    run_cmd "echo '
Package: *
Pin: origin packages.mozilla.org
Pin-Priority: 1000
' | tee /etc/apt/preferences.d/mozilla"
    run_cmd "apt-get update && apt-get install firefox -y"
}

# 应用安装
install_qq() {
    print_info "安装 QQ (Linux版)..."
    local url="https://dldir1v6.qq.com/qqfile/qq/QQNT/Linux/QQ_3.2.25_260205_amd64_01.deb"
    local deb_file="/tmp/qq.deb"
    run_cmd "wget -O $deb_file $url"
    run_cmd "dpkg -i $deb_file"
    run_cmd "apt --fix-broken install -y"
    run_cmd "rm -f $deb_file"
    print_success "QQ 安装完成"
}

install_wechat() {
    print_info "安装 微信 (Linux版)..."
    local url="https://dldir1v6.qq.com/weixin/Universal/Linux/WeChatLinux_x86_64.deb"
    local deb_file="/tmp/wechat.deb"
    run_cmd "wget -O $deb_file $url"
    run_cmd "dpkg -i $deb_file"
    run_cmd "apt --fix-broken install -y"
    run_cmd "rm -f $deb_file"
    print_success "微信 安装完成"
}

install_finalshell() {
    print_info "安装 FinalShell..."
    local url="https://dl.hostbuf.com/finalshell3/finalshell_linux_x64.deb"
    local deb_file="/tmp/finalshell.deb"
    run_cmd "wget -O $deb_file $url"
    run_cmd "dpkg -i $deb_file"
    run_cmd "apt --fix-broken install -y"
    run_cmd "rm -f $deb_file"
    print_success "FinalShell 安装完成"
}

install_cursor() {
    print_info "安装 Cursor 编辑器..."
    run_cmd "curl -fsSL https://downloads.cursor.com/keys/anysphere.asc | gpg --dearmor | tee /etc/apt/keyrings/cursor.gpg > /dev/null"
    run_cmd "echo 'deb [arch=amd64,arm64 signed-by=/etc/apt/keyrings/cursor.gpg] https://downloads.cursor.com/aptrepo stable main' | tee /etc/apt/sources.list.d/cursor.list > /dev/null"
    run_cmd "apt update"
    run_cmd "apt install -y cursor"
    print_success "Cursor 安装完成"
}

install_realvnc_viewer() {
    print_info "安装 RealVNC Viewer..."
    local url="https://downloads.realvnc.com/download/file/viewer.files/VNC-Viewer-7.15.1-Linux-x64.deb"
    local deb_file="/tmp/realvnc-viewer.deb"
    run_cmd "wget -O $deb_file $url"
    run_cmd "dpkg -i $deb_file"
    run_cmd "apt --fix-broken install -y"
    run_cmd "rm -f $deb_file"
    print_success "RealVNC Viewer 安装完成"
}

install_ibus() {
    print_info "安装 IBus 输入法框架及拼音引擎..."
    run_cmd "apt update"
    run_cmd "apt install -y ibus ibus-pinyin ibus-clutter ibus-gtk ibus-gtk3 ibus-qt4"
    
    if ! locale -a | grep -q zh_CN.utf8; then
        run_cmd "apt install -y language-pack-zh-hans"
    fi
    run_cmd "update-locale LANG=zh_CN.UTF-8 LC_ALL=zh_CN.UTF-8"
    run_cmd "im-config -s ibus"
    
    local profile_file="$TARGET_HOME/.xprofile"
    if [[ ! -f "$profile_file" ]]; then
        profile_file="$TARGET_HOME/.profile"
    fi
    if ! grep -q "ibus-daemon" "$profile_file" 2>/dev/null; then
        echo '' >> "$profile_file"
        echo '# 自动启动 IBus 输入法' >> "$profile_file"
        echo 'export GTK_IM_MODULE=ibus' >> "$profile_file"
        echo 'export QT_IM_MODULE=ibus' >> "$profile_file"
        echo 'export XMODIFIERS=@im=ibus' >> "$profile_file"
        echo 'ibus-daemon -drx' >> "$profile_file"
        print_success "已添加 IBus 自动启动到 $profile_file"
    fi
    
    if [[ -n "$DISPLAY" ]]; then
        export GTK_IM_MODULE=ibus
        export QT_IM_MODULE=ibus
        export XMODIFIERS=@im=ibus
        ibus-daemon -drx 2>/dev/null &
        print_info "IBus 已尝试在当前会话启动"
    fi
    print_success "IBus 安装完成，重启后输入法将自动生效。"
}

install_fcitx5() {
    print_info "安装 Fcitx5 中文输入法..."
    run_cmd "apt install -y fcitx5 fcitx5-chinese-addons fcitx5-frontend-qt5 fcitx5-frontend-gtk3 fcitx5-frontend-gtk2 fcitx5-config-qt"
    print_info "Fcitx5 安装完成，请重启后通过 im-config 配置输入法。"
}

install_vscode() {
    print_info "安装 Visual Studio Code..."
    run_cmd "wget -qO- https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > packages.microsoft.gpg"
    run_cmd "install -o root -g root -m 644 packages.microsoft.gpg /etc/apt/trusted.gpg.d/"
    run_cmd "sh -c 'echo \"deb [arch=amd64] https://packages.microsoft.com/repos/code stable main\" > /etc/apt/sources.list.d/vscode.list'"
    run_cmd "rm -f packages.microsoft.gpg"
    run_cmd "apt update"
    run_cmd "apt install -y code"
}

install_vlc() { run_cmd "apt install -y vlc"; }
install_mpv() { run_cmd "apt install -y mpv"; }
install_libreoffice() { run_cmd "apt install -y libreoffice"; }
install_flameshot() { run_cmd "apt install -y flameshot"; }
install_compression_tools() { run_cmd "apt install -y p7zip-full unrar"; }
install_sys_tools() { run_cmd "apt install -y neofetch htop tmux"; }
install_common_soft() {
    run_cmd "apt install -y gedit mousepad ristretto"
    run_cmd "apt install -y gnome-disk-utility gnome-system-monitor"
}

install_vnc() {
    print_title "安装 TigerVNC"
    run_cmd "apt install -y tigervnc-standalone-server tigervnc-xorg-extension"
    run_cmd "mkdir -p $TARGET_HOME/.vnc/"
    
    local xstartup_path="$TARGET_HOME/.vnc/xstartup"
    run_cmd "touch $xstartup_path"
    cat > /tmp/xstartup.tmp <<EOF
#!/bin/bash
export LANG=zh_CN.UTF-8
export LC_ALL=zh_CN.UTF-8
fcitx5 &
xset s off
xset -dpms
xset s noblank
exec $DESKTOP_CMD
EOF
    if is_root || [[ "$TARGET_USER" == "root" ]]; then
        cp /tmp/xstartup.tmp "$xstartup_path"
    else
        sudo -u "$TARGET_USER" cp /tmp/xstartup.tmp "$xstartup_path"
    fi
    rm /tmp/xstartup.tmp
    run_cmd "chmod +x $xstartup_path"
    run_cmd "chown -R $TARGET_USER:$TARGET_USER $TARGET_HOME/.vnc/"
    
    if [[ -n "$VNC_PASSWORD" ]]; then
        print_info "设置 VNC 密码..."
        if is_root || [[ "$TARGET_USER" == "root" ]]; then
            printf "%s\n%s\nn\n" "$VNC_PASSWORD" "$VNC_PASSWORD" | vncpasswd >/dev/null 2>&1
        else
            sudo -u "$TARGET_USER" bash -c "printf '%s\n%s\nn\n' \"$VNC_PASSWORD\" \"$VNC_PASSWORD\" | vncpasswd >/dev/null 2>&1"
        fi
    fi
    
    local display_num=$(port_to_display $VNC_PORT)
    local service_name="vncserver@$display_num.service"
    local pid_path="$TARGET_HOME/.vnc/%H.local:$display_num.pid"
    
    cat > /tmp/vncserver.service.tmp <<EOF
[Unit]
Description=Remote desktop service (VNC)
After=syslog.target network.target
[Service]
Type=forking
User=$TARGET_USER
Group=$TARGET_USER
WorkingDirectory=$TARGET_HOME
PIDFile=$pid_path
ExecStart=/usr/bin/vncserver :$display_num -geometry $VNC_GEOMETRY -depth $VNC_DEPTH -ZlibLevel $VNC_ZLIB -localhost $VNC_LOCALHOST
ExecStop=-/usr/bin/vncserver -kill :$display_num
[Install]
WantedBy=multi-user.target
EOF
    
    if is_root; then
        cp /tmp/vncserver.service.tmp "/etc/systemd/system/$service_name"
    else
        sudo cp /tmp/vncserver.service.tmp "/etc/systemd/system/$service_name"
    fi
    rm /tmp/vncserver.service.tmp
    
    run_cmd "systemctl daemon-reload"
    run_cmd "systemctl enable $service_name"
    
    if [[ "$VNC_START_NOW" == "y" ]]; then
        run_cmd "systemctl start $service_name"
    fi
}

install_language() {
    print_info "安装中文语言包及字体..."
    run_cmd "apt install -y language-pack-zh-hans language-pack-zh-hans-base"
    run_cmd "apt install -y fonts-wqy-microhei fonts-wqy-zenhei fonts-noto-cjk"
    run_cmd "locale-gen zh_CN.UTF-8"
    run_cmd "update-locale LANG=zh_CN.UTF-8 LC_ALL=zh_CN.UTF-8"
    cat > /tmp/locale.tmp <<'EOF'
LANG=zh_CN.UTF-8
LANGUAGE=zh_CN:zh
LC_NUMERIC="zh_CN.UTF-8"
LC_TIME="zh_CN.UTF-8"
LC_MONETARY="zh_CN.UTF-8"
LC_PAPER="zh_CN.UTF-8"
LC_NAME="zh_CN.UTF-8"
LC_ADDRESS="zh_CN.UTF-8"
LC_TELEPHONE="zh_CN.UTF-8"
LC_MEASUREMENT="zh_CN.UTF-8"
LC_IDENTIFICATION="zh_CN.UTF-8"
EOF
    if is_root; then
        cp /tmp/locale.tmp /etc/default/locale
    else
        sudo cp /tmp/locale.tmp /etc/default/locale
    fi
    rm /tmp/locale.tmp
}

install_novnc() {
    print_info "安装 noVNC (使用远程脚本)..."
    local display_num=$(port_to_display $VNC_PORT)
    local cmd="bash <(curl -L http://sh.802213.xyz/novnc/install.sh) -auto -vncport=$VNC_PORT"
    run_cmd "$cmd" || print_warn "noVNC 安装脚本执行失败，请手动检查。"
    run_cmd "systemctl restart vncserver@$display_num.service"
}

# 一键安装全部应用
install_all_apps() {
    print_title "一键安装全部应用"
    echo "即将安装以下应用:"
    echo "  - QQ (Linux版)"
    echo "  - 微信 (Linux版)"
    echo "  - FinalShell (SSH客户端)"
    echo "  - Cursor 编辑器"
    echo "  - RealVNC Viewer"
    echo "  - IBus 输入法 (含拼音)"
    echo
    
    confirm_action "确认安装全部应用" "confirm_install_all"
    local res=$?
    if [[ $res -eq 1 ]]; then
        BACK_TO_PREV=0
        return
    elif [[ $res -eq 2 ]]; then
        return
    fi
    
    install_qq
    install_wechat
    install_finalshell
    install_cursor
    install_realvnc_viewer
    install_ibus
    
    print_success "全部应用安装完成！"
    read -p "按回车键返回主菜单..." -r
}

# 一键卸载全部应用
uninstall_all_apps() {
    print_title "一键卸载全部应用"
    echo "即将卸载以下应用:"
    echo "  - QQ"
    echo "  - 微信"
    echo "  - FinalShell"
    echo "  - Cursor"
    echo "  - RealVNC Viewer"
    echo "  - IBus 输入法"
    echo
    
    confirm_action "确认卸载全部应用" "confirm_uninstall_all"
    local res1=$?
    if [[ $res1 -eq 1 ]]; then
        BACK_TO_PREV=0
        return
    elif [[ $res1 -eq 2 ]]; then
        return
    fi
    
    confirm_action "【最后确认】确定要卸载所有上述应用吗" "confirm_uninstall_all_final"
    local res2=$?
    if [[ $res2 -eq 1 ]]; then
        BACK_TO_PREV=0
        return
    elif [[ $res2 -eq 2 ]]; then
        return
    fi
    
    run_cmd "dpkg -r qq 2>/dev/null || true"
    run_cmd "dpkg -r wechat 2>/dev/null || true"
    run_cmd "dpkg -r finalshell 2>/dev/null || true"
    run_cmd "apt remove -y cursor 2>/dev/null || true"
    run_cmd "dpkg -r realvnc-vnc-viewer 2>/dev/null || true"
    run_cmd "apt remove -y ibus* 2>/dev/null || true"
    
    run_cmd "rm -f /etc/apt/sources.list.d/cursor.list"
    run_cmd "rm -f /etc/apt/keyrings/cursor.gpg"
    
    run_cmd "apt autoremove -y"
    run_cmd "apt update"
    
    print_success "全部应用卸载完成！"
    read -p "按回车键返回主菜单..." -r
}

# -------------------- 应用安装菜单 --------------------
install_apps_menu() {
    print_title "独立应用安装"
    check_desktop_installed
    echo
    
    echo "请选择要安装的应用（可多选，输入序号用空格分隔）:"
    echo "  1) Firefox (官方仓库最新版)"
    echo "  2) Microsoft Edge (直接下载 deb)"
    echo "  3) Google Chrome"
    echo "  4) Fcitx5 中文输入法"
    echo "  5) Visual Studio Code"
    echo "  6) VLC 播放器"
    echo "  7) MPV 播放器"
    echo "  8) LibreOffice 办公套件"
    echo "  9) Flameshot 截图工具"
    echo " 10) 压缩工具 (7zip, unrar)"
    echo " 11) 系统工具 (neofetch, htop, tmux)"
    echo " 12) QQ (Linux版)"
    echo " 13) 微信 (Linux版)"
    echo " 14) FinalShell (SSH客户端)"
    echo " 15) Cursor 编辑器 (AI编程)"
    echo " 16) RealVNC Viewer (VNC客户端)"
    echo " 17) IBus 输入法 (含拼音，自动配置中文)"
    echo "  0) 返回主菜单"
    echo
    
    app_choices=$(ask_input "请输入序号 (可多选，如: 1 12 13)" "select_apps" "")
    local res=$?
    if [[ $res -eq 1 ]]; then
        BACK_TO_PREV=0
        return
    fi
    
    if [[ -z "$app_choices" || "$app_choices" == "0" ]]; then
        return
    fi
    
    for choice in $app_choices; do
        case $choice in
            1)
                if is_pkg_installed firefox; then
                    ask_yes_no "Firefox 已安装，是否重新安装" "reinstall_firefox"
                    local res=$?
                    if [[ $res -eq 1 ]]; then
                        BACK_TO_PREV=0
                        continue
                    elif [[ $res -eq 0 ]]; then
                        install_browser_firefox
                    fi
                else
                    install_browser_firefox
                fi
                ;;
            2)
                if is_pkg_installed microsoft-edge-stable; then
                    ask_yes_no "Microsoft Edge 已安装，是否重新安装" "reinstall_edge"
                    local res=$?
                    if [[ $res -eq 1 ]]; then
                        BACK_TO_PREV=0
                        continue
                    elif [[ $res -eq 0 ]]; then
                        install_browser_edge
                    fi
                else
                    install_browser_edge
                fi
                ;;
            3)
                if is_pkg_installed google-chrome-stable; then
                    ask_yes_no "Google Chrome 已安装，是否重新安装" "reinstall_chrome"
                    local res=$?
                    if [[ $res -eq 1 ]]; then
                        BACK_TO_PREV=0
                        continue
                    elif [[ $res -eq 0 ]]; then
                        install_browser_google
                    fi
                else
                    install_browser_google
                fi
                ;;
            4)
                if is_pkg_installed fcitx5; then
                    ask_yes_no "Fcitx5 已安装，是否重新安装" "reinstall_fcitx5"
                    local res=$?
                    if [[ $res -eq 1 ]]; then
                        BACK_TO_PREV=0
                        continue
                    elif [[ $res -eq 0 ]]; then
                        install_fcitx5
                    fi
                else
                    install_fcitx5
                fi
                ;;
            5)
                if is_cmd_installed code; then
                    ask_yes_no "VS Code 已安装，是否重新安装" "reinstall_vscode"
                    local res=$?
                    if [[ $res -eq 1 ]]; then
                        BACK_TO_PREV=0
                        continue
                    elif [[ $res -eq 0 ]]; then
                        install_vscode
                    fi
                else
                    install_vscode
                fi
                ;;
            6)
                if is_pkg_installed vlc; then
                    ask_yes_no "VLC 已安装，是否重新安装" "reinstall_vlc"
                    local res=$?
                    if [[ $res -eq 1 ]]; then
                        BACK_TO_PREV=0
                        continue
                    elif [[ $res -eq 0 ]]; then
                        install_vlc
                    fi
                else
                    install_vlc
                fi
                ;;
            7)
                if is_pkg_installed mpv; then
                    ask_yes_no "MPV 已安装，是否重新安装" "reinstall_mpv"
                    local res=$?
                    if [[ $res -eq 1 ]]; then
                        BACK_TO_PREV=0
                        continue
                    elif [[ $res -eq 0 ]]; then
                        install_mpv
                    fi
                else
                    install_mpv
                fi
                ;;
            8)
                if is_pkg_installed libreoffice; then
                    ask_yes_no "LibreOffice 已安装，是否重新安装" "reinstall_libreoffice"
                    local res=$?
                    if [[ $res -eq 1 ]]; then
                        BACK_TO_PREV=0
                        continue
                    elif [[ $res -eq 0 ]]; then
                        install_libreoffice
                    fi
                else
                    install_libreoffice
                fi
                ;;
            9)
                if is_pkg_installed flameshot; then
                    ask_yes_no "Flameshot 已安装，是否重新安装" "reinstall_flameshot"
                    local res=$?
                    if [[ $res -eq 1 ]]; then
                        BACK_TO_PREV=0
                        continue
                    elif [[ $res -eq 0 ]]; then
                        install_flameshot
                    fi
                else
                    install_flameshot
                fi
                ;;
            10)
                if is_pkg_installed p7zip-full && is_pkg_installed unrar; then
                    ask_yes_no "压缩工具已安装，是否重新安装" "reinstall_compress"
                    local res=$?
                    if [[ $res -eq 1 ]]; then
                        BACK_TO_PREV=0
                        continue
                    elif [[ $res -eq 0 ]]; then
                        install_compression_tools
                    fi
                else
                    install_compression_tools
                fi
                ;;
            11)
                if is_cmd_installed neofetch && is_cmd_installed htop && is_cmd_installed tmux; then
                    ask_yes_no "系统工具已安装，是否重新安装" "reinstall_sys_tools"
                    local res=$?
                    if [[ $res -eq 1 ]]; then
                        BACK_TO_PREV=0
                        continue
                    elif [[ $res -eq 0 ]]; then
                        install_sys_tools
                    fi
                else
                    install_sys_tools
                fi
                ;;
            12)
                if is_pkg_installed qq; then
                    ask_yes_no "QQ 已安装，是否重新安装" "reinstall_qq"
                    local res=$?
                    if [[ $res -eq 1 ]]; then
                        BACK_TO_PREV=0
                        continue
                    elif [[ $res -eq 0 ]]; then
                        install_qq
                    fi
                else
                    install_qq
                fi
                ;;
            13)
                if is_pkg_installed wechat; then
                    ask_yes_no "微信已安装，是否重新安装" "reinstall_wechat"
                    local res=$?
                    if [[ $res -eq 1 ]]; then
                        BACK_TO_PREV=0
                        continue
                    elif [[ $res -eq 0 ]]; then
                        install_wechat
                    fi
                else
                    install_wechat
                fi
                ;;
            14)
                if is_pkg_installed finalshell; then
                    ask_yes_no "FinalShell 已安装，是否重新安装" "reinstall_finalshell"
                    local res=$?
                    if [[ $res -eq 1 ]]; then
                        BACK_TO_PREV=0
                        continue
                    elif [[ $res -eq 0 ]]; then
                        install_finalshell
                    fi
                else
                    install_finalshell
                fi
                ;;
            15)
                if is_cmd_installed cursor; then
                    ask_yes_no "Cursor 已安装，是否重新安装" "reinstall_cursor"
                    local res=$?
                    if [[ $res -eq 1 ]]; then
                        BACK_TO_PREV=0
                        continue
                    elif [[ $res -eq 0 ]]; then
                        install_cursor
                    fi
                else
                    install_cursor
                fi
                ;;
            16)
                if is_pkg_installed realvnc-vnc-viewer; then
                    ask_yes_no "RealVNC Viewer 已安装，是否重新安装" "reinstall_realvnc"
                    local res=$?
                    if [[ $res -eq 1 ]]; then
                        BACK_TO_PREV=0
                        continue
                    elif [[ $res -eq 0 ]]; then
                        install_realvnc_viewer
                    fi
                else
                    install_realvnc_viewer
                fi
                ;;
            17)
                if is_pkg_installed ibus; then
                    ask_yes_no "IBus 已安装，是否重新安装并配置" "reinstall_ibus"
                    local res=$?
                    if [[ $res -eq 1 ]]; then
                        BACK_TO_PREV=0
                        continue
                    elif [[ $res -eq 0 ]]; then
                        install_ibus
                    fi
                else
                    install_ibus
                fi
                ;;
            *)
                print_warn "无效选项: $choice，已跳过"
                ;;
        esac
    done
    
    print_success "应用安装流程结束。"
    read -p "按回车键返回主菜单..." -r
}

# -------------------- 自动安装 --------------------
auto_install() {
    print_title "自动安装模式 (全部使用默认配置)"
    reset_question_stack
    
    if check_lockfile; then
        print_warn "检测到锁文件，系统可能已安装过桌面环境。"
        confirm_action "是否继续安装（可能会覆盖部分配置）" "confirm_auto_install"
        local res=$?
        if [[ $res -eq 1 ]]; then
            BACK_TO_PREV=0
            print_info "已取消安装。"
            return
        elif [[ $res -eq 2 ]]; then
            print_info "已取消安装。"
            return
        fi
    fi
    
    confirm_action "确认执行自动安装（将安装 $AUTO_DESKTOP_TYPE + $AUTO_BROWSER_CHOICE + VNC + 中文环境 + noVNC）" "confirm_auto_install_final"
    local res=$?
    if [[ $res -eq 1 ]]; then
        BACK_TO_PREV=0
        print_info "已取消安装。"
        return
    elif [[ $res -eq 2 ]]; then
        print_info "已取消安装。"
        return
    fi
    
    # 使用默认参数
    DESKTOP_TYPE="$AUTO_DESKTOP_TYPE"
    BROWSER_CHOICE="$AUTO_BROWSER_CHOICE"
    INSTALL_COMMON_SOFT="$AUTO_INSTALL_COMMON_SOFT"
    INSTALL_VNC="$AUTO_INSTALL_VNC"
    VNC_PORT="$AUTO_VNC_PORT"
    VNC_GEOMETRY="$AUTO_VNC_GEOMETRY"
    VNC_DEPTH="$AUTO_VNC_DEPTH"
    VNC_ZLIB="$AUTO_VNC_ZLIB"
    VNC_LOCALHOST="$AUTO_VNC_LOCALHOST"
    VNC_PASSWORD="$AUTO_VNC_PASSWORD"
    VNC_START_NOW="$AUTO_VNC_START_NOW"
    INSTALL_LANG="$AUTO_INSTALL_LANG"
    INSTALL_NOVNC="$AUTO_INSTALL_NOVNC"
    
    # 设置目标用户
    setup_user_permissions
    
    install_base
    install_desktop
    [[ "$BROWSER_CHOICE" != "none" ]] && {
        case $BROWSER_CHOICE in
            firefox) install_browser_firefox ;;
            edge)    install_browser_edge ;;
            google)  install_browser_google ;;
        esac
    }
    [[ "$INSTALL_COMMON_SOFT" == "y" ]] && install_common_soft
    [[ "$INSTALL_VNC" == "y" ]] && install_vnc
    [[ "$INSTALL_LANG" == "y" ]] && install_language
    [[ "$INSTALL_NOVNC" == "y" ]] && install_novnc
    
    generate_lockfile
    show_install_summary
}

# -------------------- 高级安装（状态机架构，使用独立状态栈） --------------------
advanced_install() {
    print_title "高级安装模式"
    reset_question_stack
    declare -a STATE_STACK=()   # 新增状态栈

    # 检查锁文件
    if check_lockfile; then
        print_warn "检测到锁文件，系统可能已安装过桌面环境。"
        confirm_action "是否继续安装（可能会覆盖部分配置）" "confirm_adv_install"
        local res=$?
        if [[ $res -eq 1 ]]; then
            BACK_TO_PREV=0
            print_info "已取消安装。"
            return
        elif [[ $res -eq 2 ]]; then
            print_info "已取消安装。"
            return
        fi
    fi

    confirm_action "确认开始高级安装流程（将根据您的选择进行安装）" "confirm_adv_install_final"
    local res=$?
    if [[ $res -eq 1 ]]; then
        BACK_TO_PREV=0
        print_info "已取消安装。"
        return
    elif [[ $res -eq 2 ]]; then
        print_info "已取消安装。"
        return
    fi

    # 初始状态压栈
    local current_state="user_permissions"
    STATE_STACK+=("$current_state")

    while true; do
        # 检查是否需要回退（基于状态栈）
        if [[ $BACK_TO_PREV -eq 1 ]]; then
            BACK_TO_PREV=0
            if [[ ${#STATE_STACK[@]} -gt 1 ]]; then
                # 弹出当前状态（栈顶），然后取新的栈顶作为上一个状态
                unset 'STATE_STACK[-1]'
                current_state="${STATE_STACK[-1]}"
                # 可选：重置问题栈以避免干扰
                reset_question_stack
                continue
            else
                # 没有上一状态，返回主菜单
                print_info "已返回主菜单。"
                return
            fi
        fi

        case $current_state in
            "user_permissions")
                setup_user_permissions
                if [[ $? -eq 1 ]]; then
                    # 需要回退，但这是第一步，直接返回
                    return
                fi
                current_state="select_desktop"
                STATE_STACK+=("$current_state")
                ;;
                
            "select_desktop")
                echo "请选择要安装的桌面环境:"
                echo "  1) XFCE 完整版 (xfce4 + goodies)"
                echo "  2) Xubuntu 桌面 (xubuntu-desktop)"
                echo "  3) XFCE 精简版 (--no-install-recommends)"
                echo "  4) LXQt (通过 PPA 安装)"
                echo "  5) KDE Plasma 完整版 (kde-full)"
                echo "  6) KDE Plasma 标准版 (kde-standard)"
                echo "  7) KDE Plasma 最小版 (kde-plasma-desktop)"
                echo "  8) MATE 最小版 (mate-core)"
                echo "  9) MATE 完整版 (mate-full)"
                echo " 10) GNOME Ubuntu 定制版 (ubuntu-gnome-desktop)"
                echo " 11) GNOME 标准版 (ubuntu-desktop)"
                
                desktop_choice=$(ask_input "请输入数字 (1-11)" "select_desktop" "1")
                if [[ $? -eq 1 ]]; then
                    continue  # 触发回退
                fi
                desktop_choice=${desktop_choice:-1}
                
                case $desktop_choice in
                    1) DESKTOP_TYPE="xfce4" ;;
                    2) DESKTOP_TYPE="xubuntu" ;;
                    3) DESKTOP_TYPE="xfce-lite" ;;
                    4) DESKTOP_TYPE="lxqt" ;;
                    5) DESKTOP_TYPE="kde-full" ;;
                    6) DESKTOP_TYPE="kde-standard" ;;
                    7) DESKTOP_TYPE="kde-plasma" ;;
                    8) DESKTOP_TYPE="mate-core" ;;
                    9) DESKTOP_TYPE="mate-full" ;;
                    10) DESKTOP_TYPE="gnome-ubuntu" ;;
                    11) DESKTOP_TYPE="gnome-core" ;;
                    *) DESKTOP_TYPE="xfce4" ;;
                esac
                current_state="browser_choice"
                STATE_STACK+=("$current_state")
                ;;
                
            "browser_choice")
                ask_yes_no "是否安装浏览器" "install_browser"
                local res=$?
                if [[ $res -eq 1 ]]; then
                    continue
                elif [[ $res -eq 0 ]]; then
                    echo "请选择浏览器:"
                    echo "  1) Firefox"
                    echo "  2) Microsoft Edge (直接下载 deb)"
                    echo "  3) Google Chrome"
                    
                    browser_choice=$(ask_input "请输入数字 (1-3)" "select_browser" "1")
                    if [[ $? -eq 1 ]]; then
                        continue
                    fi
                    browser_choice=${browser_choice:-1}
                    
                    case $browser_choice in
                        1) BROWSER_CHOICE="firefox" ;;
                        2) BROWSER_CHOICE="edge" ;;
                        3) BROWSER_CHOICE="google" ;;
                        *) BROWSER_CHOICE="firefox" ;;
                    esac
                else
                    BROWSER_CHOICE="none"
                fi
                current_state="common_soft"
                STATE_STACK+=("$current_state")
                ;;
                
            "common_soft")
                ask_yes_no "是否安装常用软件 (gedit, mousepad, 磁盘管理, 系统监视器)" "install_common_soft"
                local res=$?
                if [[ $res -eq 1 ]]; then
                    continue
                elif [[ $res -eq 0 ]]; then
                    INSTALL_COMMON_SOFT="y"
                else
                    INSTALL_COMMON_SOFT="n"
                fi
                current_state="vnc_install"
                STATE_STACK+=("$current_state")
                ;;
                
            "vnc_install")
                ask_yes_no "是否安装并配置 TigerVNC" "install_vnc"
                local res=$?
                if [[ $res -eq 1 ]]; then
                    continue
                elif [[ $res -eq 0 ]]; then
                    INSTALL_VNC="y"
                    current_state="vnc_config"
                else
                    INSTALL_VNC="n"
                    current_state="language_install"
                fi
                STATE_STACK+=("$current_state")
                ;;
                
            "vnc_config")
                ask_yes_no "是否使用默认 VNC 配置 (端口5901, 1280x800, 16bit, 压缩9, -localhost no)" "vnc_default_config"
                local res=$?
                if [[ $res -eq 1 ]]; then
                    continue
                elif [[ $res -eq 0 ]]; then
                    VNC_PORT="5901"
                    VNC_GEOMETRY="1280x800"
                    VNC_DEPTH="16"
                    VNC_ZLIB="9"
                    VNC_LOCALHOST="no"
                    current_state="vnc_password"
                else
                    # 自定义配置
                    while true; do
                        # 端口
                        VNC_PORT=$(ask_input "请输入 VNC 端口 (5901-5910)" "vnc_port" "")
                        if [[ $? -eq 1 ]]; then
                            continue 2
                        fi
                        if [[ "$VNC_PORT" =~ ^59[0-1][0-9]$ ]] && [ "$VNC_PORT" -ge 5901 ] && [ "$VNC_PORT" -le 5910 ]; then
                            break
                        else
                            print_error "端口范围 5901~5910，请重新输入！"
                        fi
                    done
                    
                    VNC_GEOMETRY=$(ask_input "请输入分辨率 (例如 1920x1080)" "vnc_geometry" "1280x800")
                    if [[ $? -eq 1 ]]; then
                        continue
                    fi
                    VNC_GEOMETRY=${VNC_GEOMETRY:-1280x800}
                    
                    VNC_DEPTH=$(ask_input "请输入色彩深度 (16/24/32)" "vnc_depth" "16")
                    if [[ $? -eq 1 ]]; then
                        continue
                    fi
                    VNC_DEPTH=${VNC_DEPTH:-16}
                    
                    VNC_ZLIB=$(ask_input "请输入压缩级别 (0-9)" "vnc_zlib" "9")
                    if [[ $? -eq 1 ]]; then
                        continue
                    fi
                    VNC_ZLIB=${VNC_ZLIB:-9}
                    
                    VNC_LOCALHOST=$(ask_input "是否仅本地访问 (-localhost yes/no)" "vnc_localhost" "no")
                    if [[ $? -eq 1 ]]; then
                        continue
                    fi
                    VNC_LOCALHOST=${VNC_LOCALHOST:-no}
                    
                    current_state="vnc_password"
                fi
                STATE_STACK+=("$current_state")
                ;;
                
            "vnc_password")
                while true; do
                    read -s -p "请输入 VNC 密码 (留空则使用默认密码 123456): " vnc_pass_input
                    echo
                    # 这里无法直接通过 ask_input 返回 r，所以手动检查输入是否为 r
                    if [[ "$vnc_pass_input" =~ ^[Rr]$ ]]; then
                        BACK_TO_PREV=1
                        continue 2   # 跳出两层循环，回到主循环顶部
                    fi
                    if [[ -z "$vnc_pass_input" ]]; then
                        VNC_PASSWORD="123456"
                    else
                        VNC_PASSWORD="$vnc_pass_input"
                    fi
                    break
                done
                current_state="vnc_start"
                STATE_STACK+=("$current_state")
                ;;
                
            "vnc_start")
                ask_yes_no "是否立即启动 VNC 服务" "vnc_start_now"
                local res=$?
                if [[ $res -eq 1 ]]; then
                    continue
                elif [[ $res -eq 0 ]]; then
                    VNC_START_NOW="y"
                else
                    VNC_START_NOW="n"
                fi
                current_state="language_install"
                STATE_STACK+=("$current_state")
                ;;
                
            "language_install")
                ask_yes_no "是否安装中文语言包及字体" "install_lang"
                local res=$?
                if [[ $res -eq 1 ]]; then
                    continue
                elif [[ $res -eq 0 ]]; then
                    INSTALL_LANG="y"
                else
                    INSTALL_LANG="n"
                fi
                current_state="novnc_install"
                STATE_STACK+=("$current_state")
                ;;
                
            "novnc_install")
                if [[ "$INSTALL_VNC" == "y" ]]; then
                    ask_yes_no "是否安装 noVNC (Web VNC 客户端)" "install_novnc"
                    local res=$?
                    if [[ $res -eq 1 ]]; then
                        continue
                    elif [[ $res -eq 0 ]]; then
                        INSTALL_NOVNC="y"
                    else
                        INSTALL_NOVNC="n"
                    fi
                else
                    INSTALL_NOVNC="n"
                fi
                current_state="execute_install"
                STATE_STACK+=("$current_state")
                ;;
                
            "execute_install")
                # 执行安装
                install_base
                install_desktop
                [[ "$BROWSER_CHOICE" != "none" ]] && {
                    case $BROWSER_CHOICE in
                        firefox) install_browser_firefox ;;
                        edge)    install_browser_edge ;;
                        google)  install_browser_google ;;
                    esac
                }
                [[ "$INSTALL_COMMON_SOFT" == "y" ]] && install_common_soft
                [[ "$INSTALL_VNC" == "y" ]] && install_vnc
                [[ "$INSTALL_LANG" == "y" ]] && install_language
                [[ "$INSTALL_NOVNC" == "y" ]] && install_novnc
                
                generate_lockfile
                show_install_summary
                return
                ;;
                
            *)
                print_error "未知状态: $current_state"
                return
                ;;
        esac
    done
}
# -------------------- 显示安装总结 --------------------
show_install_summary() {
    print_title "安装完成信息汇总"
    echo -e "${GREEN}[成功] 安装完成！${NC}"
    echo -e "${CYAN}[信息] 桌面环境:${NC} $DESKTOP_TYPE (启动命令: $DESKTOP_CMD)"
    
    if [[ "$INSTALL_VNC" == "y" ]]; then
        local public_ip=$(get_public_ip)
        echo -e "${CYAN}[信息] VNC 地址:${NC} $public_ip:$VNC_PORT"
        echo -e "${CYAN}[信息] VNC 端口:${NC} $VNC_PORT"
        echo -e "${CYAN}[信息] VNC 密码:${NC} ${VNC_PASSWORD:-123456}"
    fi
    
    if [[ "$INSTALL_NOVNC" == "y" ]]; then
        local public_ip=$(get_public_ip)
        echo -e "${CYAN}[信息] noVNC:${NC} 已安装 (请通过浏览器访问 http://$public_ip:6080/vnc.html)"
    fi
    
    if [[ "$BROWSER_CHOICE" != "none" ]]; then
        echo -e "${CYAN}[信息] 浏览器:${NC} $BROWSER_CHOICE"
    fi
    
    echo
    ask_yes_no "是否立即重启操作系统 (注意: 重启将断开当前连接)" "reboot_system"
    local res=$?
    if [[ $res -eq 1 ]]; then
        BACK_TO_PREV=0
        print_info "已取消重启。"
    elif [[ $res -eq 0 ]]; then
        print_warn "系统将在 10 秒后重启..."
        sleep 10
        run_cmd "reboot"
    else
        print_info "请稍后手动重启系统以完成配置。"
    fi
}

# -------------------- 卸载管理 --------------------
uninstall_management() {
    print_title "卸载管理"
    reset_question_stack
    
    if check_lockfile; then
        read_lockfile
        print_info "检测到本脚本的安装记录，信息如下:"
        echo "----------------------------------------"
        cat "$LOCKFILE" | sed 's/[{}",]//g' | sed 's/^[[:space:]]*//' | sed '/^$/d'
        echo "----------------------------------------"
    else
        print_warn "未找到本脚本的安装记录锁文件 (~/vncinstall.lock)"
        print_info "可能不是通过本脚本安装的，但您可以继续选择卸载组件。"
    fi
    
    echo
    echo -e "${WHITE}请选择要卸载的组件类型:${NC}"
    echo "  1) 卸载桌面环境"
    echo "  2) 卸载 VNC Server"
    echo "  3) 卸载 noVNC"
    echo "  4) 卸载浏览器"
    echo "  5) 卸载应用程序（输入法/VS Code/播放器等）"
    echo "  6) 完整卸载（全部组件 + 删除锁文件）"
    echo "  0) 返回主菜单"
    echo
    
    uninstall_type=$(ask_input "请输入数字 [0-6]" "select_uninstall_type" "")
    local res=$?
    if [[ $res -eq 1 ]]; then
        BACK_TO_PREV=0
        return
    fi
    
    case $uninstall_type in
        1)
            print_warn "即将卸载桌面环境"
            confirm_action "确认继续" "confirm_uninstall_desktop"
            local res=$?
            if [[ $res -eq 1 ]]; then
                BACK_TO_PREV=0
                print_info "已取消"
                return
            elif [[ $res -eq 2 ]]; then
                print_info "已取消"
                return
            fi
            
            case "$DESKTOP_TYPE" in
                xfce4|xfce-lite|xubuntu)
                    run_cmd "apt remove -y xfce4 xfce4-goodies xfce4-terminal"
                    run_cmd "apt remove -y xubuntu-desktop"
                    ;;
                lxqt)
                    run_cmd "apt remove -y lxqt"
                    run_cmd "add-apt-repository --remove ppa:lxqt/stable -y"
                    ;;
                kde*)
                    run_cmd "apt remove -y kde-full kde-standard kde-plasma-desktop"
                    ;;
                mate*)
                    run_cmd "apt remove -y mate-desktop-environment-core mate-desktop-environment-extras"
                    ;;
                gnome*)
                    run_cmd "apt remove -y ubuntu-gnome-desktop ubuntu-desktop"
                    ;;
                *)
                    print_warn "未识别具体桌面类型，尝试通用卸载"
                    run_cmd "apt remove -y xfce4 xubuntu-desktop kde-plasma-desktop mate-desktop lxqt gnome-session"
                    ;;
            esac
            run_cmd "apt-get remove -y dbus-x11"
            run_cmd "apt autoremove -y"
            print_success "桌面环境卸载完成"
            ;;
            
        2)
            print_warn "即将卸载 TigerVNC"
            confirm_action "确认继续" "confirm_uninstall_vnc"
            local res=$?
            if [[ $res -eq 1 ]]; then
                BACK_TO_PREV=0
                print_info "已取消"
                return
            elif [[ $res -eq 2 ]]; then
                print_info "已取消"
                return
            fi
            
            run_cmd "apt remove -y tigervnc-standalone-server tigervnc-xorg-extension"
            run_cmd "rm -rf $TARGET_HOME/.vnc 2>/dev/null"
            run_cmd "rm -f /etc/systemd/system/vncserver@*.service"
            run_cmd "systemctl daemon-reload"
            run_cmd "apt autoremove -y"
            print_success "VNC 卸载完成"
            ;;
            
        3)
            print_warn "即将卸载 noVNC"
            confirm_action "确认继续" "confirm_uninstall_novnc"
            local res=$?
            if [[ $res -eq 1 ]]; then
                BACK_TO_PREV=0
                print_info "已取消"
                return
            elif [[ $res -eq 2 ]]; then
                print_info "已取消"
                return
            fi
            
            local uninstall_cmd="bash <(curl -L http://sh.802213.xyz/novnc/uninstall_auto.sh)"
            run_cmd "$uninstall_cmd" || print_warn "noVNC 卸载脚本执行失败，请手动处理。"
            print_success "noVNC 卸载完成"
            ;;
            
        4)
            print_warn "即将卸载浏览器"
            confirm_action "确认继续" "confirm_uninstall_browser"
            local res=$?
            if [[ $res -eq 1 ]]; then
                BACK_TO_PREV=0
                print_info "已取消"
                return
            elif [[ $res -eq 2 ]]; then
                print_info "已取消"
                return
            fi
            
            echo "请选择要卸载的浏览器（可多选，输入序号用空格分隔）:"
            echo "  1) Firefox"
            echo "  2) Microsoft Edge"
            echo "  3) Google Chrome"
            
            browser_uninstall=$(ask_input "请输入序号" "select_uninstall_browser" "")
            local res=$?
            if [[ $res -eq 1 ]]; then
                BACK_TO_PREV=0
                return
            fi
            
            for choice in $browser_uninstall; do
                case $choice in
                    1)
                        run_cmd "apt remove -y firefox"
                        run_cmd "rm -f /etc/apt/sources.list.d/mozilla.sources"
                        run_cmd "rm -f /etc/apt/keyrings/packages.mozilla.org.asc"
                        run_cmd "rm -f /etc/apt/preferences.d/mozilla"
                        ;;
                    2)
                        run_cmd "apt remove -y microsoft-edge-stable"
                        run_cmd "rm -f /etc/apt/sources.list.d/microsoft-edge.list"
                        run_cmd "rm -f /etc/apt/trusted.gpg.d/microsoft.gpg"
                        ;;
                    3)
                        run_cmd "apt remove -y google-chrome-stable"
                        ;;
                esac
            done
            run_cmd "apt autoremove -y"
            print_success "浏览器卸载完成"
            ;;
            
        5)
            print_warn "即将卸载应用程序"
            confirm_action "确认继续" "confirm_uninstall_apps"
            local res=$?
            if [[ $res -eq 1 ]]; then
                BACK_TO_PREV=0
                print_info "已取消"
                return
            elif [[ $res -eq 2 ]]; then
                print_info "已取消"
                return
            fi
            
            echo "请选择要卸载的应用（可多选，输入序号用空格分隔）:"
            echo "  1) Fcitx5 输入法"
            echo "  2) Visual Studio Code"
            echo "  3) VLC 播放器"
            echo "  4) MPV 播放器"
            echo "  5) LibreOffice"
            echo "  6) Flameshot 截图"
            echo "  7) 压缩工具 (7zip/unrar)"
            echo "  8) 系统工具 (neofetch/htop/tmux)"
            echo "  9) QQ"
            echo " 10) 微信"
            echo " 11) FinalShell"
            echo " 12) Cursor"
            echo " 13) RealVNC Viewer"
            echo " 14) IBus 输入法"
            
            app_uninstall=$(ask_input "请输入序号" "select_uninstall_apps" "")
            local res=$?
            if [[ $res -eq 1 ]]; then
                BACK_TO_PREV=0
                return
            fi
            
            for choice in $app_uninstall; do
                case $choice in
                    1) run_cmd "apt remove -y fcitx5 fcitx5-chinese-addons fcitx5-frontend-* fcitx5-config-qt" ;;
                    2) run_cmd "apt remove -y code" ;;
                    3) run_cmd "apt remove -y vlc" ;;
                    4) run_cmd "apt remove -y mpv" ;;
                    5) run_cmd "apt remove -y libreoffice*" ;;
                    6) run_cmd "apt remove -y flameshot" ;;
                    7) run_cmd "apt remove -y p7zip-full unrar" ;;
                    8) run_cmd "apt remove -y neofetch htop tmux" ;;
                    9) run_cmd "dpkg -r qq 2>/dev/null || true" ;;
                    10) run_cmd "dpkg -r wechat 2>/dev/null || true" ;;
                    11) run_cmd "dpkg -r finalshell 2>/dev/null || true" ;;
                    12) run_cmd "apt remove -y cursor 2>/dev/null || true" ;;
                    13) run_cmd "dpkg -r realvnc-vnc-viewer 2>/dev/null || true" ;;
                    14) run_cmd "apt remove -y ibus* 2>/dev/null || true" ;;
                esac
            done
            run_cmd "apt autoremove -y"
            print_success "应用程序卸载完成"
            ;;
            
        6)
            print_warn "⚠️  完整卸载警告 ⚠️"
            echo "此操作将卸载所有相关组件："
            echo "  - 所有桌面环境"
            echo "  - VNC Server + noVNC"
            echo "  - 所有浏览器"
            echo "  - 所有应用程序"
            echo "  - 删除安装锁文件"
            echo
            confirm_action "【风险操作】确认执行完整卸载" "confirm_full_uninstall"
            local res=$?
            if [[ $res -eq 1 ]]; then
                BACK_TO_PREV=0
                print_info "已取消完整卸载"
                return
            elif [[ $res -eq 2 ]]; then
                print_info "已取消完整卸载"
                return
            fi
            
            # 卸载桌面环境
            run_cmd "apt remove -y xfce4 xubuntu-desktop lxqt kde-full kde-standard kde-plasma-desktop mate-desktop-environment-core mate-desktop-environment-extras ubuntu-gnome-desktop ubuntu-desktop"
            # 卸载VNC
            run_cmd "apt remove -y tigervnc-standalone-server tigervnc-xorg-extension"
            run_cmd "rm -rf $TARGET_HOME/.vnc 2>/dev/null"
            run_cmd "rm -f /etc/systemd/system/vncserver@*.service"
            run_cmd "systemctl daemon-reload"
            # 卸载noVNC
            run_cmd "bash <(curl -L http://sh.802213.xyz/novnc/uninstall_auto.sh) 2>/dev/null || true"
            # 卸载浏览器
            run_cmd "apt remove -y firefox microsoft-edge-stable google-chrome-stable"
            # 卸载应用
            run_cmd "apt remove -y fcitx5* code vlc mpv libreoffice* flameshot p7zip-full unrar neofetch htop tmux ibus*"
            run_cmd "dpkg -r qq wechat finalshell realvnc-vnc-viewer 2>/dev/null || true"
            run_cmd "apt remove -y cursor 2>/dev/null || true"
            # 清理依赖
            run_cmd "apt autoremove -y"
            run_cmd "apt autoclean"
            # 删除锁文件
            run_cmd "rm -f $LOCKFILE"
            
            print_success "完整卸载完成！"
            ;;
            
        0) return ;;
        *)
            print_error "无效选项！"
            sleep 2
            ;;
    esac
    
    print_info "卸载操作执行完毕，建议重启系统以清理残留配置。"
    read -p "按回车键返回主菜单..." -r
}

# -------------------- 服务管理 --------------------
service_management() {
    print_title "服务管理"
    reset_question_stack
    
    if ! check_lockfile; then
        print_error "未找到安装记录，无法管理服务！"
        sleep 2
        return
    fi
    
    read_lockfile
    local display_num=$(port_to_display $VNC_PORT)
    local service_name="vncserver@$display_num.service"
    
    echo -e "${WHITE}当前 VNC 服务状态:${NC}"
    run_cmd "systemctl status $service_name --no-pager" 2>/dev/null || print_warn "服务未找到或未运行"
    echo
    
    echo -e "${WHITE}请选择操作:${NC}"
    echo "  1) 启动 VNC 服务"
    echo "  2) 停止 VNC 服务"
    echo "  3) 重启 VNC 服务"
    echo "  4) 设置 VNC 服务开机自启"
    echo "  5) 取消 VNC 服务开机自启"
    echo "  6) 修改 VNC 密码"
    echo "  7) 查看 VNC 连接信息"
    echo "  0) 返回主菜单"
    echo
    
    service_action=$(ask_input "请输入数字 [0-7]" "select_service_action" "")
    local res=$?
    if [[ $res -eq 1 ]]; then
        BACK_TO_PREV=0
        return
    fi
    
    case $service_action in
        1)
            run_cmd "systemctl start $service_name"
            if [[ $? -eq 0 ]]; then
                print_success "VNC 服务启动成功！"
            else
                print_error "VNC 服务启动失败！"
            fi
            ;;
        2)
            run_cmd "systemctl stop $service_name"
            if [[ $? -eq 0 ]]; then
                print_success "VNC 服务停止成功！"
            else
                print_error "VNC 服务停止失败！"
            fi
            ;;
        3)
            run_cmd "systemctl restart $service_name"
            if [[ $? -eq 0 ]]; then
                print_success "VNC 服务重启成功！"
            else
                print_error "VNC 服务重启失败！"
            fi
            ;;
        4)
            run_cmd "systemctl enable $service_name"
            if [[ $? -eq 0 ]]; then
                print_success "VNC 服务已设置开机自启！"
            else
                print_error "设置开机自启失败！"
            fi
            ;;
        5)
            run_cmd "systemctl disable $service_name"
            if [[ $? -eq 0 ]]; then
                print_success "VNC 服务已取消开机自启！"
            else
                print_error "取消开机自启失败！"
            fi
            ;;
        6)
            print_info "修改 VNC 密码（当前用户: $TARGET_USER）"
            while true; do
                read -s -p "请输入新的 VNC 密码: " new_vnc_pass
                echo
                read -s -p "请再次输入新的 VNC 密码: " new_vnc_pass_confirm
                echo
                if [[ "$new_vnc_pass" != "$new_vnc_pass_confirm" ]]; then
                    print_error "两次密码不一致，请重新输入！"
                    continue
                fi
                if [[ -z "$new_vnc_pass" ]]; then
                    print_error "密码不能为空！"
                    continue
                fi
                # 更新密码
                if is_root || [[ "$TARGET_USER" == "root" ]]; then
                    printf "%s\n%s\nn\n" "$new_vnc_pass" "$new_vnc_pass" | vncpasswd >/dev/null 2>&1
                else
                    sudo -u "$TARGET_USER" bash -c "printf '%s\n%s\nn\n' \"$new_vnc_pass\" \"$new_vnc_pass\" | vncpasswd >/dev/null 2>&1"
                fi
                VNC_PASSWORD="$new_vnc_pass"
                generate_lockfile  # 更新锁文件
                print_success "VNC 密码修改成功！"
                break
            done
            ;;
        7)
            local public_ip=$(get_public_ip)
            print_title "VNC 连接信息"
            echo -e "${CYAN}公网 IP:${NC} $public_ip"
            echo -e "${CYAN}VNC 端口:${NC} $VNC_PORT"
            echo -e "${CYAN}VNC 显示号:${NC} :$display_num"
            echo -e "${CYAN}VNC 连接地址:${NC} $public_ip:$VNC_PORT"
            if [[ "$INSTALL_NOVNC" == "y" ]]; then
                echo -e "${CYAN}noVNC 访问地址:${NC} http://$public_ip:6080/vnc.html"
            fi
            echo -e "${CYAN}当前 VNC 用户:${NC} $TARGET_USER"
            echo -e "${YELLOW}注意: VNC 密码为您设置的密码（默认 123456）${NC}"
            ;;
        0) return ;;
        *) print_error "无效选项！" ;;
    esac
    
    read -p "按回车键返回主菜单..." -r
}

# -------------------- 主菜单 --------------------
main_menu() {
    clear_screen
    while true; do
        echo -e "\n${WHITE}======= 主菜单 =======${NC}"
        echo "  1) 自动安装 (全部默认配置)"
        echo "  2) 高级安装 (自定义配置)"
        echo "  3) 独立应用安装 (QQ/微信/浏览器等)"
        echo "  4) 一键安装全部应用"
        echo "  5) 一键卸载全部应用"
        echo "  6) 卸载管理 (桌面/VNC/应用等)"
        echo "  7) 服务管理 (VNC 启停/密码/自启)"
        echo "  8) 查看系统信息"
        echo "  0) 退出脚本"
        echo -e "${WHITE}=====================${NC}"
        
        main_choice=$(ask_input "请输入选项 [0-8]" "main_menu_choice" "")
        local res=$?
        if [[ $res -eq 1 ]]; then
            BACK_TO_PREV=0
            continue
        fi
        
        case $main_choice in
            1) auto_install ;;
            2) advanced_install ;;
            3) install_apps_menu ;;
            4) install_all_apps ;;
            5) uninstall_all_apps ;;
            6) uninstall_management ;;
            7) service_management ;;
            8)
                print_title "系统信息"
                run_cmd "neofetch 2>/dev/null || cat /etc/os-release | grep -E 'NAME|VERSION' | head -n 2"
                run_cmd "echo -e '\nCPU: ' && lscpu | grep 'Model name' | cut -d: -f2 | sed 's/^ //'"
                run_cmd "echo -e '内存: ' && free -h | grep Mem | awk '{print \$2, \"(已用:\", \$3, \")\"}'"
                run_cmd "echo -e '磁盘: ' && df -h / | grep / | awk '{print \$2, \"(已用:\", \$3, \"\", \$5, \")\"}'"
                run_cmd "echo -e '\n公网 IP: ' && get_public_ip"
                run_cmd "echo -e '端口监听: ' && netstat -tulpn | grep -E '(590|6080)' 2>/dev/null || echo '无 VNC/noVNC 端口监听'"
                read -p "按回车键返回主菜单..." -r
                ;;
            0)
                print_info "感谢使用，脚本退出！"
                exit 0
                ;;
            *)
                print_error "无效选项，请输入 0-8 之间的数字！"
                sleep 2
                ;;
        esac
    done
}

# -------------------- 脚本入口 --------------------
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    if ! is_root && ! has_sudo; then
        print_error "当前用户无 sudo 权限，无法执行安装操作！"
        exit 1
    fi
    main_menu
fi