#!/bin/sh
#

NRPE_CONFIG_DIR="/etc/nagios/nrpe.d"
NRPE_ALLOWED_HOSTS_CONFIG_FILE="fliwi-nrpe-allowed-hosts-autoconf.cfg"
FLIWI_MONITORING_SERVICE="monitoring"
NRPE_SERVER_INIT_SCRIPT="/etc/init.d/nagios-nrpe-server"
exit_code=0

lockFile="/tmp/fliwi_Check_MonitoringHosts.lock"

### Do not run if an other one is running
if [ -e $lockFile ]; then
  exit 0
fi

### generate lock
/bin/date +%s > $lockFile

test -d $NRPE_CONFIG_DIR || exit 0

test -x $NRPE_SERVER_INIT_SCRIPT || exit 0

### check if monitoring hosts has changed, and replace them, if needed
monitoring_hostnames=$(/usr/bin/fliwi-get-services --as-hostnames $FLIWI_MONITORING_SERVICE)
if [ $? -ne 0 ] || [ "$monitoring_hostnames" = "" ]; then
  exit_code=1
else
  temp_monitoring_hosts_oneline=$(echo $monitoring_hostnames | sed -r 's/[ ]+/,/g')
  if [ $? -ne 0 ] || [ "$temp_monitoring_hosts_oneline" = "" ]; then
      exit_code=1
  fi
  checkString="allowed_hosts="$temp_monitoring_hosts_oneline
  ret=$(/bin/grep -c ^$checkString$ $NRPE_CONFIG_DIR/$NRPE_ALLOWED_HOSTS_CONFIG_FILE)
  if [ $ret -ne 1 ]; then
    /usr/bin/logger -p syslog.alert -t MonitoringServerCheck "monitoring host(s) has changed, reconfiguring..."
    $(/bin/sed -i '/^allowed_hosts\=/s/^.*$/allowed_hosts\='$temp_monitoring_hosts_oneline'/' $NRPE_CONFIG_DIR/$NRPE_ALLOWED_HOSTS_CONFIG_FILE)
    /usr/bin/logger -p syslog.alert -t MonitoringServerCheck "and restarting nagios-nrpe-server"
    $NRPE_SERVER_INIT_SCRIPT restart || true
  fi
fi

### unlock
/bin/rm -f $lockFile

exit $exit_code

