#!/bin/bash

# plugin to monitor OSPF process, neighbord and route(s)
# made by Dju
# version 1.2 / 09/2015

PROGNAME=`basename $0`
PROGPATH=`echo $0 | sed -e 's,[\\/][^\\/][^\\/]*$,,'`

. $PROGPATH/utils.sh

# optional: route(s) to check, separate with space if more than 1
CHECK_ROUTES="0.0.0.0/0"
# optional: minimal neighbors  to find
CHECK_NEIGHBORS_NB=2

VTYSH=$(which vtysh)
if [ -z "$VTYSH" ]; then
  VTYSH=/usr/bin/vtysh
fi
if [ ! -x $VTYSH ]; then
  echo "UNKNOWN: vtysh not available"
  exit $STATE_UNKNOWN
fi

SUDO=""
MYID=$(id -u)
if [ "$MYID" != "0" ]; then SUDO=sudo; fi

STATE=OK

intf=$($SUDO $VTYSH -c 'show ip ospf interface')
intf_ospf=$(echo "$intf" | grep -c 'Router ID ')
if [ $intf_ospf -lt 1 ]; then
  STATE=CRITICAL
  LEGEND="no ospf enabled interface found"
else
  neighbor=$(echo "$intf" | grep "Neighbor Count is ")
  if [ -n "$neighbor" ]; then
    nb_neighbors=$(echo "$neighbor" | awk '{print $4}' | sed 's/,//' | awk '{n+=$1} END {print n}')
  else
    nb_neighbors=0
  fi
  if [ $nb_neighbors -lt 1 ]; then
    STATE=CRITICAL
    LEGEND="no ospf neighbor"
  elif [ -n "$CHECK_NEIGHBORS_NB" -a $CHECK_NEIGHBORS_NB -gt 0 -a $CHECK_NEIGHBORS_NB -gt $nb_neighbors ]; then
    STATE=WARNING
    LEGEND="only $nb_neighbors/$CHECK_NEIGHBORS_NB neighbor(s) found"
  else
    stats="intf=$intf_ospf neighbors=$nb_neighbors"
    if [ -n "$CHECK_ROUTES" ]; then
      routes_ok=0
      routes_nb=0
      routes_ospf=$($SUDO $VTYSH -c 'show ip ospf route')
      for route in $CHECK_ROUTES; do
         routes_nb=$(expr $routes_nb + 1)
         route_regex=$(echo $route | sed 's/\./\\\./')
         route_exists=$(echo "$routes_ospf" | egrep "$route_regex.*\[.*\].*tag")
         if [ -n "$route_exists" ]; then
           routes_ok=$(expr $routes_ok + 1)
         fi
      done
      if [ $routes_ok -lt $routes_nb ]; then
        STATE=WARNING
      else
        STATE=OK
      fi
      stats="$stats routes_ok=$routes_ok"
    else
      STATE=OK
    fi
    LEGEND="$intf_ospf interface(s) with OSPF, $nb_neighbors neighbor(s)"
    if [ -n "$CHECK_ROUTES" ]; then LEGEND="${LEGEND}, $routes_ok/$routes_nb route(s)"; fi
  fi
fi

echo -n "$STATE: $LEGEND"
[ -n "$stats" ] && echo " | $stats"
STATE_EXIT="STATE_${STATE}"
exit ${!STATE_EXIT}
