#!/bin/bash

while read line; do
	# Check if this is a new batch of sensors and get the name to set a prefix
	if [[ $(grep -Po '^\S+$' <<< "$line") ]]; then
		OLDIFS=$IFS
		IFS='-'
		read -a splitline <<< "$line"
		IFS=$OLDIFS
		
		# Make a prefix for duplicate sensors
		case ${splitline[0]} in
			nvme)
				prefix=${splitline[0]}_${splitline[2]}_
			;;
			
			jc42)
				prefix=${splitline[0]}_${splitline[3]}_
			;;
			
			acpitz)
				prefix=${splitline[0]}_
			;;
			
			*)
				prefix=""
			;;
		esac 
	fi
	
	# Process the sensor readings
	reading_name=$(grep -Po '^.*?(?=:)' <<< "$line")
	reading_val=$(grep -Po ':\s*\+?\K-?[0-9.]+' <<< "$line")
	reading_units=$(grep -Po ':\s*\+?-?[0-9.]+\s?\K[^0-9. ]+' <<< "$line")
	
	# Make reading name lowercase and convert spaces to underscore
	reading_name=${reading_name,,*}
	reading_name=${reading_name// /_}
	# Fixes for weird characters
	reading_name=${reading_name//+/}
	reading_name=${reading_name//-/minus}
	# Remove some extra unit markings from the name
	# Zenpower
	reading_name=${reading_name//_p_/_}
	reading_name=${reading_name//_c_/_}
	# Others
	reading_name=${reading_name//_temp/}
	reading_name=${reading_name//temp1/1}
	reading_name=${reading_name//temp2/2}
	reading_name=${reading_name//temp3/3} # Just in case
	
	# Ganglia does not like the degrees symbol
	reading_units=${reading_units//°/}
	
	# Suffix a description of the type of reading
	case $reading_units in
		V | mV)
			suffix="_voltage"
		;;
		
		RPM)
			suffix="_speed"
		;;
		
		C)
			suffix="_temp"
		;;
		
		A)
			suffix="_current"
		;;
		
		W)
			suffix="_power"
		;;
		
		GHz)
			suffix="_freq"
		;;
		
		*)
			suffix=""
		;;
	esac
	
	# Ignore some unset/unconnected values
	if [[ "$reading_val" ]]; then
		case $reading_val in
			-40.0 | 0.0 | 0.00 | 0 | 127.0)
			;;
			
			*)
				# Log the reading
				if [[ "$1" == "debug" ]]; then
					echo $prefix$reading_name$suffix = $reading_val : $reading_units
				else
					gmetric --name="$prefix$reading_name$suffix" --value="$reading_val" --units="$reading_units" --type=float --group=sensors
				fi
					
			;;
		esac
	fi
done <<<$(sensors;/usr/local/bin/zen-rapl)
