#!/bin/sh

. /opt/etc/globals

statusfile=/tmp/`$basename $0`.pwrstatus
lockfile=/tmp/`$basename $0`.lock

if [ -f $lockfile ]; then
	echo "$0: recursive call!" >> $logfile
	exit
fi

$touch $lockfile

$apcaccess status $powerhost > $statusfile

if [ $? -gt 0 ]; then
	echo "Error getting power status, is $apcaccess running on $powerhost ?"
	$rm $lockfile
	exit;
fi

maxtime=`$cat $statusfile | $grep MAXTIME | $awk '{print $3}'`
tonbatt=`$cat $statusfile | $grep TONBATT | $awk '{print $3}'`
shuttime=$(($maxtime / 2))

if [ $tonbatt -gt 0 ]; then
	$rm -f $powerflag > /dev/null 2>&1
	if [ $tonbatt -gt $shuttime ]; then
		# It is Ok to call this script with no VMs running, so
		# don't bother cheching if we already were here before
		/opt/etc/vmmon/stopvms
	fi
else
	# Power good, set flag for VM monitoring script
	$touch $powerflag
fi

$rm $lockfile
