#!/bin/bash

. `dirname $0`/salpack-functions

SSHD_CONFIG=/etc/ssh/sshd_config
ALIASES=/etc/aliases

ssh_restrict_root() {
  if get_yes_no "Restrict root login with keyboard password?"; then
    grep -q '^Match User root' $SSHD_CONFIG \
      || (
           echo "" >> $SSHD_CONFIG
           echo "Match User root" >> $SSHD_CONFIG
           echo -e "\tPasswordAuthentication no" >> $SSHD_CONFIG
         )
    sed -i 's/#\(auth\s*required\s*pam_wheel.so use_uid\)/\1/' \
      /etc/pam.d/su
  fi
}

ssh_allow_editor() {
  if get_yes_no "Allow EDITOR variable for ssh connections?"; then
    grep -q '^AcceptEnv EDITOR' $SSHD_CONFIG || \
      sed -i '/^AcceptEnv XMODIFIERS/aAcceptEnv EDITOR\n' \
        $SSHD_CONFIG
  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" >> $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
}

disable_nfs() {
  if get_yes_no "Disable NFS support?"; then
    ssrv disable nfs nfslock rpcbind rpcgssd rpcidmapd rpcsvcgssd
  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
ssh_restrict_root

# Allow EDITOR
ssh_allow_editor

# Configure serial console
configure_console
increase_grub_timeout

# Update aliases
grep -q ^root: $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
