#!/bin/bash

VM_NAME="rhel9.2"
VM_IP="192.168.122.231"

wait_vm_up()
{
	while true; do
		ping -c 3 -q "$VM_IP" > /dev/null
		ret=$?

		if [ $ret -eq 0 ]; then
		       break;
		fi
	done
}

paused_vm_presents()
{
	ssh root@"$VM_IP" "virsh list" | grep "paused"
	return $?
}

running_vms_count()
{
	ssh root@"$VM_IP" "virsh list" | grep "running" | wc -l
}

iteration=1

while true; do
	echo "Iteration $iteration, resetting VM..."
	# virsh reset --domain "$VM_NAME" > /dev/null
	ssh root@"$VM_IP" "echo b > /proc/sysrq-trigger" &
	sleep 2

       	wait_vm_up
	#echo "VM is ping-able"
	if paused_vm_presents ; then
		echo "Found a paused VM, exiting!"
		date
		ssh root@"$VM_IP" "virsh list"
		break
	fi
	num=$(running_vms_count)
	if [ $num -ne 10 ]; then
		echo "Number of running VMs != 10, exiting"
		date
		ssh root@"$VM_IP" "virsh list"
		break
	fi
	iteration=$(($iteration + 1))
done


