#!/bin/bash

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

get_text() {
  # input returned in $RET variable
  whiptail --title salpack --inputbox "$1" 8 70 "$2" 2> $TMP
  RET=`cat $TMP`
}

get_yes_no() {
  whiptail --title salpack --yesno "$1" 8 70
}

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 grep -q "^# configured by salpack" /etc/nagios/nrpe.cfg; then
    echo "NRPE already configured."
    return
  fi
  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/' \
    /etc/nagios/nrpe.cfg
  if [ -d /usr/lib64 ]; then
    LIBDIR=/usr/lib64
  else
    LIBDIR=/usr/lib
  fi
  service nrpe restart
  chkconfig nrpe on
}

reconfigure_nrpe "$@"
