#!/usr/bin/bash

TMP=`mktemp salpack.XXXXXXXXXX`
trap "rm -rf $TMP; exit" INT TERM EXIT

. `dirname $0`/salpack-functions

reconfigure_nrpe() {
  DOMAIN=`hostname -d`
  if [ "$1" ]; then
    STATS=`host $1 | grep 'has address' | cut -d" " -f4`
  else
    STATS=`host stats.$DOMAIN | grep 'has address' | cut -d" " -f4`
  fi
  get_text "Enter stats server IP address:" "$STATS"
  STATS="$RET"
  if [[ ! "$STATS" =~ ^[0-9.]*$ ]]; then
    STATS=`host $STATS | grep 'has address' | cut -d" " -f4`
  fi
  if grep -q "^# configured by salpack" /etc/nagios/nrpe.cfg; then
    echo "NRPE already configured."
    return
  fi
  if [ "$STATS" ]; then
    sed -i \
      -e "s/^allowed_hosts=.*/allowed_hosts=$STATS/" \
      -e 's/^\(command.check_hda1.=\)/#\1/' \
      -e 's/^\(command.check_zombie_procs.=\)/#\1/' \
      -e 's/^\(command.check_total_procs.=\)/#\1/' \
      -e 's/\(check_load .*\) \.15,\.10,\.05 \(-c\) \.30,\.25,\.20/\1 15,10,5 \2 30,25,20/' \
      /etc/nagios/nrpe.cfg
    if [ -d /usr/lib64 ]; then
      LIBDIR=/usr/lib64
    else
      LIBDIR=/usr/lib
    fi
    service nrpe restart
    chkconfig nrpe on
  fi
}

reconfigure_nrpe "$@"
