#!/usr/bin/bash

NAGIOS_STATUS_FILE=${NAGIOS_STATUS_FILE:-/var/spool/nagios/status.dat}
MODE=${MODE:-hostservice}
FILTER_HOST=$1
FILTER_SVC=$2

if [[ $MODE == hostservice ]]; then
  HEADERS=${HEADERS:-"host_name,service_description,current_state"}
elif [[ $MODE == servicestatus ]]; then
  HEADERS=${HEADERS:-"host_name,service_description,current_state"}
elif [[ $MODE == hoststatus ]]; then
  HEADERS=${HEADERS:-"host_name,current_state"}
elif [[ $MODE == full ]]; then
  MODE=hostservice
  HEADERS=${HEADERS:-"host_name,service_description,current_state,plugin_output"}
fi


AWK_OPTS=(
  -v MODE=$MODE
  -v HEADERS="$HEADERS"
  -v FHST="$FILTER_HOST"
  -v FSVC="$FILTER_SVC"
)

awk "${AWK_OPTS[@]}" '
BEGIN {
  split(HEADERS, headers, ",");
  for (ih in headers) {
    DUMP[headers[ih]] = 1;
  }
  REWRITE["hoststatus","current_state",0] = "OK";
  REWRITE["hoststatus","current_state",1] = "DOWN";
  REWRITE["hoststatus","current_state",2] = "UNREACHABLE";
  REWRITE["servicestatus","current_state",0] = "OK";
  REWRITE["servicestatus","current_state",1] = "WARNING";
  REWRITE["servicestatus","current_state",2] = "CRITICAL";
  REWRITE["servicestatus","current_state",3] = "UNKNOWN";

  EXIT_CODE = 1;
}
{
  if ($2 == "{") {
    section = ""; hname = ""; sname = "";
    if ($1 == MODE)
      section = $1;
    else if (MODE == "hostservice" && $1 == "hoststatus")
      section = $1;
    else if (MODE == "hostservice" && $1 == "servicestatus")
      section = $1;
    next;
  }
  else if ($1 == "}") {
    printf("\n");
    next;
  }
  else if (section == "") {
    next;
  }
  else if (substr($0, 1, 1) != "\t") {
    next;
  }

  var = substr($1, 1, index($1, "=") - 1);
  val = substr($0, index($0, "=") + 1);

  if (var == "host_name") {
    hname = val;
    if (FHST && FHST != hname) { section = ""; next; }
    if (section == "hoststatus") {
      if (FSVC && FSVC != "_HOST_") { section = ""; next; }
      printf("\t%s\t%s", hname, "_HOST_");
      EXIT_CODE = 0;
      next;
    }
    if (section == "servicestatus") { next; }
  }
  if (var == "service_description") {
    sname = val;
    if (FSVC && FSVC != sname) { section = ""; next; }
    if (section == "servicestatus") {
      printf("\t%s\t%s", hname, sname);
      EXIT_CODE = 0;
      next;
    }
  }
  if (DUMP[var]) {
    if (REWRITE[section,var,val])
      printf("\t%s", REWRITE[section,var,val]);
    else
      printf("\t%s", val);
  }
}

END {
  exit(EXIT_CODE);
}
' < $NAGIOS_STATUS_FILE | sort -k 1 -k 2 -k 3 | column -t -s $'\t' | cut -c3-

if [[ ${PIPESTATUS[0]} != 0 ]]; then
  exit 1
fi

exit 0
