#!/bin/bash

. `dirname $0`/salpack-functions

restrict_root() {
  if get_yes_no "Restrict root login with keyboard password?"; then
    grep -q '^Match User root' /etc/ssh/sshd_config \
      || (
           echo "" >> /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
}

configure_console() {
  if get_yes_no "Reconfigure console to serial /dev/ttyS0?"; then
    /usr/sbin/salpack-configure-console update-grub2
  fi
}

update_aliases() {
  get_text "root's email address:"
  root_email="$RET"
  if [ "$root_email" ]; then
    echo "root: $root_email" >> /etc/aliases
    newaliases
  fi
}

increase_grub_timeout() {
  # GRUB1
  if [ -f /boot/grub/grub.conf ]; then
    sed -i 's/^timeout=1$/timeout=5/' /boot/grub/grub.conf
  fi
  # GRUB2
  if [ -f /boot/grub2/grub.cfg ]; then
    sed -i 's/^set timeout=1$/set timeout=5/' /boot/grub2/grub.cfg
    sed -i 's/^GRUB_TIMEOUT=1$/GRUB_TIMEOUT=5/' /etc/default/grub
  fi
}

if [ "$1" ]; then
  $@ # run this command
  exit 0
fi

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

# Restrict root login only with key
restrict_root

# Configure serial console
configure_console
increase_grub_timeout

# Update aliases
grep -q ^root: /etc/aliases || update_aliases

# Update serial console and other things for virtual machine
if [ -x /usr/sbin/salpack-configure-console ]; then
  # only update automatically if virtio disks found (for guests)
  if [ -f /dev/vda ]; then
    /usr/sbin/salpack-configure-console
  fi
fi

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

# Update mysql
if [ -x /usr/sbin/salpack-configure-mysql ]; then
  /usr/sbin/salpack-configure-mysql
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
  hwclock -w
fi
if [ -x /bin/systemctl ]; then
  systemctl enable ntpdate.service && systemctl start ntpdate.service
  hwclock -w
fi
chkconfig ntpd on
service ntpd start

# check mdadm.conf
if [ -f /etc/mdadm.conf ]; then
  if grep -q num-devices= /etc/mdadm.conf >/dev/null; then
    cat /etc/mdadm.conf
    echo "Num-devices defined in mdadm.conf, is it OK?"
  fi
fi
