#!/bin/bash

GREP="/bin/grep"
SED="/bin/sed"
TAIL="/usr/bin/tail"
SSH="/usr/bin/ssh"
BASENAME="/usr/bin/basename"

# script name must be like  esx_cpu_machine.domain  or  esx_mem_machine.domain
temp="$(basename $0 | $SED 's/^esx_//g')"
which_info="${temp%%_*}"
HOST="${temp##*_}"

case "$which_info" in
	"cpu" | "mem" | "hmem" | "gmem" ) ;;
	* ) echo "Script name incorrect, should be  esx_xxx_hostname   where xxx in {cpu,mem,hmem,gmem}"
		exit 1;;
esac

# ---------------

function get_infos () {
	summary="$($SSH "$HOST" \
	       	vim-cmd hostsvc/hostsummary \; \
		vim-cmd vmsvc/getallvms)"
}

function get_vmlist () {
	total_linenumber="$(echo "$summary" | wc -l)"

	vmlist_linenumber="$(echo "$summary" | $GREP -n "^Vmid")"
	vmlist_linenumber="${vmlist_linenumber/:*/}"

	vmlist="$(echo "$summary" | $TAIL -n $(($total_linenumber - $vmlist_linenumber)) | tr -s " ")"
}

function overallCpuUsage () {
	cpu="$(echo "$1" | $GREP "overallCpuUsage")"
	cpu="${cpu/*overallCpuUsage = /}"
	cpu="${cpu/,*/}"
}

function overallMemoryUsage () {
	mem="$(echo "$1" | $GREP "overallMemoryUsage")"
	mem="${mem/*overallMemoryUsage = /}"
	mem="${mem/,*/}"
}

# ---------------

function get_vmsvcsummaries () {
	n=0
	cmd=""
#	echo "$vmlist" | \
	while read vmline ; do
		id[$n]="${vmline%% *}"
		temp="${vmline#${id[$n]} }"
		name[$n]="${temp%% *}"
		cmd="$cmd""vim-cmd vmsvc/get.summary ${id[$n]} \\\; "
		(( n++ ))
	done <<EOF
$vmlist
EOF

	vmsummaries="$($SSH "$HOST" $cmd)"
}

# ---------------

function VMoverallCpuUsage () {
	cpulist="$(echo "$1" | $GREP "overallCpuUsage")"
	n=0
	while read c ; do
		temp="${c/*overallCpuUsage = /}"
		vmcpu[$n]="${temp/,*/}"
		if [ "${vmcpu[$n]}" == "<unset>" ]; then
			vmcpu[$n]="0"
		fi
		(( n++ ))
	done <<EOF
$cpulist
EOF
}

function VMoverallGuestMemUsage () {
	memlist="$(echo "$1" | $GREP "guestMemoryUsage")"
	n=0
	while read m ; do
		temp="${m/*guestMemoryUsage = /}"
		vmmem[$n]="${temp/,*/}"
		if [ "${vmmem[$n]}" == "<unset>" ]; then
			vmmem[$n]="0"
		fi
		(( n++ ))
	done <<EOF
$memlist
EOF
}

function VMoverallHostMemUsage () {
	memlist="$(echo "$1" | $GREP "hostMemoryUsage")"
	n=0
	while read m ; do
		temp="${m/*hostMemoryUsage = /}"
		vmmem[$n]="${temp/,*/}"
		if [ "${vmmem[$n]}" == "<unset>" ]; then
			vmmem[$n]="0"
		fi
		(( n++ ))
	done <<EOF
$memlist
EOF
}


# ---------------

if [ "$1" = "autoconf" ]; then
       	get_infos
	if [ -n "$summary" ]; then
                echo yes
        else
		echo "no (cannot connect to ESX server $HOST)"
        fi
	exit 0
fi

if [ "$1" = "config" ]; then
	get_infos
	if [ -z "$summary" ]; then
		echo "Cannot connect to ESX server $HOST"
		exit 1
	fi

	case "$which_info" in
		"cpu" )
			echo 'graph_title ESXi Domain CPU Usage'
			echo 'graph_args -l 0'
			echo 'graph_scale no'
			echo 'graph_vlabel CPU usage in MHz'
			echo 'graph_category virtualization'
			echo 'graph_info This graph shows the average CPU MHz used by each domain'

			name="Domain_0"
			echo "$name.label $name"
			echo "$name.type GAUGE"
			echo "$name.draw AREA"
			echo "$name.min 0"
			echo "$name.info CPU MHz used by $name"


			get_vmlist
			if [ -n "$vmlist" ]; then
				n=0
				cmd=""
				while read vmline ; do
					id="${vmline%% *}"
					temp="${vmline#$id }"
					name="${temp%% *}"

					name=`echo $name | sed -e"s/[-\.]/_/g"`
					echo "$name.label $name"
					echo "$name.type GAUGE"
					echo "$name.draw STACK"
					echo "$name.min 0"
					echo "$name.info CPU MHz used by $name"

					(( n++ ))
				done <<EOF
$vmlist
EOF
			fi;;
		"mem" | "hmem" | "gmem" )
			echo 'graph_title ESXi Domain '"$which_info"' Usage'
			echo 'graph_args -l 0'
			echo 'graph_scale no'
			echo 'graph_vlabel Memory usage in Megabytes'
			echo 'graph_category virtualization'
			echo 'graph_info This graph shows the average Memory used by each domain'

			name="Domain_0"
			echo "$name.label $name"
			echo "$name.type GAUGE"
			echo "$name.draw AREA"
			echo "$name.min 0"
			echo "$name.info Memory usage for $name"


			get_vmlist
			if [ -n "$vmlist" ]; then
				n=0
				cmd=""
				while read vmline ; do
					id="${vmline%% *}"
					temp="${vmline#$id }"
					name="${temp%% *}"

					name=`echo $name | sed -e"s/[-\.]/_/g"`
					echo "$name.label $name"
					echo "$name.type GAUGE"
					echo "$name.draw STACK"
					echo "$name.min 0"
					echo "$name.info Memory usage for $name"

					(( n++ ))
				done <<EOF
$vmlist
EOF
			fi;;

	esac

        exit 0
fi

# ---------------
# Get the informations

get_infos
if [ -z "$summary" ]; then
	echo "Cannot connect to ESX server $HOST"
	exit 1
fi

case $which_info in
	"cpu" ) overallCpuUsage "$summary" ;;
	"mem" | "hmem" | "gmem" ) overallMemoryUsage "$summary" ;;
esac


get_vmlist
if [ -n "$vmlist" ]; then

	get_vmsvcsummaries

	case $which_info in
		"cpu" ) VMoverallCpuUsage "$vmsummaries";;
		"mem" |	"hmem" ) VMoverallHostMemUsage "$vmsummaries";;
		"gmem" ) VMoverallGuestMemUsage "$vmsummaries";;
	esac
fi


# ---------------
# Print information Munin style
case $which_info in
	"cpu" ) echo "Domain_0.value ""$cpu";;
	"mem" | "gmem" | "hmem" ) echo "Domain_0.value ""$(($mem))";;
esac


if [ -n "$vmlist" ]; then
	n=0
	while [ -n "${id[$n]}" ]; do
		#echo ${id[$n]} ${name[$n]}  ${vmcpu[$n]} ${vmmem[$n]}
		nicename=`echo ${name[$n]} | sed 's/[^a-z|A-Z|0-9]/\_/g'`
		case $which_info in
			"cpu" ) echo "$nicename".value "${vmcpu[$n]}";;
			"mem" | "gmem" | "hmem" ) echo "$nicename".value "$((${vmmem[$n]}))";;
		esac
		(( n++ ))
	done
fi
