#!/bin/bash


message=""
okay_info=""
exit_code=0


NEWLINE="
"
ORG_IFS="$IFS"

if [ ! -x "$(which ipmimonitoring)" ]; then
  echo "Command 'ipmimonitoring' not found or not executable"
  exit 3
fi

ipmi_output="$(ipmimonitoring --no-header-output \
                              --comma-separated-output \
                              --quiet-readings \
                              --output-sensor-state \
                              --ignore-unrecognized-events \
                              --ignore-not-available-sensors \
              )"
if [ $? -ne 0 ] || \
   [ -z "$ipmi_output" ]; then
  echo "Command 'ipmimonitoring' failed to produce usable output"
  exit 3
fi

IFS="$NEWLINE"
for line in $ipmi_output
do
  sensor_name="$(echo $line |cut -d ',' -f 2)"
  #sensor_type="$(echo $line |cut -d ',' -f 3)"
  sensor_state="$(echo $line |cut -d ',' -f 4)"
  sensor_message="$(echo $line |cut -d ',' -f 5)"

  case "$sensor_state" in
    "Nominal")
      okay_info="$okay_info | $sensor_name: $sensor_message"
      continue;
    ;;

    "N/A")
      continue;
    ;;

    "Critical")
      exit_code=2
    ;;

    *)
      if [ $exit_code -lt 1 ]; then
        exit_code=1
      fi
    ;;
  esac

  message="$message | $sensor_name: $sensor_state ($sensor_message)"
done


message="$(echo $message | sed -r 's/^ \| //')"

if [ $exit_code -eq 0 ]; then
  echo "OK: No problems detected ($(echo $okay_info | sed -r 's/^ \| //'))"
  exit 0
fi

if [ "$message" = "" ]; then
  echo "Check in unknown state"
  exit 3
fi

echo $message
exit $exit_code
