#!/bin/bash
VM_NAME=${VM_NAME:-TEST}
VM_MEMORY_SIZE=${VM_MEMORY_SIZE:-1024}
VM_NET_MAC=${VM_NET_MAC:-52:54:00:c1:0d:ff}
VM_NET_INT=${VM_NET_INT:-eth0}
VN_NET_TYPE=${VM_NET_TYPE:-direct}
LIB_VIRT_VER=`virsh -v`
LIB_VIRT_VER_BASE="0.9"
REDHAT_RELEASE="$( cat /etc/redhat-release | awk '{print $1}' )"
# devices
VM_HW_HDD=${VM_HW_HDD:-ide}
VM_HW_NET=${VM_HW_NET:-rtl8139}
if [ "${REDHAT_RELEASE}" = "Fedora" ]
then VM_EMULATOR="/usr/bin/qemu-kvm"
else VM_EMULATOR="/usr/libexec/qemu-kvm"
fi
#VM_DISK_1="/var/lib/libvirt/images/grid_cloud-win_xp.img"
#VM_DISK_2="/var/lib/libvirt/images/win_xp.img"
#VM_CD_DISK_1="/home/Barracuda/Documents/Work/development/tftp/pxelinux/iso/f16-x86_64-netinst.iso"
#VM_CD_DISK_2="/home/Barracuda/Documents/Work/development/tftp/pxelinux/iso/f16-i386-netinst.iso"
function gen_network_direct {
local iface=$1
local mac=$2
cat << END
END
}
function gen_network_bridge {
local iface=$1
local mac=$2
if [ "${REDHAT_RELEASE}" = "Fedora" ]
then cat << END
END
else cat << END
END
fi
}
cat << END > vm.xml
$VM_NAME
END
if [ $LIB_VIRT_VER_BASE = `echo -e "$LIB_VIRT_VER_BASE\n$LIB_VIRT_VER" | sort -n | head -n1` ] # if True then LIB_VIRT_VER_BASE smaler then LIB_VIRT_VER
then cat << END >> vm.xml
$VM_MEMORY_SIZE$VM_MEMORY_SIZE
END
else
VM_MEMORY_SIZE=$((VM_MEMORY_SIZE*1024))
cat << END >> vm.xml
$VM_MEMORY_SIZE$VM_MEMORY_SIZE
END
fi
cat << END >> vm.xml
1hvmdestroyrestartrestart$VM_EMULATOR
END
#DANGER!!!! magic begins
printf -v alphabet "%c" {a..z}
BUS="0"
var=""
ind=1
i=1
#++++++++++++++++++++++HDD+++++++++++++++++++++++++++++++++++
eval var=\$VM_DISK_$ind
while [ -n "$var" ]
do
unit_id=$[ind-1]
DEV=`echo hd${alphabet[@]:$unit_id:1}`
cat << END >> vm.xml
END
ind=$[ind+1]
i=$[i+1]
eval var=\$VM_DISK_$ind
done
#++++++++++++++++++++++CD++++++++++++++++++++++++++++++++++++
BUS=$[BUS+1] # CD use another bus
ind=1 # unit ID and variable name begins from start
var="" # set to default
i=$[i-1] # need shif to use DEV in oder
eval var=\$VM_CD_DISK_$ind
while [ -n "$var" ]
do
unit_id=$[ind-1]
DEV=`echo hd${alphabet[@]:$i:1}`
cat << END >> vm.xml
END
ind=$[ind+1]
i=$[i+1]
eval var=\$VM_CD_DISK_$ind
done
#end of magic
if [ $LIB_VIRT_VER_BASE = `echo -e "$LIB_VIRT_VER_BASE\n$LIB_VIRT_VER" | sort -n | head -n1` ] # if True then LIB_VIRT_VER_BASE smaler then LIB_VIRT_VER
then
cat << END >> vm.xml
END
fi
cat << END >> vm.xml
END
#
# network
#
if [ "$VN_NET_TYPE" = "direct" ]; then
gen_network_direct "$VM_NET_INT" "$VM_NET_MAC" >> vm.xml
elif [ "$VN_NET_TYPE" = "bridge" ]; then
gen_network_bridge "$VM_NET_INT" "$VM_NET_MAC" >> vm.xml
fi
cat << END >> vm.xml
END
function check_vm_running {
virsh -r -c qemu:///system list | grep -qe "\s${VM_NAME}\s"
return $?
}
function destroy_vm {
virsh -c qemu:///system destroy ${VM_NAME}
}
virsh -c qemu:///system create vm.xml