#!/bin/bash
# Nagios plugin to do a Novell eDirectory time check
# Written by Jesse Pretorius, jesse.pretorius@gmail.com
# Version 1.1, 18 July 2011
# Project location: www.monitoringexchange.org
#
# Changelog:
#   v1.1 : Added specific critical and unknown errors thanks to input from Magnus Felix

errorlvl=0
tmpfile=`mktemp`
output=""

# Run the ndsrepair command and save the output to a temporary file
if [ -e /opt/novell/eDirectory/bin/ndsrepair ]; then
  NDSREPAIR="/opt/novell/eDirectory/bin/ndsrepair"
elif [ -e /usr/bin/ndsrepair ]; then
  NDSREPAIR="/usr/bin/ndsrepair"
else
  NDSREPAIR=`which ndsrepair`
fi
$NDSREPAIR -T > $tmpfile 2>&1
ndsrepairerrorlvl="$?"

# If the command produces an error, return the error
if [ "$ndsrepairerrorlvl" -eq "5" ]; then
  output="CRITICAL: Unable to connect to eDirectory!"
  errorlvl=2
elif [ "$ndsrepairerrorlvl" -eq "8" ]; then
  output="UNKNOWN: The ndsrepair module is already loaded."
  errorlvl=3
elif [ "$ndsrepairerrorlvl" -eq "9" ]; then
  output="CRITICAL: eDirectory is in a DEFUNCT state!"
  errorlvl=2
elif [ "$ndsrepairerrorlvl" -eq "127" ]; then
  output="UNKNOWN: The ndsrepair binary could not be found."
  errorlvl=3
elif [ "$ndsrepairerrorlvl" -gt "0" ]; then
  output="UNKNOWN: Failed to run ndsrepair successfully! `cat $tmpfile`"
  errorlvl=3
else
  # Extract the details from the output in the temporary file
  time_not_in_sync=`grep " No " $tmpfile | wc -l`
  other_errors=`grep "ERROR" $tmpfile | wc -l`

  if [ "$time_not_in_sync" -gt 0 ]; then
    time_not_in_sync_servers=`grep " No " $tmpfile | cut -d"." -f2 | sed -e :a -e '$!N;s/\n/,/;ta'`
    output="$output CRITICAL: The following servers do not have time in sync: $time_not_in_sync_servers."
    errorlvl=2
  else
    output="$output OK: All reachable servers have time in sync."
  fi

  if [ "$other_errors" -gt 0 ]; then
    other_errors_servers=`grep -B 1 "ERROR" /tmp/time.output | grep -v "ERROR" | grep -v "\-\-" | cut -d"." -f2 | sed -e :a -e '$!N;s/\n/,/;ta'`
    output="$output WARNING: The following servers are not contactable: $other_errors_servers."
  else
    output="$output OK: All servers were contacted."
  fi

fi

# Clean up the temp file, output the result and the error level
rm -f $tmpfile
echo $output
exit $errorlvl
