#!/bin/bash set -Eeuo pipefail if [[ $# -ne 1 ]]; then echo "Usage: $0 " exit 1 fi VM="${1}" if [ -d "/var/lib/libvirt/images/${VM}/" ]; then echo "VM ${VM} already exists. Please remove it first." exit 1 fi temp_dir=$(mktemp -d) cleanup() { local exit_code=$? rm -rf "$temp_dir" if [ $exit_code -ne 0 ]; then echo "An error occurred. Cleaning up..." virsh destroy "${VM}" || true virsh undefine "${VM}" --nvram || true rm -rf "/var/lib/libvirt/images/${VM}/" fi } trap cleanup EXIT # Create a temporary directory to hold the VM image and copy the base image there install -m 0710 -o root -g qemu --context=system_u:object_r:virt_image_t:s0 -d "$temp_dir" install -m 0710 -o root -g qemu -Z -d "/var/lib/libvirt/images/${VM}" # Migrate the VM disk from Hyper-V to KVM echo "Copying the VM disk from Hyper-V..." rclone copy "$DOMAIN_HYPERV_DISK_LOCATION" "$temp_dir" echo "Converting the VM disk to qcow2 format..." qemu-img convert -O qcow2 "$temp_dir/$DOMAIN_HYPERV_DISK_NAME" "/var/lib/libvirt/images/${VM}/root.qcow2" restorecon -F "/var/lib/libvirt/images/${VM}/root.qcow2" # Create and start the VM using virt-install echo "Creating and starting the VM ${VM}..." virt-install --name "${VM}" \ --autostart \ --cpu=host-passthrough \ --vcpus=${DOMAIN_VCPUS} \ --ram=${DOMAIN_RAM} \ --os-variant=${DOMAIN_OS_VARIANT} \ --disk=path=/var/lib/libvirt/images/${VM}/root.qcow2,bus=sata,format=qcow2 \ --disk=path=/usr/share/virtio-win/virtio-win.iso,device=cdrom,bus=sata \ --boot uefi \ --import \ --network=network=default,mac=${DOMAIN_MAC_ADDRESS} \ --noautoconsole echo "VM ${VM} has been created and started." exit 0