#!/bin/bash

# 检查输入参数
if [ "$#" -lt 3 ]; then
    echo "Usage: $0 <vm_name> <cpu_count> <memory_size_in_GB>"
    exit 1
fi

VM_NAME=$1
CPU_COUNT=$2
MEMORY_SIZE_GB=$3
TIMESTAMP=$(date +%s)
XML_FILE="/opt/data/${VM_NAME}img/${VM_NAME}.xml"
BACKUP_FILE="/tmp/${VM_NAME}_${TIMESTAMP}_backup.xml"

MEMORY_SIZE_KB=$((MEMORY_SIZE_GB * 1024 * 1024))

# 检查虚拟机是否存在
if ! virsh dominfo "$VM_NAME" > /dev/null 2>&1; then
    echo "Error: Virtual machine '$VM_NAME' does not exist."
    exit 1
fi

# 备份原始配置
cp "$XML_FILE" "$BACKUP_FILE"

# 导出虚拟机 XML 配置
virsh dumpxml "$VM_NAME" > "$XML_FILE"
if [ $? -ne 0 ]; then
    echo "Error: Failed to export XML configuration for '$VM_NAME'."
    exit 1
fi


# 校验 XML 配置字段是否存在
if ! grep -q "<memory unit='KiB'>" "$XML_FILE"; then
    echo "Error: Memory configuration (<memory>) not found in XML file."
    exit 1
fi

if ! grep -q "<currentMemory unit='KiB'>" "$XML_FILE"; then
    echo "Error: Current memory configuration (<currentMemory>) not found in XML file."
    exit 1
fi

if ! grep -q "<vcpu placement='static'" "$XML_FILE"; then
    echo "Error: CPU configuration (<vcpu>) not found in XML file."
    exit 1
fi

# 修改 XML 配置
sed -i "s|<memory unit='KiB'>[0-9]*</memory>|<memory unit='KiB'>${MEMORY_SIZE_KB}</memory>|" "$XML_FILE"
sed -i "s|<currentMemory unit='KiB'>[0-9]*</currentMemory>|<currentMemory unit='KiB'>${MEMORY_SIZE_KB}</currentMemory>|" "$XML_FILE"
sed -i "s|<vcpu placement='static'[^>]*>[0-9]*</vcpu>|<vcpu placement='static'>${CPU_COUNT}</vcpu>|" "$XML_FILE"

# 重新定义虚拟机
virsh define "$XML_FILE"
if [ $? -ne 0 ]; then
    echo "Error: Failed to redefine virtual machine '$VM_NAME'."
    echo "You can restore the original configuration using:"
    echo "virsh define $BACKUP_FILE"
    exit 1
fi
