#!/bin/sh
#
# Nagios plugin to check if required service ip(s) are up
# written by Gerd Koenig <geko@deb.ymc.ch>
#
# Description:
#
# This plugin will return information about the
# availability of required service ip(s)

haRes="/etc/heartbeat/haresources"
message="initial error"
exitCode=2

### check if I am an active server
if [ -x "/usr/sbin/fliwi-simple-heartbeat-info" ]; then
  isPrimary=$(/usr/sbin/fliwi-simple-heartbeat-info | grep -c "Status: ACTIVE")
else
  echo "Ok. heartbeat functionality not required/available"
  exit 0
fi
### check for heartbeat resources file
if [ ! -r $haRes ]; then
  echo "ERROR: $haRes not readable"
  exit 2
fi

if [ $isPrimary -eq 1 ]; then
  ### detect the IP(s) which should be up on this active node
  requiredIps=$(cat $haRes | grep 'fliwiIpTakeover' |  tr " " "\n" | grep 'fliwiIpTakeover' | awk -F '::' '{print $2}')
  for requiredIp in $(echo $requiredIps | tr " " "\n"); do
    ### test if the requiredIp is up on this node
    ipFound=$(ip a | grep -c "inet $requiredIp")
    if [ $ipFound -eq 0 ]; then
      if [ -n $ipDown ]; then
        ipDown="$requiredIp"
      else
        ipDown=", $requiredIp"
      fi
    fi
  done
  ### set output message and exit status
  if [ -n $ipDown ]; then
    message="Ok"
    exitCode=0
  else
    message="Error: $ipDown missing"
    exitCode=2
  fi
else
  message="Ok, I am a PASSIV server"
  exitCode=0
fi

### return the status
echo $message
exit $exitCode
