#!/bin/bash

# 核心配置（状态存储+XML路径）
HOTPLUG_STATUS_FILE="/tmp/vmtool_hotplug_status"
HOTPLUG_STATUS=0
# USB静态直通状态文件
USB_DIRECT_STATUS_FILE="/tmp/vmtool_usb_direct_status"
USB_DIRECT_STATUS=0

# 虚拟机名称
VM_NAME="Windows_11"
# 网桥创建脚本路径
BRIDGE_CREATE_SCRIPT="/usr/local/bin/creat_br0.sh"
# 虚拟机环境配置&定义脚本路径
VM_CREATE_SCRIPT="/usr/local/bin/vm_create"
# 虚拟机销毁脚本路径
VM_DESTROY_SCRIPT="/usr/local/bin/vm_destroy"

# power-sync服务配置
POWER_SYNC_SERVICE_SOURCE="/etc/vmdeploy/power-sync.service"  # 服务文件源路径
POWER_SYNC_SERVICE_TARGET_DIR="/etc/systemd/system"   # 服务文件目标文件夹
POWER_SYNC_SERVICE_NAME="power-sync.service"          # 服务文件名
POWER_SYNC_PYTHON_SCRIPT="/usr/local/bin/power-sync"  # 脚本路径

# auto-start服务配置
AUTO_START_SERVICE_SOURCE="/etc/vmdeploy/auto-start.service"  # auto-start服务文件源路径
AUTO_START_SERVICE_TARGET_DIR="/etc/systemd/system"   # 服务文件目标文件夹
AUTO_START_SERVICE_NAME="auto-start.service"          # auto-start服务文件名

# USB热插拔规则文件路径
USB_HOTLOG_RULES_SOURCE="/etc/vmdeploy/70-usb-hotlog.rules"  # home路径下的源文件
USB_HOTLOG_RULES_TARGET="/etc/udev/rules.d/70-usb-hotlog.rules"  # 目标路径

# XML路径配置
VM_XML_SOURCE_PATH="/etc/vmdeploy/Windows_11.xml"  # 虚拟机主XML文件
NET_DIRECT_SCRIPT="/usr/local/bin/net_direct"  # 网卡直通脚本路径
NET_DIRECT_WORK_DIR="/tmp/netcard"  # net_direct脚本工作目录
GPU_DIRECT_SCRIPT="/usr/local/bin/gpu_direct"  # 显卡直通脚本路径
GPU_DIRECT_WORK_DIR="/tmp/gpucard"  # gpu_direct脚本工作目录
USB_DIRECT_SCRIPT="/usr/local/bin/usb_direct"  # U盘直通脚本路径
SERIAL_DIRECT_SCRIPT="/usr/local/bin/serial_direct"  # 串口直通脚本路径
IGPU_DIRECT_SCRIPT="/usr/local/bin/igpu_direct"  # 核心显卡直通脚本路径

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# 初始化热插拔状态
init_hotplug_status() {
    if [ ! -f "$HOTPLUG_STATUS_FILE" ]; then
        echo "0" > "$HOTPLUG_STATUS_FILE"
        HOTPLUG_STATUS=0
        return
    fi
    local status=$(cat "$HOTPLUG_STATUS_FILE" | tr -d ' \n')
    if [[ $status =~ ^[01]$ ]]; then
        HOTPLUG_STATUS=$status
    else
        echo "0" > "$HOTPLUG_STATUS_FILE"
        HOTPLUG_STATUS=0
    fi
}

# 初始化USB静态直通状态
init_usb_direct_status() {
    if [ ! -f "$USB_DIRECT_STATUS_FILE" ]; then
        echo "0" > "$USB_DIRECT_STATUS_FILE"
        USB_DIRECT_STATUS=0
        return
    fi
    local status=$(cat "$USB_DIRECT_STATUS_FILE" | tr -d ' \n')
    if [[ $status =~ ^[01]$ ]]; then
        USB_DIRECT_STATUS=$status
    else
        echo "0" > "$USB_DIRECT_STATUS_FILE"
        USB_DIRECT_STATUS=0
    fi
}

# 更新热插拔状态（参数：0=关闭，1=开启）
update_hotplug_status() {
    local new_status=$1
    if [[ ! $new_status =~ ^[01]$ ]]; then
        echo -e "${RED}Error: Status value can only be 0 or 1${NC}"
        return 1
    fi
    HOTPLUG_STATUS=$new_status
    echo "$new_status" > "$HOTPLUG_STATUS_FILE"
    return 0
}

# 更新USB静态直通状态（参数：0=未配置，1=已配置）
update_usb_direct_status() {
    local new_status=$1
    if [[ ! $new_status =~ ^[01]$ ]]; then
        echo -e "${RED}Error: Status value can only be 0 or 1${NC}"
        return 1
    fi
    USB_DIRECT_STATUS=$new_status
    echo "$new_status" > "$USB_DIRECT_STATUS_FILE"
    return 0
}

# 清空热插拔状态记录
clear_hotplug_status() {
    if [ -f "$HOTPLUG_STATUS_FILE" ]; then
        rm -f "$HOTPLUG_STATUS_FILE"
        echo -e "${GREEN}Deleted hotplug status file: $HOTPLUG_STATUS_FILE${NC}"
    fi
    # 删除USB静态直通状态文件
    if [ -f "$USB_DIRECT_STATUS_FILE" ]; then
        rm -f "$USB_DIRECT_STATUS_FILE"
        echo -e "${GREEN}Deleted USB static passthrough status file: $USB_DIRECT_STATUS_FILE${NC}"
    fi
    unset VMTOOL_HOTPLUG_STATUS
    echo -e "${GREEN}Cleared hotplug-related environment variables${NC}"
}

# 获取热插拔状态描述
get_hotplug_status_desc() {
    if [ $HOTPLUG_STATUS -eq 1 ]; then
        echo -e "${GREEN}Enabled${NC}"
    else
        echo -e "${RED}Disabled${NC}"
    fi
}

# 辅助函数：检查net_direct脚本是否存在且可执行
check_net_direct() {
    if [ ! -f "$NET_DIRECT_SCRIPT" ]; then
        echo -e "${RED}Error: Network card passthrough script $NET_DIRECT_SCRIPT does not exist!${NC}"
        return 1
    fi
    if [ ! -x "$NET_DIRECT_SCRIPT" ]; then
        echo -e "${YELLOW}Warning: Network card passthrough script has no execute permission, adding now...${NC}"
        chmod +x "$NET_DIRECT_SCRIPT" || {
            echo -e "${RED}Error: Failed to add execute permission to the script!${NC}"
            return 1
        }
    fi
    return 0
}

# 检查gpu_direct脚本是否存在且可执行（仿照net_direct逻辑）
check_gpu_direct() {
    if [ ! -f "$GPU_DIRECT_SCRIPT" ]; then
        echo -e "${RED}Error: GPU passthrough script $GPU_DIRECT_SCRIPT does not exist!${NC}"
        return 1
    fi
    if [ ! -x "$GPU_DIRECT_SCRIPT" ]; then
        echo -e "${YELLOW}Warning: GPU passthrough script has no execute permission, adding now...${NC}"
        chmod +x "$GPU_DIRECT_SCRIPT" || {
            echo -e "${RED}Error: Failed to add execute permission to the script!${NC}"
            return 1
        }
    fi
    return 0
}

# 检查usb_direct脚本是否存在且可执行
check_usb_direct() {
    if [ ! -f "$USB_DIRECT_SCRIPT" ]; then
        echo -e "${RED}Error: USB disk passthrough script $USB_DIRECT_SCRIPT does not exist!${NC}"
        return 1
    fi
    if [ ! -x "$USB_DIRECT_SCRIPT" ]; then
        echo -e "${YELLOW}Warning: USB disk passthrough script has no execute permission, adding now...${NC}"
        chmod +x "$USB_DIRECT_SCRIPT" || {
            echo -e "${RED}Error: Failed to add execute permission to the script!${NC}"
            return 1
        }
    fi
    return 0
}

# 检查serial_direct脚本是否存在且可执行
check_serial_direct() {
    if [ ! -f "$SERIAL_DIRECT_SCRIPT" ]; then
        echo -e "${RED}Error: Serial passthrough script $SERIAL_DIRECT_SCRIPT does not exist!${NC}"
        return 1
    fi
    if [ ! -x "$SERIAL_DIRECT_SCRIPT" ]; then
        echo -e "${YELLOW}Warning: Serial passthrough script has no execute permission, adding now...${NC}"
        chmod +x "$SERIAL_DIRECT_SCRIPT" || {
            echo -e "${RED}Error: Failed to add execute permission to the script!${NC}"
            return 1
        }
    fi
    return 0
}

# 检查ai_direct脚本是否存在且可执行（仿照net/usb直通的检查逻辑）
check_ai_direct() {
    local AI_DIRECT_SCRIPT="/usr/local/bin/ai_direct"
    if [ ! -f "$AI_DIRECT_SCRIPT" ]; then
        echo -e "${RED}Error: AI inference card passthrough script $AI_DIRECT_SCRIPT does not exist!${NC}"
        return 1
    fi
    if [ ! -x "$AI_DIRECT_SCRIPT" ]; then
        echo -e "${YELLOW}Warning: AI inference card passthrough script has no execute permission, adding now...${NC}"
        chmod +x "$AI_DIRECT_SCRIPT" || {
            echo -e "${RED}Error: Failed to add execute permission to the script!${NC}"
            return 1
        }
    fi
    return 0
}

# 校验BDF格式（xx:xx.x）
validate_bdf() {
    local bdf=$1
    if ! echo "$bdf" | grep -qE '^[0-9a-fA-F]{2}:[0-9a-fA-F]{2}\.[0-9]$'; then
        echo -e "${RED}Error: Invalid BDF format ($bdf), correct format is xx:xx.x (e.g. 03:00.0)${NC}"
        return 1
    fi
    # 校验BDF是否存在于系统中
    if ! lspci -s "$bdf" >/dev/null 2>&1; then
        echo -e "${RED}Error: BDF $bdf does not exist in the system!${NC}"
        return 1
    fi
    return 0
}

# 校验USB参数格式（十六进制xxx:xxx，支持0-9/a-f/A-F）
validate_usb_params() {
    local params=("$@")
    for param in "${params[@]}"; do
        # 核心修改：正则兼容十六进制字符（0-9/a-f/A-F），格式为 十六进制串:十六进制串
        if ! echo "$param" | grep -qE '^[0-9a-fA-F]+:[0-9a-fA-F]+$'; then
            echo -e "${RED}Error: Invalid USB parameter format ($param), correct format is hexadecimal:hexadecimal (e.g. 0951:1666, 12c9:1017)${NC}"
            return 1
        fi
    done
    return 0
}

# 验串口参数格式（设备路径+COM口）
validate_serial_params() {
    local serial_dev=$1
    local com_port=$2

    # 校验COM口格式
    if ! echo "$com_port" | grep -qE '^COM[123]$'; then
        echo -e "${RED}Error: Invalid COM port ($com_port), only COM1/2/3 are supported!${NC}"
        return 1
    fi

    # 校验设备路径是否为字符设备
    if [ ! -c "$serial_dev" ]; then
        echo -e "${RED}Error: Serial device $serial_dev is not a valid character device!${NC}"
        return 1
    fi

    return 0
}

# 网卡专用XML插入函数
insert_passthrough_xml() {
    local bdf=$1
    local passthrough_xml_path="$NET_DIRECT_WORK_DIR/i210_all_passthrough.xml"
    
    # 检查生成的直通XML是否存在且非空
    if [ ! -s "$passthrough_xml_path" ]; then
        echo -e "${RED}Error: Valid passthrough XML file not found ($passthrough_xml_path)${NC}"
        return 1
    fi

    # 检查虚拟机主XML是否存在
    if [ ! -f "$VM_XML_SOURCE_PATH" ]; then
        echo -e "${RED}Error: VM main XML file $VM_XML_SOURCE_PATH does not exist!${NC}"
        return 1
    fi

    # 先备份原XML文件
    local backup_xml="${VM_XML_SOURCE_PATH}.bak_$(date +%Y%m%d_%H%M%S)"
    cp "$VM_XML_SOURCE_PATH" "$backup_xml"
    echo -e "${YELLOW}Backed up original VM XML to: $backup_xml${NC}"

    # 将直通XML内容插入到<memballoon model='virtio'>标签上方
    grep -v '^<!--' "$passthrough_xml_path" | grep -v '^$' > /tmp/tmp_passthrough.xml
    sed -i "/<memballoon model='virtio'>/e cat /tmp/tmp_passthrough.xml" "$VM_XML_SOURCE_PATH"

    # 清理临时文件
    rm -f /tmp/tmp_passthrough.xml
    
    return 0
}

# 显卡专用XML插入函数
insert_gpu_passthrough_xml() {
    local gpu_bdf=$1
    local gpu_passthrough_xml_path="$GPU_DIRECT_WORK_DIR/gpu_all_passthrough.xml"
    
    # 检查生成的显卡直通XML是否存在且非空
    if [ ! -s "$gpu_passthrough_xml_path" ]; then
        echo -e "${RED}错误：未找到有效的显卡直通XML文件（$gpu_passthrough_xml_path）${NC}"
        return 1
    fi

    # 检查虚拟机主XML是否存在
    if [ ! -f "$VM_XML_SOURCE_PATH" ]; then
        echo -e "${RED}错误：虚拟机主XML文件 $VM_XML_SOURCE_PATH 不存在！${NC}"
        return 1
    fi

    # 先备份原XML文件
    local backup_xml="${VM_XML_SOURCE_PATH}.bak_$(date +%Y%m%d_%H%M%S)"
    cp "$VM_XML_SOURCE_PATH" "$backup_xml"
    echo -e "${YELLOW}已备份原虚拟机XML到：$backup_xml${NC}"

    # 将显卡直通XML内容插入到<memballoon model='virtio'>标签上方
    grep -v '^<!--' "$gpu_passthrough_xml_path" | grep -v '^$' > /tmp/tmp_gpu_passthrough.xml
    sed -i "/<memballoon model='virtio'>/e cat /tmp/tmp_gpu_passthrough.xml" "$VM_XML_SOURCE_PATH"

    # 清理临时文件
    rm -f /tmp/tmp_gpu_passthrough.xml
    
    return 0
}

# 帮助信息
show_help() {
    echo -e "${YELLOW}Usage: vmdeploy <command> [options]${NC}"
    echo "VM management tool (parameter + menu interactive version), supports the following commands:"
    echo "  direct         Configure device passthrough (parameterized call)"
    echo "                 Sub-parameters: -n <BDF>     Passthrough I210 network card (BDF format: xx:xx.x)"
    echo "                       -u <BUS:DEV>...        Passthrough USB devices (format: hex:hex, support multiple)"
    echo "                       -g <BDF1> <BDF2>       Passthrough RTX 30xx GPU (two BDF parameters, format: xx:xx.x)"
    echo "  config         Configure VM resources (need to specify sub-parameters)"
    echo "                 Sub-parameters: -c (CPU core count)  -m (memory size)"
    echo "  create         Create new VM (need to specify absolute path of qcow2 image)"
    echo "  destroy        Destroy VM (Undefine + delete XML file)"
    echo "  start          Start VM"
    echo "  stop           Stop VM"
    echo "  power-sync     Configure VM shutdown sync service (execute binary file power-sync )"
    echo "  auto-start     Configure VM auto-start service (execute creat_br0.sh + start VM)"
    echo "  usb_hotlog     Control USB hotplug function"
    echo "  -h/--help      Show this help information"
    echo ""
    echo "Examples:"
    echo "  vmdeploy direct -n 03:00.0                             # Passthrough I210 network card"
    echo "  vmdeploy direct -u 3535:6300 3535:6400                 # Passthrough multiple USB devices"
    echo "  vmdeploy direct -g 01:00.0 01:00.1                     # Passthrough RTX 3060 GPU (two BDF)"
    echo "  vmdeploy config -c                                     # Configure CPU core count"
    echo "  vmdeploy create /var/lib/libvirt/images/Win11.qcow2    # Create VM (specify qcow2 path)"
    echo "  vmdeploy destroy                                       # Destroy VM"
    echo "  vmdeploy start                                         # Start VM"
    echo "  vmdeploy stop                                          # Stop VM"
    echo "  vmdeploy power-sync                                    # Configure shutdown sync service"
    echo "  vmdeploy auto-start                                    # Configure VM auto-start service"
}

# 创建虚拟机
menu_create() {
    # 检查是否传入qcow2路径参数
    if [ $# -eq 0 ]; then
        echo -e "${RED}Error: create command requires specifying the absolute path of the qcow2 image file!${NC}"
        echo "Usage: vmdeploy create /path/to/xxx.qcow2"
        return 1
    fi
    local vm_qcow2_path="$1"

    # 检查是否为绝对路径
    if [[ "$vm_qcow2_path" != /* ]]; then
        echo -e "${RED}Error: The provided path is not an absolute path!${NC}"
        echo -e "${YELLOW}Current path: $vm_qcow2_path${NC}"
        echo -e "${GREEN}Please use the absolute path, for example:${NC}"
        echo -e "  vmdeploy create $(cd "$(dirname "$vm_qcow2_path")" && pwd)/$(basename "$vm_qcow2_path")"
        return 1
    fi

    echo -e "\n${YELLOW}===== Create New VM =====${NC}"
    echo -e "${GREEN}Executing bridge creation script: $BRIDGE_CREATE_SCRIPT${NC}"
    
    # 检查网桥脚本是否存在
    if [ ! -f "$BRIDGE_CREATE_SCRIPT" ]; then
        echo -e "${RED}Error: Bridge creation script does not exist ($BRIDGE_CREATE_SCRIPT)${NC}"
        return 1
    fi
    # 检查网桥脚本是否可执行，不可执行则添加权限
    if [ ! -x "$BRIDGE_CREATE_SCRIPT" ]; then
        echo -e "${YELLOW}Warning: Bridge creation script has no execute permission, adding now...${NC}"
        chmod +x "$BRIDGE_CREATE_SCRIPT" || {
            echo -e "${RED}Error: Failed to add execute permission to the bridge script!${NC}"
            return 1
        }
    fi
    echo -e "${GREEN}Executing bridge creation script...${NC}"
    "$BRIDGE_CREATE_SCRIPT"

    # 执行虚拟机环境配置&定义脚本（vm_create）
    echo -e "${GREEN}Executing VM environment configuration script: $VM_CREATE_SCRIPT${NC}"
    # 检查vm_create脚本是否存在
    if [ ! -f "$VM_CREATE_SCRIPT" ]; then
        echo -e "${RED}Error: VM configuration script does not exist ($VM_CREATE_SCRIPT)${NC}"
        return 1
    fi
    # 检查vm_create脚本是否可执行，不可执行则添加权限
    if [ ! -x "$VM_CREATE_SCRIPT" ]; then
        echo -e "${YELLOW}Warning: VM configuration script has no execute permission, adding now...${NC}"
        chmod +x "$VM_CREATE_SCRIPT" || {
            echo -e "${RED}Error: Failed to add execute permission to the VM configuration script!${NC}"
            return 1
        }
    fi
    # 执行vm_create脚本并传入qcow2路径参数
    if "$VM_CREATE_SCRIPT" "$vm_qcow2_path"; then
        echo -e "${GREEN}VM environment configuration script executed successfully!${NC}"
    else
        echo -e "${RED}Error: VM configuration script execution failed (return code: $?)${NC}"
        return 1
    fi

    echo -e "${GREEN}VM created successfully${NC}"
}

# 销毁虚拟机
menu_destroy() {
    echo -e "\n${YELLOW}===== Destroy VM =====${NC}"
    read -p "Warning: This operation will undefine the VM and delete the XML file, confirm? (y/N) " confirm
    if [[ ! $confirm =~ ^[Yy]$ ]]; then
        echo -e "${YELLOW}Destroy operation cancelled${NC}"
        return 0
    fi

    # 调用虚拟机销毁脚本
    echo -e "${GREEN}Executing VM destroy script: $VM_DESTROY_SCRIPT${NC}"
    
    # 检查销毁脚本是否存在
    if [ ! -f "$VM_DESTROY_SCRIPT" ]; then
        echo -e "${RED}Error: VM destroy script does not exist ($VM_DESTROY_SCRIPT)${NC}"
        return 1
    fi
    # 检查销毁脚本是否可执行，不可执行则添加权限
    if [ ! -x "$VM_DESTROY_SCRIPT" ]; then
        echo -e "${YELLOW}Warning: VM destroy script has no execute permission, adding now...${NC}"
        chmod +x "$VM_DESTROY_SCRIPT" || {
            echo -e "${RED}Error: Failed to add execute permission to the destroy script!${NC}"
            return 1
        }
    fi
    # 执行销毁脚本
    if "$VM_DESTROY_SCRIPT"; then
        echo -e "${GREEN}VM destroy script executed successfully!${NC}"
    else
        echo -e "${RED}Error: VM destroy script execution failed (return code: $?)${NC}"
        return 1
    fi

    # 清空热插拔状态（保留原有逻辑）
    clear_hotplug_status
    echo -e "${GREEN}VM destroyed successfully!${NC}"
    echo -e "${GREEN}XML has been reset! /etc/vmdeploy/Windows_11.xml ${NC}"
}

# 启动虚拟机
menu_start() {
    echo -e "\n${YELLOW}===== Start VM [$VM_NAME] =====${NC}"
    
    # 1. 检查libvirtd服务状态
    if ! systemctl is-active --quiet libvirtd; then
        echo -e "${YELLOW}libvirtd service is not running, starting now...${NC}"
        systemctl start libvirtd || {
            echo -e "${RED}Error: Failed to start libvirtd service!${NC}"
            return 1
        }
        sleep 2 # 等待服务生效
    fi

    # 2. 检查虚拟机是否存在
    if ! virsh list --all | awk 'NR>2 {print $2}' | grep -wq "$VM_NAME"; then
        echo -e "${RED}Error: VM [$VM_NAME] does not exist!${NC}"
        return 1
    fi

    # 3. 检查虚拟机是否已启动
    if virsh list | grep -wq "$VM_NAME"; then
        echo -e "${YELLOW}VM [$VM_NAME] is already running, no need to start again${NC}"
        return 0
    fi

    # 4. 执行virsh start启动虚拟机
    echo -e "${GREEN}Executing: virsh start $VM_NAME${NC}"
    if virsh start "$VM_NAME" &> /dev/null; then
        echo -e "${GREEN}VM [$VM_NAME] started successfully!${NC}"
    else
        echo -e "${RED}Error: Failed to start VM [$VM_NAME]!${NC}"
        return 1
    fi
}

# ====================== 停止虚拟机（和start逻辑一致，执行virsh shutdown） ======================
menu_stop() {
    echo -e "\n${YELLOW}===== Stop VM [$VM_NAME] =====${NC}"
    
    # 1. 检查libvirtd服务状态
    if ! systemctl is-active --quiet libvirtd; then
        echo -e "${YELLOW}libvirtd service is not running, starting now...${NC}"
        systemctl start libvirtd || {
            echo -e "${RED}Error: Failed to start libvirtd service!${NC}"
            return 1
        }
        sleep 2 # 等待服务生效
    fi

    # 2. 检查虚拟机是否存在
    if ! virsh list --all | awk 'NR>2 {print $2}' | grep -wq "$VM_NAME"; then
        echo -e "${RED}Error: VM [$VM_NAME] does not exist!${NC}"
        return 1
    fi

    # 3. 检查虚拟机是否已停止
    if ! virsh list | grep -wq "$VM_NAME"; then
        echo -e "${YELLOW}VM [$VM_NAME] is already stopped, no need to stop again${NC}"
        return 0
    fi

    # 4. 执行virsh shutdown停止虚拟机
    echo -e "${GREEN}Executing: virsh shutdown $VM_NAME${NC}"
    if virsh shutdown "$VM_NAME" &> /dev/null; then
        echo -e "${GREEN}VM [$VM_NAME] shutdown command sent successfully!${NC}"
        echo -e "${GREEN}Note: VM may take a few seconds to completely stop${NC}"
    else
        echo -e "${RED}Error: Failed to send shutdown command to VM [$VM_NAME]!${NC}"
        return 1
    fi
}

# 替换：关机同步服务控制（原menu_auto_start → menu_power_sync，仅开/关交互，无过度设计）
menu_power_sync() {
    echo -e "\n${YELLOW}===== VM Shutdown Sync Service Control =====${NC}"
    PS3="Please select an operation (enter number): "
    select opt in "Enable" "Disable" "Exit"; do
        case $REPLY in
            1) 
                # 开启：复制服务文件到目标目录 + 启动服务
                echo -e "${YELLOW}Configuring shutdown sync service...${NC}"
                # 检查服务源文件是否存在
                if [ ! -f "${POWER_SYNC_SERVICE_SOURCE}" ]; then
                    echo -e "${RED}Error: Shutdown sync service source file does not exist (${POWER_SYNC_SERVICE_SOURCE})${NC}"
                    continue
                fi
                # 复制服务文件到目标文件夹
                cp "${POWER_SYNC_SERVICE_SOURCE}" "${POWER_SYNC_SERVICE_TARGET_DIR}/${POWER_SYNC_SERVICE_NAME}" || {
                    echo -e "${RED}Error: Failed to copy service file to target directory!${NC}"
                    continue
                }
                # 重新加载systemd配置
                systemctl daemon-reload
                # 启用并立即启动服务
                if systemctl enable --now "${POWER_SYNC_SERVICE_NAME}" &> /dev/null; then
                    echo -e "${GREEN}Shutdown sync service enabled!${NC}"
                    echo -e "${GREEN}Service file path: ${POWER_SYNC_SERVICE_TARGET_DIR}/${POWER_SYNC_SERVICE_NAME}${NC}"
                    echo -e "${GREEN}Execution script: ${POWER_SYNC_PYTHON_SCRIPT}${NC}"
                else
                    echo -e "${RED}Error: Failed to start shutdown sync service!${NC}"
                fi
                break 
                ;;
            2) 
                # 关闭：停止服务 + 删除服务文件
                echo -e "${YELLOW}Disabling shutdown sync service...${NC}"
                # 停止并禁用服务（容错，不存在则忽略）
                systemctl stop "${POWER_SYNC_SERVICE_NAME}" &> /dev/null || true
                systemctl disable "${POWER_SYNC_SERVICE_NAME}" &> /dev/null || true
                # 删除目标目录的服务文件
                if [ -f "${POWER_SYNC_SERVICE_TARGET_DIR}/${POWER_SYNC_SERVICE_NAME}" ]; then
                    rm -f "${POWER_SYNC_SERVICE_TARGET_DIR}/${POWER_SYNC_SERVICE_NAME}"
                    systemctl daemon-reload
                    echo -e "${GREEN}Shutdown sync service disabled!${NC}"
                    echo -e "${GREEN}Deleted service file: ${POWER_SYNC_SERVICE_TARGET_DIR}/${POWER_SYNC_SERVICE_NAME}${NC}"
                else
                    echo -e "${YELLOW}Shutdown sync service file does not exist, no need to delete${NC}"
                fi
                break 
                ;;
            3) echo "Exit shutdown sync service control"; break ;;
            *) echo -e "${RED}Error: Please enter a number between 1-3${NC}" ;;
        esac
    done
}

# 虚拟机自启动服务控制
menu_auto_start() {
    echo -e "\n${YELLOW}===== VM Auto-Start Service Control =====${NC}"
    PS3="Please select an operation (enter number): "
    select opt in "Enable" "Disable" "Exit"; do
        case $REPLY in
            1) 
                # 开启：复制服务文件到目标目录 + 启动服务
                echo -e "${YELLOW}Configuring VM auto-start service...${NC}"
                # 检查服务源文件是否存在
                if [ ! -f "${AUTO_START_SERVICE_SOURCE}" ]; then
                    echo -e "${RED}Error: VM auto-start service source file does not exist (${AUTO_START_SERVICE_SOURCE})${NC}"
                    continue
                fi
                # 复制服务文件到目标文件夹
                cp "${AUTO_START_SERVICE_SOURCE}" "${AUTO_START_SERVICE_TARGET_DIR}/${AUTO_START_SERVICE_NAME}" || {
                    echo -e "${RED}Error: Failed to copy service file to target directory!${NC}"
                    continue
                }
                # 重新加载systemd配置
                systemctl daemon-reload
                # 启用并立即启动服务
                if systemctl enable "${AUTO_START_SERVICE_NAME}" &> /dev/null; then
                    echo -e "${GREEN}VM auto-start service enabled!${NC}"
                    echo -e "${GREEN}Service file path: ${AUTO_START_SERVICE_TARGET_DIR}/${AUTO_START_SERVICE_NAME}${NC}"
                    echo -e "${GREEN}Service will execute: /usr/local/bin/creat_br0.sh → virsh start Windows_11${NC}"
                else
                    echo -e "${RED}Error: Failed to enable VM auto-start service!${NC}"
                fi
                break 
                ;;
            2) 
                # 关闭：停止服务 + 删除服务文件
                echo -e "${YELLOW}Disabling VM auto-start service...${NC}"
                # 停止并禁用服务（容错，不存在则忽略）
                systemctl stop "${AUTO_START_SERVICE_NAME}" &> /dev/null || true
                systemctl disable "${AUTO_START_SERVICE_NAME}" &> /dev/null || true
                # 删除目标目录的服务文件
                if [ -f "${AUTO_START_SERVICE_TARGET_DIR}/${AUTO_START_SERVICE_NAME}" ]; then
                    rm -f "${AUTO_START_SERVICE_TARGET_DIR}/${AUTO_START_SERVICE_NAME}"
                    systemctl daemon-reload
                    echo -e "${GREEN}VM auto-start service disabled!${NC}"
                    echo -e "${GREEN}Deleted service file: ${AUTO_START_SERVICE_TARGET_DIR}/${AUTO_START_SERVICE_NAME}${NC}"
                else
                    echo -e "${YELLOW}VM auto-start service file does not exist, no need to delete${NC}"
                fi
                break 
                ;;
            3) echo "Exit VM auto-start service control"; break ;;
            *) echo -e "${RED}Error: Please enter a number between 1-3${NC}" ;;
        esac
    done
}

# 设备直通配置
menu_direct() {
    if [ $# -eq 0 ]; then
        echo -e "${RED}Error: direct requires sub-parameters!${NC}"
        echo "Supported parameters: -n <BDF>  -u <BUS:DEV>...  -g <BDF1> <BDF2>  -a <BDF>  -c <DEVICE> <COM>"
        echo "Example: vmdeploy direct -n 03:00.0, vmdeploy direct -c /dev/ttyS2 COM3"
        return 1
    fi

    case "$1" in
        -n)
            shift  # 移除-n参数，获取后续所有BDF参数
            # 检查是否传入至少一个BDF
            if [ $# -eq 0 ]; then
                echo -e "${RED}Error: -n parameter requires specifying one or more I210 network card BDFs (e.g. 03:00.0 1a:00.1)!${NC}"
                return 1
            fi
            local input_bdfs=("$@")  # 接收所有传入的BDF参数
            local valid_bdfs=()       # 存储校验通过的有效BDF
            
            # 循环校验每个BDF
            for bdf in "${input_bdfs[@]}"; do
                if validate_bdf "$bdf"; then
                    valid_bdfs+=("$bdf")  # 有效BDF加入列表
                else
                    echo -e "${YELLOW}Warning: Skipping invalid or non-existent BDF [$bdf]${NC}"
                fi
            done
            
            # 检查是否有有效BDF
            if [ ${#valid_bdfs[@]} -eq 0 ]; then
                echo -e "${RED}Error: No valid I210 network card BDFs provided!${NC}"
                return 1
            fi

            # 检查net_direct脚本
            if ! check_net_direct; then
                return 1
            fi

            # 执行脚本
            echo -e "${YELLOW}Executing network card passthrough script, generating XML configuration for BDFs [${valid_bdfs[*]}]...${NC}"
            if ! "$NET_DIRECT_SCRIPT" "${valid_bdfs[@]}"; then  # 传入多个有效BDF
                echo -e "${RED}Error: Failed to execute net_direct script!${NC}"
                return 1
            fi

            # 插入XML配置
            echo -e "${YELLOW}Inserting passthrough configuration into VM main XML file...${NC}"
            if insert_passthrough_xml "${valid_bdfs[0]}"; then
                echo -e "${GREEN}===== Network Card Passthrough Configuration Completed =====${NC}"
                echo -e "${GREEN}1. Network Card BDFs: ${valid_bdfs[*]}${NC}"  # 调整输出，显示所有有效BDF
                echo -e "${GREEN}2. VM XML File: $VM_XML_SOURCE_PATH${NC}"
            fi
            ;;
        -u)
            # 检查USB热插拔是否开启，开启则禁止执行
            if [ $HOTPLUG_STATUS -eq 1 ]; then
                echo -e "${RED}Error: USB hotplug function is enabled, USB static passthrough configuration is prohibited!${NC}"
                echo -e "${YELLOW}Solution: First execute vmdeploy usb_hotlog to disable hotplug function${NC}"
                return 1
            fi

            shift
            if [ $# -eq 0 ]; then
                echo -e "${RED}Error: -u parameter requires specifying USB device (e.g. 3535:6300)!${NC}"
                return 1
            fi
            local usb_params=("$@")
            if ! validate_usb_params "${usb_params[@]}"; then
                return 1
            fi
            if ! check_usb_direct; then
                return 1
            fi
            echo -e "${YELLOW}Executing USB disk passthrough script, parameters: ${usb_params[*]}${NC}"
            if ! "$USB_DIRECT_SCRIPT" "${usb_params[@]}"; then
                echo -e "${RED}Error: Failed to execute usb_direct script!${NC}"
                return 1
            fi
            # USB静态直通配置成功后，更新状态为1
            update_usb_direct_status 1
            echo -e "${GREEN}===== USB Device Passthrough Configuration Completed =====${NC}"
            echo -e "${GREEN}1. USB Parameters: ${usb_params[*]}${NC}"
            echo -e "${GREEN}2. VM XML File: $VM_XML_SOURCE_PATH${NC}"
            ;;
        -g)
            # 检查是否传入两个BDF参数
            if [ -z "$2" ] || [ -z "$3" ]; then
                echo -e "${RED}Error: -g parameter requires specifying two GPU BDF parameters (e.g. 01:00.0 01:00.1)!${NC}"
                return 1
            fi
            local gpu_bdf1=$2
            local gpu_bdf2=$3
            # 分别校验两个BDF格式和存在性
            if ! validate_bdf "$gpu_bdf1"; then
                return 1
            fi
            if ! validate_bdf "$gpu_bdf2"; then
                return 1
            fi
            if ! check_gpu_direct; then
                return 1
            fi
            echo -e "${YELLOW}Executing GPU passthrough script, generating XML configuration for BDF $gpu_bdf1 and $gpu_bdf2...${NC}"
            # 传入两个BDF参数给gpu_direct脚本
            if ! "$GPU_DIRECT_SCRIPT" "$gpu_bdf1" "$gpu_bdf2"; then
                echo -e "${RED}Error: Failed to execute gpu_direct script!${NC}"
                return 1
            fi
            echo -e "${YELLOW}Inserting passthrough configuration into VM main XML file...${NC}"
            # 调用显卡专用插入函数（函数内部未使用BDF参数，传第一个即可）
            if insert_gpu_passthrough_xml "$gpu_bdf1"; then
                echo -e "${GREEN}===== RTX 30xx GPU Passthrough Configuration Completed =====${NC}"
                echo -e "${GREEN}1. GPU BDF 1: $gpu_bdf1${NC}"
                echo -e "${GREEN}2. GPU BDF 2: $gpu_bdf2${NC}"
                echo -e "${GREEN}3. VM XML File: $VM_XML_SOURCE_PATH${NC}"
            fi
            ;;
        -a)
            # 适配AI推理卡直通：使用和网卡一致的BDF格式校验
            if [ -z "$2" ]; then
                echo -e "${RED}Error: -a parameter requires specifying AI inference card BDF (e.g. 02:00.0)!${NC}"
                return 1
            fi
            local ai_bdf=$2
            # 复用网卡的BDF校验函数（格式+存在性）
            if ! validate_bdf "$ai_bdf"; then
                return 1
            fi
            # 检查ai_direct脚本是否存在且可执行
            if ! check_ai_direct; then
                return 1
            fi
            # 执行AI推理卡直通脚本（传入BDF参数）
            echo -e "${YELLOW}Executing AI inference card passthrough script, BDF: $ai_bdf${NC}"
            if ! /usr/local/bin/ai_direct "$ai_bdf"; then
                echo -e "${RED}Error: Failed to execute ai_direct script!${NC}"
                return 1
            fi
            # 输出完成信息
            echo -e "${GREEN}===== AI Inference Card Passthrough Configuration Completed =====${NC}"
            echo -e "${GREEN}1. AI Inference Card BDF: $ai_bdf${NC}"
            echo -e "${GREEN}2. VM XML File: $VM_XML_SOURCE_PATH${NC}"
            ;;
        -i)
            # 1. 移位获取BDF参数，简单检查参数是否存在
            shift
            if [ $# -eq 0 ]; then
                echo -e "${RED}Error: -i parameter requires specifying UHD Graphics 630 BDF (e.g. 00:02.0)!${NC}"
                return 1
            fi
            local igpu_bdf=$1  # 核显仅需1个BDF参数，直接接收

            # 2. 使用现有validate_bdf函数检验BDF
            if ! validate_bdf "$igpu_bdf"; then
                return 1
            fi

            # 3. 简单检查核显脚本是否存在且可执行
            if [ ! -x "$IGPU_DIRECT_SCRIPT" ]; then
                echo -e "${RED}Error: igpu_direct script not found or not executable ($IGPU_DIRECT_SCRIPT)!${NC}"
                return 1
            fi

            # 4. 执行核显直通脚本，传递BDF参数
            echo -e "${YELLOW}Executing iGPU passthrough script, BDF: $igpu_bdf${NC}"
            if ! "$IGPU_DIRECT_SCRIPT" "$igpu_bdf"; then
                echo -e "${RED}Error: Failed to execute igpu_direct script!${NC}"
                return 1
            fi

            # 5. 输出完成信息，格式与其他分支保持一致
            echo -e "${GREEN}===== UHD Graphics 630 iGPU Passthrough Configuration Completed =====${NC}"
            echo -e "${GREEN}1. iGPU BDF: $igpu_bdf${NC}"
            echo -e "${GREEN}2. VM XML File: $VM_XML_SOURCE_PATH${NC}"
            ;;
        # 串口直通分支（-c）
        -c)
            shift
            # 检查参数数量（必须2个：设备路径 + COM口）
            if [ $# -ne 2 ]; then
                echo -e "${RED}Error: -c parameter requires exactly 2 parameters (serial device path + COM port), e.g., /dev/ttyS2 COM3!${NC}"
                return 1
            fi
            local serial_dev=$1
            local com_port=$2

            # 校验串口参数合法性
            if ! validate_serial_params "$serial_dev" "$com_port"; then
                return 1
            fi

            # 检查serial_direct脚本
            if ! check_serial_direct; then
                return 1
            fi

            # 执行串口直通脚本
            echo -e "${YELLOW}Executing serial passthrough script: $serial_dev → $com_port...${NC}"
            if ! "$SERIAL_DIRECT_SCRIPT" "$serial_dev" "$com_port"; then
                echo -e "${RED}Error: Failed to execute serial_direct script!${NC}"
                return 1
            fi

            # 输出完成信息
            echo -e "${GREEN}===== Serial Port Passthrough Configuration Completed =====${NC}"
            echo -e "${GREEN}1. Serial Device: $serial_dev${NC}"
            echo -e "${GREEN}2. Windows COM Port: $com_port${NC}"
            echo -e "${GREEN}3. VM XML File: $VM_XML_SOURCE_PATH${NC}"
            ;;
        *)
            echo -e "${RED}Error: Unknown direct parameter $1${NC}"
            echo "Supported parameters: -n <BDF>  -u <BUS:DEV>...  -g <BDF1> <BDF2>  -a <BDF>  -c <DEVICE> <COM>"
            return 1
            ;;
    esac
}

# CPU核心数配置
menu_config_cpu() {
    echo -e "\n${YELLOW}===== CPU Core Count Configuration =====${NC}"
    PS3="Please select CPU core count (enter number): "
    select cpu in "4 Cores" "6 Cores" "8 Cores" "Exit"; do
        case $REPLY in
            1) target_cpu=4; sockets=1; cores=4; threads=1 ;;
            2) target_cpu=6; sockets=1; cores=6; threads=1 ;;
            3) target_cpu=8; sockets=1; cores=8; threads=1 ;;
            4) echo "Exit CPU configuration"; break ;;
            *) echo -e "${RED}Error: Please enter a number between 1-4${NC}"; continue ;;
        esac
        if [ -n "$target_cpu" ]; then
            sed -i "s/<vcpu placement=['\"]auto['\"]>[0-9]\+<\/vcpu>/<vcpu placement='auto'>${target_cpu}<\/vcpu>/g" "$VM_XML_SOURCE_PATH"
            sed -i "s/<topology sockets=['\"]*[0-9]\+['\"]* dies=['\"]*[0-9]\+['\"]* clusters=['\"]*[0-9]\+['\"]* cores=['\"]*[0-9]\+['\"]* threads=['\"]*[0-9]\+['\"]*\/>/<topology sockets='${sockets}' dies='1' clusters='1' cores='${cores}' threads='${threads}'\/>/g" "$VM_XML_SOURCE_PATH"
            echo -e "${GREEN}Configured VM CPU core count to ${target_cpu} cores${NC}"
            unset target_cpu sockets cores threads
            break
        fi
    done
}

# 内存大小配置
menu_config_mem() {
    echo -e "\n${YELLOW}===== Memory Size Configuration =====${NC}"
    local MEM_16G_KiB="16777216"  # 16G = 16 * 1024 * 1024 KiB
    local MEM_20G_KiB="20971520"  # 20G = 20 * 1024 * 1024 KiB
    local MEM_24G_KiB="25165824"  # 24G = 24 * 1024 * 1024 KiB
    local MEM_28G_KiB="29360128"  # 28G = 28 * 1024 * 1024 KiB

    PS3="Please select memory size (enter number): "
    select mem in "16G" "20G" "24G" "28G" "Exit"; do
        case $REPLY in
            1) target_mem="$MEM_16G_KiB"; mem_label="16G" ;;
            2) target_mem="$MEM_20G_KiB"; mem_label="20G" ;;
            3) target_mem="$MEM_24G_KiB"; mem_label="24G" ;;
            4) target_mem="$MEM_28G_KiB"; mem_label="28G" ;;
            5) echo "Exit memory configuration"; break ;;
            *) echo -e "${RED}Error: Please enter a number between 1-5${NC}"; continue ;;
        esac
        if [ -n "$target_mem" ]; then
            sed -i "s/<memory unit=['\"]KiB['\"]>[0-9]\+<\/memory>/<memory unit='KiB'>${target_mem}<\/memory>/g" "$VM_XML_SOURCE_PATH"
            sed -i "s/<currentMemory unit=['\"]KiB['\"]>[0-9]\+<\/currentMemory>/<currentMemory unit='KiB'>${target_mem}<\/currentMemory>/g" "$VM_XML_SOURCE_PATH"
            echo -e "${GREEN}Configured VM memory size to ${mem_label}${NC}"
            unset target_mem mem_label
            break
        fi
    done
}

# USB热插拔控制
menu_hotlog() {
    echo -e "\n${YELLOW}===== USB Hotplug Function Control =====${NC}"
    echo -e "Current hotplug status: $(get_hotplug_status_desc)"
    PS3="Please select an operation (enter number): "
    select opt in "Enable" "Disable" "Exit"; do
        case $REPLY in
            1) 
                # 检查USB静态直通是否已配置，已配置则禁止开启热插拔
                if [ $USB_DIRECT_STATUS -eq 1 ]; then
                    echo -e "${RED}Error: USB static passthrough (direct -u) is configured, USB hotplug function is prohibited!${NC}"
                    echo -e "${YELLOW}Solution: First restore the VM XML backup and delete the USB static passthrough configuration before trying${NC}"
                    continue
                fi

                # 开启热插拔：复制udev规则文件
                if [ ! -f "$USB_HOTLOG_RULES_SOURCE" ]; then
                    echo -e "${RED}Error: Source rule file does not exist ($USB_HOTLOG_RULES_SOURCE)${NC}"
                    continue
                fi
                if cp "$USB_HOTLOG_RULES_SOURCE" "$USB_HOTLOG_RULES_TARGET"; then
                    udevadm control --reload-rules && udevadm trigger
                    update_hotplug_status 1
                    echo -e "${GREEN}Copied hotplug rule file:${NC}"
                    echo -e "${GREEN}Source file: $USB_HOTLOG_RULES_SOURCE${NC}"
                    echo -e "${GREEN}Target file: $USB_HOTLOG_RULES_TARGET${NC}"
                    echo -e "${GREEN}Enabled VM USB hotplug function${NC}"
                else
                    echo -e "${RED}Failed to copy rule file, please check permissions!${NC}"
                    continue
                fi
                break 
                ;;
            2) 
                # 关闭热插拔：删除udev规则文件
                if [ -f "$USB_HOTLOG_RULES_TARGET" ]; then
                    if rm -f "$USB_HOTLOG_RULES_TARGET"; then
                        update_hotplug_status 0
                        echo -e "${GREEN}Deleted hotplug rule file: $USB_HOTLOG_RULES_TARGET${NC}"
                        echo -e "${GREEN}Disabled VM USB hotplug function${NC}"
                    else
                        echo -e "${RED}Failed to delete rule file, please check permissions!${NC}"
                        continue
                    fi
                else
                    update_hotplug_status 0
                    echo -e "${YELLOW}Rule file does not exist, directly update hotplug status to disabled${NC}"
                    echo -e "${GREEN}Disabled VM USB hotplug function${NC}"
                fi
                break 
                ;;
            3) echo "Exit USB hotplug control"; break ;;
            *) echo -e "${RED}Error: Please enter a number between 1-3${NC}" ;;
        esac
    done
}

# 主逻辑
init_hotplug_status
init_usb_direct_status

if [ $# -eq 0 ]; then
    show_help
    exit 1
fi

case "$1" in
    # 直通配置
    direct)
        shift
        menu_direct "$@"
        ;;
    # 资源配置
    config)
        shift
        if [ $# -eq 0 ]; then
            echo -e "${RED}Error: config requires sub-parameters!${NC}"
            echo "Supported parameters: -c (CPU)  -m (Memory)"
            exit 1
        fi
        case "$1" in
            # -c cpu配置， -m 内存配置
            -c) menu_config_cpu ;;
            -m) menu_config_mem ;;
            *) echo -e "${RED}Error: Unknown parameter $1${NC}"; exit 1 ;;
        esac
        ;;
    # define虚拟机
    create)
        shift
        menu_create "$@"
        ;;
    # 销毁虚拟机
    destroy) menu_destroy ;;
    # 启动虚拟机
    start) menu_start ;;
    #关闭虚拟机
    stop) menu_stop ;;
    # 电源同步
    power-sync) menu_power_sync ;;
    # 自动启动
    auto-start) menu_auto_start ;;
    # 热插拔
    usb_hotlog) menu_hotlog ;;
    #帮助手册
    -h|--help) show_help ;;
    *) echo -e "${RED}Error: Unknown command $1${NC}"; show_help; exit 1 ;;
esac
