#!/bin/sh
# Check_MK agent plugin: /usr/lib/check_mk_agent/plugins/rack_monitor
#
# Sends one section per reading: the value, then the number of seconds since
# its data file was last updated, so the server can spot stale data:
#
#     <<<room_temp>>>
#     24.3 5          <- value, then seconds since the data file was updated
#
# A missing or empty data file is reported as a single "-".

RACK_DATA_DIR=/run/rack-monitor
ENERGENIE_SENSOR_ID=0x354
[ -r /etc/rack-monitor/rack-monitor.conf ] && . /etc/rack-monitor/rack-monitor.conf

emit_section() {
    section=$1
    file=$2
    value=$3
    echo "<<<$section>>>"
    if [ -n "$value" ]; then
        age=$(( $(date +%s) - $(stat -c %Y "$file") ))
        echo "$value $age"
    else
        echo "-"
    fi
}

TEMP_FILE="$RACK_DATA_DIR/temperature"
HUMIDITY_FILE="$RACK_DATA_DIR/humidity"
POWER_FILE="$RACK_DATA_DIR/energenie_$ENERGENIE_SENSOR_ID"

emit_section room_temp     "$TEMP_FILE"     "$(head -n 1 "$TEMP_FILE" 2>/dev/null)"
emit_section room_humidity "$HUMIDITY_FILE" "$(head -n 1 "$HUMIDITY_FILE" 2>/dev/null)"
emit_section power_usage   "$POWER_FILE"    "$(awk '$1=="REAL_POWER"{print $2; exit}' "$POWER_FILE" 2>/dev/null)"
