#!/bin/bash

# XML escape in string metrics. Gmond handles this for its own metrics, we must do it ourself
xml_escape() {
    local input="$1"
    input="${input//&/\&amp;}"
    input="${input//</\&lt;}"
    input="${input//>/\&gt;}"
    input="${input//\"/\&quot;}"
    input="${input//\'/\&apos;}"
    echo "$input"
}

# Read all the IPMI hardware sensors
/usr/sbin/ipmi-sensors --ignore-not-available --no-header-output |
	sed -Es 's/ *\| */|/g' |
while read line; do
	# Read the line into a split array
	readarray -td '|' linearray < <(echo $line)

	# line looks like:
	# 4    | CPU1 Temp       | Temperature              | 46.00      | C     | 'OK'

	# name of the sensor
	reading_name=${linearray[1]}

	# replace spaces with underscores
	reading_name=${reading_name// /_}

	# fix the tilde on some machines which report ram temperatures in banks
	reading_name=${reading_name//\~/_thru_}
	
	# make it all lowercase
	reading_name=${reading_name,,*}

	# reading units and value
	reading_value=${linearray[3]}
	reading_units=${linearray[4]}

	# If it's an event, report a string not a float
	if [ $reading_value == "N/A" ]; then
		reading_event=${linearray[5]}
		reading_event=${reading_event//$'\n'/}
		reading_event=${reading_event//"' '"/, }
		reading_event=${reading_event//"'"/}
		gmetric --name="$reading_name" --value="$(xml_escape "$reading_event")" --type=string --group=physical
	else
		gmetric --name="$reading_name" --value="$reading_value" --units=$reading_units --type=float --group=physical
	fi
	
	# echo "$reading_name $reading_value $reading_units"
done




