#!/bin/sh

# usensor
# Copyright (c) 2015 Wavestore Ltd

# prints all sensors in ipmi-style table, including
# - lmsensors (sensors)
# - ipmi (ipmitool sensor)
# - enclosure ses (sg_ses -p ec)

# usage:
# usensor 			# displays all configured sensors
# usensor nolm 		# displays all configured except lm 
# usensor lm 		# only lm 
# usensor ipmi 		# only ipmi
# usensor ses 		# only ses
# usensor sgN 		# only ses sgN where N is a digit

OPT="$1"

lmsensor()
{
#reads sensors from lmsensors, turn into table
sensors | grep "min =\|crit =" | while read L; do
	A=${L%(*}
	T=${A%:*}
	V="${A#*:}"
	if [[ "$V" == *" V"* ]]; then
		V=${V%V*}
		UU="Volts"
	elif [[ "$V" == *"RPM"* ]]; then
		V=${V%RPM*}
		UU="RPM"
	elif [[ "$V" == *"°C"* ]]; then
		V=${V%°C*}
		UU="degrees C"
	else
		V=""
	fi
	if [[ "$L" == *"ALARM"* ]]; then
		S=alarm
	else
		S=ok
	fi
	if [ "$V" ]; then
		printf "%-17s| %-11s| %-11s| %s\n" "$T" ${V/+/} "${UU:-status}" "$S"
	fi
	done
}

ipmisensor()
{
#reads sensors from ipmi, only outputs first 4 columns
ipmitool sensor | cut -d"|" -f1-4 | grep -v "| na\|| 0x8080"
}

sessensor()
{
#reads page ec from enclosure /dev/$EN and turns into ipmi style table
EN=$1
sg_ses -p ec -f /dev/$EN 2>/dev/null | while read A; do
	if [[ "$A" == *"not an enclosure"* ]]; then
		return
	elif [[ "$A" == "Element type"* ]]; then
		T=${A#Element type: }; T=${T:0:4}; N=0; S="Unk"; V=""; UU=""
	elif [[ "$A" == "Element"* ]]; then
		N=${A#Element }; N=${N% *}
	elif [[ "$A" == *"status:"* ]]; then
		S=${A#*status: }
	elif [[ "$A" == *"speed="* ]]; then
		V=${A#*speed=}; V="${V%% *}"; UU="RPM"
	elif [[ "$A" == *"Voltage"* ]]; then
		V=${A#*Voltage: }; V="${V%% *}"; UU="Volts"
	elif  [[ "$A" == *"Temperature"* ]]; then
		V=${A#*Temperature=}; V="${V%% *}"; UU="degrees C"
	fi
	if [ "${S:0:1}" == "U" ]; then
		V=""; UU=""
	elif [ "$V" -o "$T" = "Powe" -o "$T" = "Encl" ]; then
		S=${S/OK/ok}
		T=${T/Cool/Fan}
		T=${T/Powe/Power}
		printf "%-17s| %-11s| %-11s| %s\n" "$EN-$T-$N" "${V:-1}" "${UU:-status}" "$S"
		S="Unk"
	fi
done
}

#special cases (even if not configured)...
if [ "$OPT" == "ipmi" ]; then
	ipmisensor
elif [ "$OPT" == "lm" ]; then
	lmsensor
elif [ "$OPT" == "ses" ]; then
	sg_scan  | while read A B; do
		A=${A%:}
		sessensor ${A#/dev/}
	done
elif [ "${OPT:0:2}" == "sg" ]; then
	sessensor $OPT
else
	#no option or "nolm".... output configured sensors...

	#lmsensors, if enabled
	if [ "$OPT" != "nolm" ] && extract.pl [Sensors | grep -i "LM=y" &>/dev/null; then
		lmsensor
	fi

	#ipmi, if enabled
	if extract.pl [Sensors | grep -i "IPMI=y" &>/dev/null; then
		ipmisensor
	fi

	#enclosures, if any
	if extract.pl [Sensors | grep -i "SES=y" &>/dev/null; then
		sg_scan  | while read A B; do
			A=${A%:}
			sessensor ${A#/dev/}
		done
	fi
fi
