#!/bin/bash

CacheDir=/var/cache/nagios3/nrpe
PluginCmd=/usr/lib/nagios/plugins/check_nrpe
RetVal=""; Status=""

while getopts "H:c:" Opt; do
  case ${Opt} in
    H)
      Host=${OPTARG}
      ;;
    c)
      Cmd=${OPTARG}
      ;;
  esac
done

if [ -z "${Host}" -o -z "${Cmd}" ]; then
  echo "Parameters -H hostname -c command expected."
  exit 3
fi

if ping -qnc 3 -w 3 "${Host}" >/dev/null; then
  # Maschine ist online, aktuellen Status besorgen
  RetVal=$(${PluginCmd} "$@")
  Status=$?

  mkdir -p ${CacheDir}/${Host}
  echo "${Status}|${RetVal}" > ${CacheDir}/${Host}/${Cmd}
else
  # Maschine ist offline, Cache verwenden
  if [ ! -r ${CacheDir}/${Host}/${Cmd} ]; then
    echo "Host is offline and can't read cached status."
    exit 3
  fi
  TimeStamp=$(stat --format=%y ${CacheDir}/${Host}/${Cmd})
  TimeStamp=${TimeStamp:0:19}
  read -d "" RetVal < ${CacheDir}/${Host}/${Cmd}
  Status=${RetVal%%|*}
  RetVal=${RetVal#*|}
  RetVal1=${RetVal%%|*}
  RetVal2=${RetVal#*|}
  RetVal="${RetVal1} (cached) [${TimeStamp}]|${RetVal2}"
fi

echo "${RetVal}"
exit ${Status}
