#!/bin/sh
#
# Nagios plugin to check the mismatch count of all configured software raid(s)
# written by Gerd Koenig <geko@deb.ymc.ch>
# and Daniel Beyer <dabe@deb.ymc.ch>
#
# Description:
#
# This plugin will return information about the
# mismatch count of any existing software raid

message=""
exit_code=3
sw_raid_found=0
mismatch_detected=0
empty_output=0

for file_path in $(find /sys/block/*/md/* -mindepth 0 -maxdepth 0 -type f -path "/sys/block/*/md/mismatch_cnt" 2>/dev/null)
do
  sw_raid_found=1
  raid_device=$(echo $file_path | cut -d '/' -f 4)
  mismatch_count=$(cat $file_path 2>/dev/null | sed -r 's/[^0-9]//g')
  if [ -n "$mismatch_count" ]; then
    if [ $mismatch_count -gt 0 ]; then
      mismatch_detected=1
      message="$message""Raid device '$raid_device' reports mismatch count of $mismatch_count. "
    fi
  else
    empty_output=1
    message="$message""File '$file_path' contains invalid or no content. "
  fi
done

if [ $sw_raid_found -eq 0 ]; then
  message="OK, no sw-raid to check."
  exit_code=0
else
  if [ $empty_output -eq 1 ]; then
    exit_code=2
  elif [ $mismatch_detected -eq 1 ]; then
    exit_code=1
  elif [ $mismatch_detected -eq 0 ] &&\
       [ $empty_output -eq 0 ]; then
    message="OK"
    exit_code=0
  else
    message="Can not determine status"
  fi
fi

echo $message
exit $exit_code