#!/usr/bin/bash
#
# Note: libvirt hook scripts execute with uid=0(root) gid=0(root) for all
#       operations, i.e., started, stopped.
#

function log {
	echo "$(date +"%Y/%m/%d %T"):libvirt_hooks:ws; $@" >>/var/log/anvil.log;
}

log "wsargs=$@"

domain_xml=$(</dev/stdin)
operation="$2"

# Operation migrate will:
# 1. Trigger migrate->prepare->start->started operation on the destination host.
# 2. Trigger stopped->release operations on the source host.
if [[ ! $operation =~ ^(started|stopped)$ ]]
then
	exit
fi

guest_uuid=$( sed -En "s/^.*<uuid>([^[:space:]]+)<.*$/\1/p" <<<"$domain_xml" )
ws_server_uuid_flag="--server-uuid $guest_uuid"

ws_open_flag=""
ws_port_flag=""

if [[ $operation == "started" ]]
then
	ws_open_flag="--open"

	# Cannot call $ virsh vncdisplay... because libvirt hooks
	# cannot call anything related to libvirt, i.e., virsh, because
	# a deadlock will happen.
	server_vnc_port=$( sed -En "s/^.*<graphics.*type=['\"]vnc['\"].*port=['\"]([[:digit:]]+)['\"].*$/\1/p" <<<"$domain_xml" )
	ws_port_flag="--server-vnc-port $server_vnc_port"
fi

ws_command_args="$ws_server_uuid_flag $ws_port_flag $ws_open_flag"

log "wscmd_args=$ws_command_args"

anvil-manage-vnc-pipe $ws_command_args &
