#!/bin/bash
# Script called on the primary server for stopping VM

# For logging into SafeKit log use:
# $SAFE/safekit printi | printe "message" 

#----------------------------------------------------------
#
# 2 stop modes:
#
# - graceful stop
#
# - force stop ($1=force)
#
#----------------------------------------------------------

# stdout goes into Application log
echo "Running stop_prim $*" 

# Stop VM_NAME
unset LANG
res=0 

if ([ "$1" = "force" ]) ; then
	virsh destroy --graceful $VM_NAME
else
	virsh shutdown $VM_NAME
fi

state=$(virsh domstate $VM_NAME)
if ([ "x$state" == "x" ]) ; then
	res=1
	$SAFE/safekit printe "$VM_NAME not found"
else
	let i=1
	while ( [ $i -le 5 ] && [ "x$state" == "xrunning" ]); do
		# Stop VM_NAME
		virsh shutdown $VM_NAME
		sleep 5
                state=$(virsh domstate $VM_NAME)
      		let i=i+1
	done
	if ([ "x$state" == "xrunning" ]) ; then
		res=1
		$SAFE/safekit printe "$VM_NAME stop failed"
	fi
fi

[ $res -ne 0 ] && $SAFE/safekit printe "stop_prim failed"


