#!/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`
  STATS=`host stats.$DOMAIN | grep 'has address' | cut -d" " -f4`
  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 "s/^allowed_hosts=.*/allowed_hosts=$STATS/" /etc/nagios/nrpe.cfg
  if [ -d /usr/lib64 ]; then
    LIBDIR=/usr/lib64
  else
    LIBDIR=/usr/lib
  fi
  cat << EOF >> /etc/nagios/nrpe.cfg
command[check_disk_root]=$LIBDIR/nagios/plugins/check_disk -w 20% -c 10% -p /
command[check_disk_var]=$LIBDIR/nagios/plugins/check_disk -w 20% -c 10% -p /var
command[check_disk_home]=$LIBDIR/nagios/plugins/check_disk -w 20% -c 10% -p /home
command[check_zombie_procs]=/usr/lib/nagios/plugins/check_procs_perf -w 5 -c 10 -s Z
command[check_total_procs]=/usr/lib/nagios/plugins/check_procs_perf -w 150 -c 200
command[check_mailq]=$LIBDIR/nagios/plugins/check_mailq -w 100 -c 200 -M postfi
command[check_swap]=$LIBDIR/nagios/plugins/check_swap -w 80 -c 50
command[check_eth0]=/usr/lib/nagios/plugins/check_eth eth0 1000 90 95
EOF
  service nrpe restart
  chkconfig nrpe on
}

restrict_root() {
  if get_yes_no; then
    grep -q '^Match User root' /etc/ssh/sshd_config \
      || (
           echo "Match User root" >> /etc/ssh/sshd_config
           echo -e "\tPasswordAuthentication no" >> /etc/ssh/sshd_config
         )
    sed -i 's/#\(auth\s*required\s*pam_wheel.so use_uid\)/\1/' \
      /etc/pam.d/su
  fi
}

# Update hostname & static IP
get_text "Hostname:" `hostname`
HOSTNAME="$RET"
echo "HOSTNAME=$HOSTNAME"
/usr/sbin/salpack-static-network all "$HOSTNAME"

# Update aliases
grep -q ^root: /etc/aliases \
  || (get_text "root's email address:";
      echo "root: $RET" >> /etc/aliases; newaliases)

# Update serial console and other things for virtual machine
if [ -x /usr/sbin/salpack-update-guest ]; then
  /usr/sbin/salpack-update-guest
fi

# Update NRPE
if rpm -q salpack-nrpe >/dev/null; then
  reconfigure_nrpe
fi

# stop iscsi (you only need iscsid), if present
chkconfig iscsi off 2>/dev/null || true

# Start ntp if possible
chkconfig ntpd stop >/dev/null 2>/dev/null
if [ -x /etc/init.d/ntpdate ]; then
  chkconfig ntpdate on
  service ntpdate start
fi
chkconfig ntpd on
service ntpd start
