#!/usr/bin/bash

SALPACKDIR=`dirname $0`
. $SALPACKDIR/salpack-functions

SSHD_CONFIG=/etc/ssh/sshd_config
ALIASES=/etc/aliases
OS_VER=`uname -r | sed 's/^.*\([fe][cl][0-9]\+\).*$/\1/'`

if [ -x /usr/bin/dnf ]; then
  PKGMGR=dnf
else
  PKGMGR=yum
fi

show_completions() {
# update with:
#   grep '() {' salpack-configure-all | tr -d '(){}'
cat << EOF
ssh_restrict_root 
ssh_allow_editor 
configure_console 
update_aliases 
postfix_enable_tls 
increase_grub_timeout 
remove_mdadm_num_devices 
disable_mdadm_lvm 
disable_raid_check 
yum_cron 
enable_repo_centos_cr 
disable_unnecessary_services 
remove_unnecessary_pkgs 
install_logwatch 
install_qemu_ev 
enable_guest_shutdown 
remove_selinux 
enable_ntp_sync 
enable_firewall 
disable_debug_kernel
authselect_minimal
EOF
}

ssh_restrict_root() {
  if get_yes_no RESTRICT_ROOT "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
           if [ "${get_results[SSH_EDITOR]}" = "ON" ]; then
             echo -e "\tAcceptEnv EDITOR" >> $SSHD_CONFIG
           fi
         )
    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 SSH_EDITOR "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 SERIAL_CONSOLE "Reconfigure console to serial /dev/ttyS0?"; then
    $SALPACKDIR/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
}

postfix_enable_tls() {
  POSTFIX_CONF=/etc/postfix/main.cf
  if [ -f $POSTFIX_CONF ]; then
    if [ "`postconf -h smtpd_tls_security_level`" = "" ]; then
      if [ "`postconf -h smtp_tls_security_level`" = "" ]; then
        if get_yes_no POSTFIX_TLS "Enable TLS email sending for postfix?"; then
          echo "" >> $POSTFIX_CONF
          echo "# smtps email sending" >> $POSTFIX_CONF
          echo "smtp_tls_security_level = may" >> $POSTFIX_CONF
        fi
      fi
    fi
  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
}

remove_mdadm_num_devices() {
  if [ -r /etc/mdadm.conf ]; then
    if grep -q num-devices /etc/mdadm.conf; then
      if get_yes_no REMOVE_NUM_DEV "Remove num-devices=# from mdadm.conf?"; then
        sed -i 's/ num-devices=[0-9] / /' /etc/mdadm.conf
      fi
    fi
  fi
}

disable_mdadm_lvm() {
  if get_yes_no DISABLE_MDADM_LVM "Disable mdadm and LVM for external storage?"; then
    if [ ! -e /etc/mdadm.conf ]; then
      echo "DEVICE /dev/zero" >> /etc/mdadm.conf
    fi
    if [ -e /etc/lvm/lvm.conf -a ! -d /etc/lvm/devices ]; then
      # Add line after last occurence of "# filter =" string.
      mv -f /etc/lvm/lvm.conf /etc/lvm/lvm.conf~
      awk '
        FNR==NR{if (/# filter = /) p=NR; next} 1;
        FNR==p{
          print "\t# Filter out external storage devices"
          print "\tfilter = [ \"a|^/dev/sda[0-9]$|\", \"r|.*|\" ]";
        }' /etc/lvm/lvm.conf~ /etc/lvm/lvm.conf~ > /etc/lvm/lvm.conf
    fi
  fi
}

disable_raid_check() {
  if [ -f /etc/sysconfig/raid-check ]; then
    if get_yes_no DISABLE_RAID_CHECK \
         "Disable raid-check?"; then
      sed -i 's/^ENABLED=yes/ENABLED=no/' /etc/sysconfig/raid-check
    fi
  fi
}

yum_cron() {
  if get_yes_no YUM_CRON \
       "Reconfigure yum-cron to be silent and run automatic update?"; then
    if [ -r /etc/yum/yum-cron.conf ]; then
      sed -i~ \
        -e 's/^update_messages = yes/update_messages = no/' \
        -e 's/^apply_updates = no/apply_updates = yes/' \
        -e 's/^debuglevel = -2/debuglevel = -3/' \
        /etc/yum/yum-cron.conf
    fi
    #if [ -r /etc/yum/yum-cron-hourly.conf ]; then
    #  sed -i~ \
    #    -e 's/^debuglevel = -2/debuglevel = -4/' \
    #    /etc/yum/yum-cron-hourly.conf
    #fi
    # disable yum-cron-hourly
    if [ -r /etc/cron.hourly/0yum-hourly.cron ]; then
      sed -i~ \
        's|^exec /usr/sbin/yum-cron|#exec /usr/sbin/yum-cron|' \
        /etc/cron.hourly/0yum-hourly.cron
    fi
  fi
}

enable_repo_centos_cr() {
  if [ -f /etc/yum.repos.d/CentOS-CR.repo ]; then
    if [ -x /usr/bin/yum-config-manager ]; then
      yum-config-manager --enable cr > /dev/null
    fi
  fi
}

disable_unnecessary_services() {
  if get_yes_no DISABLE_UNNEC_SERVICES \
       "Disable unnecessary services?"; then
    if [ "$OS_VER" = "el7" ]; then
      NM="NetworkManager"
    else
      NM=""
    fi
    if [ -x /usr/bin/systemctl ]; then
      systemctl daemon-reload
    fi
    ssrv disable iscsi avahi-daemon \
      nfs nfslock nfs-lock rpcbind rpcgssd rpcidmapd rpcsvcgssd \
      iprdump iprinit iprupdate tuned firewalld $NM \
      dbus-org.freedesktop.Avahi netcf-transaction
    #ssrv enable rsyslog
  fi
}

remove_unnecessary_pkgs() {
  if get_yes_no REMOVE_UNNEC_PKGS \
       "Remove unnecessary packages?"; then
    if [ "$OS_VER" = "el7" ]; then
      $PKGMGR install -y network-scripts
      ssrv enable network
      $PKGMGR remove -y NetworkManager\*
    fi
    $PKGMGR remove -y firewalld iprutils subscription-manager
    $PKGMGR remove -y timedatex
    # xkeyboard-config required by KVM tools
    # remove firmwares in guest servers
    # but do not remove linux-firmware provided/obsoleted by salpack-vm
    rpm -q salpack-vm && $PKGMGR remove -y --exclude=salpack\* \
      iwl\*-firmware aic\*-firmware alsa\*-firmware ivtv-firmware
  fi
}

install_logwatch() {
  if get_yes_no INSTALL_LOGWATCH "Install logwatch?"; then
    $PKGMGR install -y logwatch
  fi
}

install_qemu_ev() {
  if get_yes_no INSTALL_QEMU_EV "Install QEMU EV and multipath?"; then
    $PKGMGR install centos-release-qemu-ev -y
    $PKGMGR install qemu-kvm-ev device-mapper-multipath -y
  fi
}

enable_guest_shutdown() {
  if [ -f /etc/sysconfig/libvirt-guests ]; then
    if get_yes_no GUEST_SHUTDOWN "Enable guest shutdown?"; then
      sed -i \
        -e 's/^#ON_BOOT=.*$/ONBOOT=ignore/' \
        -e 's/^#ON_SHUTDOWN=.*$/ON_SHUTDOWN=shutdown/' \
        -e 's/^#PARALLEL_SHUTDOWN=.*$/PARALLEL_SHUTDOWN=10/' \
        /etc/sysconfig/libvirt-guests
      echo "Guest shutdown enabled."
      systemctl enable libvirt-guests --now
      systemctl status libvirt-guests
      grep -v -e '^$' -e '^#' /etc/sysconfig/libvirt-guests
    fi
  fi
}

remove_selinux() {
  if get_yes_no REMOVE_SELINUX "Remove SELinux packages?"; then
    $PKGMGR remove selinux-policy\*
  fi
}

enable_ntp_sync() {
  if get_yes_no ENABLE_NTP "Enable NTP service?"; then
    if [ "$OS_VER" = "el7" -o "$OS_VER" = "el6" ]; then
      ssrv stop ntpd
      ssrv enable ntpdate ntpd
    else
      ssrv enable chrony-wait chronyd
    fi
    hwclock -w
  fi
}

enable_firewall() {
  if get_yes_no ENABLE_FIREWALL "Enable firewall?"; then
    ssrv enable iptables ip6tables
  fi
}

disable_debug_kernel() {
  sed -i 's/^\(MAKEDEBUG=yes\)/#\1/' /etc/sysconfig/kernel
}

authselect_minimal() {
  if get_yes_no AUTHSELECT_MINIMAL "Authselect minimal?"; then
    if [ -x /usr/bin/authselect ]; then
      authselect select minimal --force
      authselect apply-changes
    fi
  fi
}

if [ "$1" ]; then
  if [ "$1" = "--completions" ]; then
    show_completions
    exit 0
  fi
  if [ "$1" = "-f" ]; then
    export SALPACK_FORCE="ON"
    shift 1
  fi
fi
if [ "$1" ]; then
  $@ # run this command
  exit 0
fi

# Enable persistend journald logging
if [ -f /etc/systemd/journald.conf -a ! -f /var/log/journal ]; then
  mkdir -p /var/log/journal
  systemctl restart systemd-journald
fi

# Update hostname & static IP
get_text "Hostname:" `hostname`
HOSTNAME="$RET"
echo "HOSTNAME=$HOSTNAME"

# Update aliases
grep -q ^root: $ALIASES || update_aliases

if [ -f /etc/sysconfig/raid-check ]; then
  S_DISABLE_RAID_CHECK="ON"
else
  S_DISABLE_RAID_CHECK="OFF"
fi

get_multi Settings \
  STATIC_NETWORK "Configure static IP?" ON \
  RESTRICT_ROOT "Restrict root login with keyboard password?" ON \
  SSH_EDITOR "Allow EDITOR variable for ssh connections?" ON \
  AUTHSELECT_MINIMAL "Authselect minimal?" ON \
  DISABLE_UNNEC_SERVICES "Disable unnecessary services?" ON \
  REMOVE_UNNEC_PKGS "Remove unnecessary pkgs (firewalld,iprutils)?" ON \
  REMOVE_SELINUX "Remove SELinux packages?" OFF \
  INSTALL_LOGWATCH "Install logwatch?" ON \
  GUEST_SHUTDOWN "Enable guest shutdown?" ON \
  DISABLE_MDADM_LVM "Disable mdadm and LVM for external storage?" OFF \
  REMOVE_NUM_DEV "Remove num-devices=# from mdadm.conf?" ON \
  DISABLE_RAID_CHECK "Disable raid-check?" $S_DISABLE_RAID_CHECK \
  POSTFIX_TLS "Enable TLS email sending for postfix?" ON \
  DEL_LOCALHOST "Remove IPv6 localhost from /etc/hosts?" ON \
  ENABLE_NTP "Enable NTP service?" ON \
  ENABLE_FIREWALL "Enable firewall?" OFF \
  SERIAL_CONSOLE "Reconfigure console to serial /dev/ttyS0?" OFF

# reconfigure network
if get_yes_no STATIC_NETWORK "Configure static IP?"; then
  . $SALPACKDIR/salpack-static-network all "$HOSTNAME"
fi

# Restrict root login only with key
ssh_restrict_root

# Allow EDITOR
ssh_allow_editor

# Configure serial console
configure_console
increase_grub_timeout

# update mdadm.conf
remove_mdadm_num_devices
disable_mdadm_lvm

# configure services
postfix_enable_tls
disable_raid_check

# packages and services
enable_repo_centos_cr
remove_unnecessary_pkgs
disable_unnecessary_services
install_logwatch
enable_guest_shutdown

# Start ntp if possible
enable_ntp_sync

# Enable firewall
enable_firewall

# Disable debug kernels
disable_debug_kernel

# Switch to minimal auth
authselect_minimal

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

# Update mysql
if [ -x $SALPACKDIR/salpack-configure-mysql ]; then
  $SALPACKDIR/salpack-configure-mysql
fi
