#!/bin/sh
# Script ----------------------------------------------------------------------
# $Id: gsx-ipmi.sh,v 1.1 2009/08/09 23:08:14 jayrfink Exp $
# 
# gsx-ipmi - An ipmilike shell wrapper for vmware-vim-cmd vmsvc/power.*
#------------------------------------------------------------------------------

HOSTSFILE=./gsxhosts.example
GSXPOWER=" vmware-vim-cmd  vmsvc/power." # We just tack on the oper

#-----------------------------------------------------------------------------
# usage - Usage message
#-----------------------------------------------------------------------------
usage()
{
    if [ -n "$*" ]; then
        echo " "
        echo "${PROG}: $*"
    fi
    cat <<_usage_
${PROG} [host][oper cmd]|[-u]
${PROG} [host][power getstate|hibernate|off|on|reboot|shutdown|suspend]|[-u]
Commands:
  getstate    Display the current power state of the guest
  hibernate   Place the guest power into hibernate mode (OS must support)
  off         Power off the guest
  on          Power on and boot up the guest
  reboot      Normal reboot of the guest
  reset       Power reset (cold) the guest
  shutdown    Normal shutdown of the guest
  suspend     Place the guest into suspended mode
Notes:
 The user must have appropiate privileges to perform power operations on 
guests.
_usage_
}

error_exit()
{
	message=$1
	exit_code=$2

	echo $message
	usage
	exit $exit_code
}

# Input parsing - the usage explains what each one does
if [ $# -gt 0 -a "$1" = "-u" ];then
    usage
    exit 0
fi

guest=$1
oper=$2
subcmd=$3

if [ ! $guest ]; then
	echo "Error: No guest specified"
	usage
	exit 1
fi

[ ! $guest ] && error_exit "No guest specified" 1
[ ! $oper ] && error_exit "No operation specified" 1
[ ! $subcmd ] && error_exit "No subcommand specified" 1

vmid=`grep $guest $HOSTSFILE|awk '{print $2}'`

[ ! $vmid ] && error_exit "${guest} did not match anything in $HOSTSFILE" 2

case $oper in 
	power)
		$GSXPOWER$subcmd $vmid 2>/dev/null
		if [ $? -gt 0 ]; then
			error_exit "$subcmd failed" 1
		fi
		;;
	*)
		error_exit "Invalid operation" 2
		;;
esac
		
exit 0

