#!/bin/sh

USAGE="Usage: $(basename $0) on | off"
VMNAME="b2007cel-v"
VMDIR="/VM/${VMNAME}"

MONDIR="${VMDIR}/${VMNAME}.vmdk.lck"
VMX="${VMDIR}/${VMNAME}.vmx"
RUNNING="${VMDIR}/RUNNING"
STARTING="${VMDIR}/STARTING"
ONLINE="${VMDIR}/ONLINE"
FQDN="$(hostname)v.os22.ru"

die() {
	echo $@
	exit 1
}

[ $# -eq 0 ] && die "${USAGE}"

case $1 in
	on)
		if [ -d "${MONDIR}" ]; then
			if ! vmrun list | grep "${VMNAME}" 2>&1; then
				echo "Warning: lockdir present but VM \"${VMNAME}\" is not running!"
				[ -f "${RUNNING}" ] && rm "${RUNNING}"
				[ -f "${ONLINE}" ] && rm "${ONLINE}"
				systemctl restart windows-vm
			fi
			_msg=""
			_msg1=""
			_msg2=""
			if [ ! -f "${RUNNING}" ]; then
				touch "${RUNNING}"
				_msg1="VM ${FQDN} on $(hostname) starts running"
			fi
			if ping -c 1 "${FQDN}" > /dev/null 2>&1; then
				if [ ! -f "${ONLINE}" ]; then
					touch "${ONLINE}"
					_msg2="becomes online"
				fi
			else
				[ -f "${ONLINE}" ] && rm "${ONLINE}"
			fi
			if [ "x${_msg1}" = "x" ]; then
				[ "x${_msg2}" = "x" ] || _msg="VM ${FQDN} on $(hostname) ${_msg2}"
			else
				[ "x${_msg2}" = "x" ] && _msg2="still offline"
				_msg="${_msg1} and ${_msg2}"
			fi
			[ "x${_msg}" = "x" ] || echo "${_msg}" | mail -s `hostname` root
		else
			[ -f "${RUNNING}" ] && rm "${RUNNING}"
			[ -f "${ONLINE}" ] && rm "${ONLINE}"
			systemctl restart windows-vm
		fi
		;;
	off)
		if [ -d "${MONDIR}" ]; then
			vmrun stop "${VMX}" soft
			if [ -d "${MONDIR}" ]; then
				echo "Unable to power off VM on $(hostname) via ACPI, forcing off!" | mail -s `hostname` root
				# Force power off 
				vmrun stop "${VMX}"
				rm -rf "${MONDIR}"
				while [ -d "${MONDIR}" ]; do
					echo "Still trying to remove ${MONDIR}..."
					rm -rf "${MONDIR}"
					sleep 1
				done
			fi
		fi
		[ -f "${RUNNING}" ] && rm "${RUNNING}"
		[ -f "${ONLINE}" ] && rm "${ONLINE}"
		;;
	*)
		die "${USAGE}"
esac
