#!/bin/bash

vm_username=root
vm_passwd=suse
SSH_OPTS="-q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no"

function wait_bootup() {
    vm_ip=$1

    echo "waiting for VM with IP $vm_ip to boot..."
    for i in `seq 0 120`; do
	sshpass -p $vm_passwd ssh $SSH_OPTS -o ConnectTimeout=0 $vm_username@$vm_ip "cat /dev/null"
	if [ $? == 0 ]; then
            return
        fi
	sleep 5
    done
    echo "Could not ssh to VM within 600 seconds!"
    exit 1
}

function wait_shutdown() {
    vm_name=$1

    echo "waiting for VM $vm_name to shutdown..."
    state="running"
    for i in `seq 0 120`; do 
        state=`virsh domstate $vm_name`
        if [ "$state" == "shut off" ] ; then
            break
        fi
        sleep 5
    done
    if [ "$state" != "shut off" ]; then
        echo "VM $vm_name did not shutdown within 600 seconds!"
        exit 1
    fi
    
}

count=0

vm1_name=testvm1
vm1_ip=10.156.210.174

vm2_name=testvm2
vm2_ip=10.156.210.175

vm3_name=testvm3
vm3_ip=10.156.210.176

vm4_name=testvm4
vm4_ip=10.156.210.177

vm5_name=testvm5
vm5_ip=10.156.210.178

vm6_name=testvm6
vm6_ip=10.156.210.179

while true; do
    virsh start $vm1_name
    virsh start $vm2_name
    virsh start $vm3_name
    virsh start $vm4_name
    virsh start $vm5_name
    virsh start $vm6_name

    # Wait for each VM to come alive, ensuring it can respond to shutdown requests
    wait_bootup $vm1_ip
    wait_bootup $vm2_ip
    wait_bootup $vm3_ip
    wait_bootup $vm4_ip
    wait_bootup $vm5_ip
    wait_bootup $vm6_ip
    echo "VMs started!"

    virsh shutdown $vm1_name &
    virsh shutdown $vm2_name &
    virsh shutdown $vm3_name &
    virsh shutdown $vm4_name &
    virsh shutdown $vm5_name &
    virsh shutdown $vm6_name &
    echo "VMs shutdown, waiting..."
    wait

    wait_shutdown $vm1_name
    wait_shutdown $vm2_name
    wait_shutdown $vm3_name
    wait_shutdown $vm4_name
    wait_shutdown $vm5_name
    wait_shutdown $vm6_name
        
    echo "Check if libvirtd is alive..."
    virsh list > /dev/null 2>&1
    if [ $? != 0 ]; then
	echo "No! Unable to connect to libvirtd!"
	exit 1
    fi

    let count=count+1
    echo "Yes! Iteration $count done"
    echo ""
done
