#!/bin/bash

# 定义虚拟机名称数组
VM_NAMES=("servera" "serverb" "serverc" "serverd" "router")

# 检查输入参数
if [ "$#" -ne 2 ]; then
    echo "使用方法: $0 {start|stop|restart|status|console|create|drop} {servera|serverb|serverc|serverd|router|all}"
    exit 1
fi

ACTION=$1
TARGET_VM=$2

# 检查是否是合法的虚拟机名称
if [[ ! " ${VM_NAMES[*]} " =~ " ${TARGET_VM} " ]] && [ "${TARGET_VM}" != "all" ]; then
    echo "错误：无效的虚拟机名称 '${TARGET_VM}'。"
    exit 1
fi

function manage_vm() {
    local vm_name=$1
    local action=$2
    local FILE_PATH="/var/lib/libvirt/images/${vm_name}.qcow2"

    # 检查虚拟机是否存在
    if ! virsh dominfo $vm_name > /dev/null 2>&1; then
        echo "虚拟机 ${vm_name} 不存在。"
        return
    fi

    case $action in
        start)
            if [[ $(virsh domstate $vm_name) =~ "running" ]]; then
                echo "虚拟机 ${vm_name} 已在运行。"
            else
                virsh start $vm_name
                echo "虚拟机 ${vm_name} 启动中。"
            fi
            ;;
        stop)
            if [[ $(virsh domstate $vm_name) =~ "shut off" ]]; then
                echo "虚拟机 ${vm_name} 已关闭。"
            else
                virsh shutdown $vm_name
                echo "虚拟机 ${vm_name} 关闭中。"
            fi
            ;;
        restart)
            virsh reboot $vm_name
            echo "虚拟机 ${vm_name} 重启中。"
            ;;
        status)
            echo "虚拟机 ${vm_name} 状态：$(virsh domstate $vm_name)"
            ;;
        console)
            virsh console $vm_name
            ;;
        create)
            if [ ! -f "${FILE_PATH}" ]; then
                echo "磁盘文件不存在：${FILE_PATH}，正在复制..."
                cp "/var/lib/libvirt/images/server.qcow2" "${FILE_PATH}"
            fi
            if ! virsh dominfo $vm_name > /dev/null 2>&1; then
                echo "虚拟机 ${vm_name} 不存在，正在创建..."
                sudo virt-install --name=${vm_name} \
                --ram=2048 --vcpus=2 \
                --disk path=${FILE_PATH},format=qcow2,bus=virtio \
                --network bridge=virbr0,model=virtio \
                --os-type=linux \
                --os-variant=generic \
                --import --noautoconsole
            else
                echo "虚拟机 ${vm_name} 已存在。"
            fi
            ;;
        drop)
            # 删除虚拟机的逻辑
            if virsh dominfo $vm_name > /dev/null 2>&1; then
                virsh destroy $vm_name
                virsh undefine $vm_name
                rm -f "${FILE_PATH}"
                echo "虚拟机 ${vm_name} 和磁盘文件已删除。"
            else
                echo "虚拟机 ${vm_name} 不存在。"
            fi
            ;;
        *)
            echo "无效的操作：$action"
            exit 1
            ;;
    esac
}

# 如果指定了all，则对所有虚拟机执行操作
if [ "${TARGET_VM}" == "all" ]; then
    for vm in "${VM_NAMES[@]}"; do
        manage_vm $vm $ACTION
    done
else
    manage_vm $TARGET_VM $ACTION
fi
