#!/usr/bin/bash

/opt/MegaRAID/storcli/storcli64 /c0 show all | awk '
BEGIN {
  warn = 0
  crit = 0
  ok = 0
  msg = ""
}
/^-----/ {
  if (row==0) {
    row = 1
    state_col = 0
  }
}
/^$/ {
  row = 0
}
/^=====/ {
  section = last_row
}
row>0 {
  if (row==2) {
    if ($1=="Policy" || $1=="Predictive") {
      # ignore policy table
      row = -1
    } else {
      col_names = $0
      coln = split($0, col)
      for (c=0; c<coln; c++) {
        if (col[c]=="State") state_col = c
      }
    }
  } else if (row>3) {
    split($0, ss)
    current_state = ss[state_col]
    if (current_state=="Unknown") {
      msg = (msg col_names "\n" $0 "\n")
      last_state = section " " current_state
      warn += 1
    } else if (current_state=="" || current_state=="Onln" || current_state=="Optl" || current_state=="Optimal") {
      ok += 1
    } else {
      msg = (msg col_names "\n" $0 "\n")
      last_state = section " " current_state
      crit += 1
    }
  }
  row++
}
{
  last_row = $0
}
END {
  if (ok==0) {
    print "CRITICAL - no controller found"
    exit 2
  } else if (crit>0) {
    printf "CRITICAL - %s state\n%s", last_state, msg
    exit 2
  } else if (warn>0) {
    printf "WARNING - %s state\n%s", last_state, msg
    exit 1
  } else {
    printf "OK\n%s", msg
    exit 0
  }
}
'
