#!/bin/sh
#
### BEGIN INIT INFO
# Provides:          fliwi-monitoring-client-config
# Should-Start:
# Required-Start:    $local_fs networking
# X-Start-Before:    nagios-nrpe-server
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Updates the configuration of nagios-nrpe-server
# Description:       This especially cares about proper entries for the
#                    'allowed_hosts'-setting in the configuration of the
#                    nagios-nrpe-server.
### END INIT INFO
set -e

PATH=/sbin:/bin:/usr/sbin:/usr/bin
NRPE_CONFIG_DIR="/etc/nagios/nrpe.d"
NRPE_ALLOWED_HOSTS_CONFIG_FILE="fliwi-nrpe-allowed-hosts-autoconf.cfg"
FLIWI_MONITORING_SERVICE="monitoring"

test -d $NRPE_CONFIG_DIR || exit 0

if [ -r /etc/default/locale ]; then
  . /etc/default/locale
  export LANG LANGUAGE
fi

. /lib/lsb/init-functions

case "$1" in
  start)
    exit_code=0
    log_daemon_msg "Adding configuration-updates of nagios-nrpe-server..." "fliwi-monitoring-client-config"


    monitoring_hostnames=$(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

      echo "allowed_hosts=$temp_monitoring_hosts_oneline" > $NRPE_CONFIG_DIR/$NRPE_ALLOWED_HOSTS_CONFIG_FILE || exit_code=1
    fi
    log_end_msg $exit_code
    echo
  ;;

  stop)
    exit_code=0
    log_daemon_msg "Removing configuration-updates of nagios-nrpe-server..." "fliwi-monitoring-client-config"
    if [ -f "$NRPE_CONFIG_DIR/$NRPE_ALLOWED_HOSTS_CONFIG_FILE" ]; then
      rm -f $NRPE_CONFIG_DIR/$NRPE_ALLOWED_HOSTS_CONFIG_FILE || exit_code=1
    fi
    log_end_msg $exit_code
    echo
  ;;

  status)
    exit_code=0
    if [ -f "$NRPE_CONFIG_DIR/$NRPE_ALLOWED_HOSTS_CONFIG_FILE" ]; then
      log_success_msg "fliwi-monitoring-client-config is active"
    else
      exit_code=1
      log_failure_msg "fliwi-monitoring-client-config is inactive"
    fi
    exit $exit_code
  ;;

  restart|force-reload|reload)
    $0 stop
    sleep 1
    $0 start
  ;;

  *)
    echo "Usage: /etc/init.d/fliwi-monitoring-client-config {start|stop|restart|reload|force-reload|status}"
    exit 1
  ;;
esac

exit 0

