#!/bin/sh
##C
#
# Vaisala software source code file
#
# Copyright (c) Vaisala Oyj 2012.
# All rights reserved.
#
##/C

# @file
#
# Vaisala Post OS Install Script     
#
# $URL: ssh://git@git.vaisala.com/wr/sigmet_base.git
#
# $Id: sigconfig 31584 2017-11-10 16:46:17Z vch $

# This script performs all of the post install configuration and
# actual software installation steps necessary for an IRIS or RDA
# system.  These are all NEW installations and will overwrite
# /usr/sigmet/config.

# Must specify exactly one of the following operations:
#Select valid software type:
#            -rvp900 : Configure RVP900 system and start RVP9 services
#            -rcp8   : Configure RCP8 system and start RCP8 services
#             -rda   : Configure generic RDA system without initial services
#            -iris   : Configure IRIS system with autostart
#   -instdir <DIR>   : Set directory holding RDA/IRIS files
#Select valid Linux release:"
#               -7   : For CentOS7.x"
#               -8   : For CentOS8.x"
#Optional directory path where CENTOS6 or CENTOS7 is located:"
#  -instdir <DIR> : Set directory holding RDA/IRIS files"

# ==============================


# Process argument list
HELP="" ; RVP="" ; RCP="" ; IRIS="" ; OS_VERSION="" ; INSTDIR=$PWD


function update_sudoers()
{
    sfile=/etc/sudoers

    chmod u+w $sfile

    sed -i.bak -e "s/^\(Defaults[ ]* requiretty\)/#\1/" ${sfile}
    rm -f ${sfile}.bak

    # Add SERVICES alias if it is not already there
    grep -q -e "^Cmnd_Alias *SERVICES" $sfile  || \
        echo "Cmnd_Alias SERVICES = /sbin/service, /sbin/chkconfig, /usr/bin/systemctl" >> $sfile

    # Add radarop user to sudoers 
    grep -q -i -e "^radarop.*SERVICE" $sfile  || \
        echo "radarop ALL=(ALL)  NOPASSWD: SERVICES" >> $sfile

    chmod u-w $sfile
}

function net_defroute()
{
  _IFDRINT='/etc/sysconfig/network-scripts/ifcfg-enp9s0'
  grep "DEFROUTE=yes" ${_IFDRINT} && \
       sed -i "s/DEFROUTE=yes/DEFROUTE=no/" ${_IFDRINT}
  grep "GATEWAY" ${_IFDRINT} && \
        sed -i '/GATEWAY/, +1 d' ${_IFDRINT}
}        

function config_repo()
{
  REPO_NAME=$1
  REPO_DIR="/etc/yum.repos.d"
  CUR_DIR=$(pwd)
  URL_PATH="file://${CUR_DIR}"

  # Create yum repo for installing extras rpms
  cp ${CUR_DIR}/${REPO_NAME} ${REPO_DIR} 
  sed -i "s+BASEURL+${URL_PATH}+" ${REPO_DIR}/${REPO_NAME}
}

function config_services()
{
 if [ "${RVP}" = "rvp900" ] || \
   [ "${RCP}" = "rcp8" ] ; then
   systemctl enable antennad.service 
 fi
 if [ "${RCP}" = "rcp8" ] ; then
   systemctl enable rcp8.service
 fi

 if [ "${RVP}" = "rvp900" -a "${HAS_IRIS}" = "true" ] ; then
   systemctl enable rvp900.service
 elif [ "${RVP}" = "rvp900" -a "${HAS_IRIS}" != "true" ] ; then
   systemctl enable rvp900.service
   systemctl enable dspexport.service
 fi

 if [ "${HAS_IRIS}" = "true" ] ; then
   systemctl enable iris.service
 fi

 # Turn off the bridge network interface (virbr0)
 systemctl stop libvirtd.service
 systemctl mask libvirtd.service

 # Turn off the automatic offline software update
 # 
 systemctl stop packagekit-offline-update.service
 systemctl mask packagekit-offline-update.service
 #
 # Turn this delay on to fix problem with network link down during the system booting that cause rvp900 service to fail   
 systemctl enable NetworkManager-wait-online.service

}


function kernel_param()
{
 # kernel parameters for network tuning
 grep rmem_max /etc/sysctl.conf >/dev/null \
    || echo "net.core.rmem_max = 4000000" >> /etc/sysctl.conf
 grep rmem_default /etc/sysctl.conf >/dev/null \
    || echo "net.core.rmem_default = 1000000" >> /etc/sysctl.conf 
 # kernel shared memory tuning  
 grep shmmax /etc/sysctl.conf >/dev/null \
    || echo -e "\n# Increase Shared Memory\nkernel.shmmax = 4294967295" >> /etc/sysctl.conf 
}

while [ "$1" != "" ] ; do
  OPT="$1" ; shift
  case ${OPT} in
  -rvp900 | -rda )
    if [ "${RVP}" != "" ] ; then
      echo "Can only specify either -rvp900, or rda" 1>&2 ; exit 1
    else
      RVP="${OPT#-}"
    fi ;;

  -rcp8 )
      RCP="${OPT#-}" ;;

  -iris )
      IRIS="${OPT#-}" ;;

  -7 )
    if [ "${OS_VERSION}" != "" ] ; then
      echo "Can not specify more than one option" 1>&2 ; exit 1
    else
      OS_VERSION="${OPT#-}"
    fi ;;

  -8 )
    if [ "${OS_VERSION}" != "" ] ; then
      echo "Can not specify more than one option" 1>&2 ; exit 1
    else
      OS_VERSION="${OPT#-}"
    fi ;;

  -help | -? )
    HELP="true" ;;

  -instdir )
    if [ "${1}" = "" ] ; then
      echo "Missing directory name for -instdir" 1>&2 ; exit 1
    else
      INSTDIR="${1}" ; shift
    fi ;;

  * )
    echo "Unknown option: '${OPT}'" 1>&2 ; exit 1 ;;
 esac
done

# Verify that there is something to do, and that our release
# directories are reasonable.
#
if [ "${RVP}" = "" -a "${RCP}" = "" -a "${IRIS}" = "" ] ; then
  HELP="true"
elif [ "${OS_VERSION}" = "" ] ; then
  HELP="true"
fi

# Print HELP messages if these were requested, either directly or
# indirectly.
#
if [ "${HELP}" = "true" ] ; then
  echo ""
  echo "Command Line Options:"
  echo "Select valid Sigmet software type:"
  echo "         -rvp900 : Configure RVP900 system and start RVP900 services"
  echo "           -rcp8 : Configure RCP8 system and start RCP8 services"
  echo "            -rda : Configure generic RDA system without initial services"
  echo "           -iris : Configure IRIS system with autostart"
  echo "Select valid Linux release:"
  echo "              -7 : For CentOS7.x"
  echo "              -8 : For CentOS8.x"
  echo "Optional directory path where CentOS6.x or CentOS7.x is located:"
  echo "  -instdir <DIR> : Set directory holding RDA/IRIS files"
  echo ""
  exit 0
fi

CUR_KERNEL=$(ker=`uname -r` ; echo ${ker%%-*})

if [ "${OS_VERSION}" = "7" -a "${CUR_KERNEL}" = "3.10.0" ] ; then
  KERNEL_MATCH="true"
elif [ "${OS_VERSION}" = "8" -a "${CUR_KERNEL}" = "4.18.0" ] ; then
  KERNEL_MATCH="true"
else
  KERNEL_MATCH="false"
fi

if [ "${KERNEL_MATCH}" = "false" ] ; then
  echo ""
  echo "#############################################################"
  echo "## Warning: Kernel release ${CUR_KERNEL} does not match CentOs${OS_VERSION:1:1} or RHEL${OS_VERSION:1:1} release"
  if [ "${OS_VERSION}" = "7"  ] ; then
    echo "##          We Require kernel release 3.10.0."  
  elif [ "${OS_VERSION}" = "8"  ] ; then
    echo "##          We Require kernel release 4.18.0."  
  fi
  echo "##          Current kernel release is ${CUR_KERNEL}."
  echo "#############################################################"
  echo ""
  echo -n "Type 'yes' if you want to override: "
  read OVERRIDE 
  if [ "${OVERRIDE}" != "yes" ] ; then
    echo "Exiting sigconfig"
    exit 1;
  fi
fi

IRIS_INSTDIR="${INSTDIR}/CENTOS${OS_VERSION}/iris"      ; HAS_IRIS=""
RDA_INSTDIR="${INSTDIR}/CENTOS${OS_VERSION}/rda"        ; HAS_RDA=""
EXTRASDIR="${INSTDIR}/CENTOS${OS_VERSION}/extras/RPMS"



if [ "${IRIS}" = "iris" ] ; then
  HAS_IRIS="true"
  if [ ! -d ${IRIS_INSTDIR} ] ; then
    echo "Bad IRIS install directory: ${IRIS_INSTDIR}" 1>&2 ; exit 1
  fi
fi


if [ "${RVP}" = "rvp900"  -o  "${RVP}" = "rda" -o "${RCP}" = "rcp8" ] ; then
  HAS_RDA="true"
  if [ ! -d ${RDA_INSTDIR} ] ; then
    echo "Bad RDA install directory: ${RDA_INSTDIR}" 1>&2 ; exit 1
  fi
fi

if [ ! -d ${EXTRASDIR} ] ; then
   echo "Missing RPMS directory in extras please install RPMS manually: ${EXTRASDIR}" 1>&2
else
  echo "Installing Extras RPMS"
  # kill yum process if it is doing some updates to proceed to install rpms
  if [ -f /var/run/yum.pid ] ; then
       pkill yumBackend.py
       rm -f /var/run/yum.pid
  fi
  # Identify OS version and configure yum repos, and install extras rpms
  if [ ${OS_VERSION} = "7" ] ; then
    config_repo iriscentos7.repo
    yum -y --disablerepo="*" --enablerepo="iriscentos7" groupinstall "Common-Extras"
    if [ "${HAS_RDA}" = "true" ] ; then
       yum -y --disablerepo="*" --enablerepo="iriscentos7" groupinstall "RDA-Extras"
       pip2 install -r requirements.txt --no-index --find-link file://${CUR_DIR}/CENTOS7/extras/optional
    fi
    if [ "${HAS_IRIS}" = "true" ] ; then
       yum -y --disablerepo="*" --enablerepo="iriscentos7" groupinstall "IRIS-Extras"
    fi
  fi

  if [ "${OS_VERSION}" = "8" ] ; then
     config_repo iriscentos8.repo
     dnf -y --disablerepo="*" --enablerepo="iriscentos8" groupinstall "Common-Extras"
     if [ "${HAS_RDA}" = "true" ] ; then
        dnf -y --disablerepo="*" --enablerepo="iriscentos8" groupinstall "RDA-Extras"  
        pip3 install -r requirements.txt --no-index --find-link file://${CUR_DIR}/CENTOS8/extras/optional
     fi           
     if [ "${HAS_IRIS}" = "true" ] ; then
        dnf -y --disablerepo="*" --enablerepo="iriscentos8" groupinstall "IRIS-Extras"
     fi
  fi
fi

echo "Configuring system, users and services..."

# Section A.4.2:
# Add radarop account with the appropriate settings.
#
if [ "`echo ~radarop`" != "/home/radarop" ]; then
    /usr/sbin/useradd -G users -m -u 1002 radarop
    echo 'xxxxxx' | passwd --stdin radarop
fi

# Add the observer account with the appropriate settings
#

if [ "`echo ~observer`" != "/home/observer" ]; then
    /usr/sbin/useradd -G users -m -u 1001 observer
    echo 'xxxxxx' | passwd --stdin observer
fi

# Add operator and radarop to sudoers file
update_sudoers

# Fix/update default route for network interface "enp9s0" in new RVP9 server
net_defroute


# Section A.4.4
# Create IRIS root directory and data directories
#
IRIS_ROOT="/usr/sigmet"
if [ ! -d ${IRIS_ROOT} ] ; then mkdir ${IRIS_ROOT} ; fi
chown operator:users ${IRIS_ROOT}
chmod 6775 ${IRIS_ROOT}

# If /usr/iris_data is a partition on the hard drive
# mkdir /usr/iris_data will fail, but we can
# still continue on with creating the data dirs 
# along with setting owner and permissions
#
IRIS_DATA="/usr/iris_data"
if [ ! -d ${IRIS_DATA} ] ; then mkdir ${IRIS_DATA} ; fi
cd ${IRIS_DATA}
for DIR in ascope ingest input log product product_raw suncal tape_inv temp zdrcal ; do
    if [ ! -d ${DIR} ] ; then mkdir ${DIR} ; fi
done
chown -R operator:users ${IRIS_DATA}
chmod -R 6775 ${IRIS_DATA}

# Section A.4.5
# Begin the actual IRIS/RDA installation.  Begin with an IRIS install
# followed by an optional RDA install if both are specified.
# Otherwise just do an RDA install.
#
if [ "${HAS_IRIS}" = "true" -a "${HAS_RDA}" = "true" ] ; then
    ${IRIS_INSTDIR}/instiris -files ${IRIS_INSTDIR} -root ${IRIS_ROOT} \
    -new -manuals
    ${RDA_INSTDIR}/instiris -files ${RDA_INSTDIR} -root ${IRIS_ROOT} -nodelete \
    -new -manuals -rda
else
  ${RDA_INSTDIR}/instiris -files ${RDA_INSTDIR} -root ${IRIS_ROOT} \
    -new -manuals -rda
fi

# Section A.4.6
# Add the shell environment
#
echo "Configuring home environments..."

IRIS_CONF_DESK="${IRIS_ROOT}/config_template/LINUX/desktop"
for USER in radarop observer ; do
    install --owner=${USER} --group=users ${IRIS_CONF_DESK}/mwmrc        /home/${USER}/.mwmrc
    install --owner=${USER} --group=users ${IRIS_CONF_DESK}/bash_profile /home/${USER}/.bash_profile
    install --owner=${USER} --group=users ${IRIS_CONF_DESK}/Xdefaults    /home/${USER}/.Xdefaults
    if [ "${HAS_RDA}" = "true" ] ; then
	install --owner=${USER} --group=users ${IRIS_CONF_DESK}/xinitrc_mwm /home/${USER}/.xinitrc
    else
	install --owner=${USER} --group=users ${IRIS_CONF_DESK}/xinitrc     /home/${USER}/.xinitrc
    fi
done

# Section A.4.7
# Increase shared memory for all system types 
#
  kernel_param

# Add the SIGMET pci card info to the pci.ids file
#

 grep "SIGMET RVP8" /usr/share/hwdata/pci.ids >/dev/null
 if [ "$?" = "1" ] ; then
     mv /usr/share/hwdata/pci.ids /usr/share/hwdata/pci.ids.bak
     sed s/'Altera Corporation$'/'Altera Corporation\
	7805  SIGMET RVP8\/Rx IF Receiver\
	7806  SIGMET RVP8\/Tx IF Transmitter\
	7807  SIGMET RVP\/RCP 62-pin I\/O Board'/ /usr/share/hwdata/pci.ids.bak > \
	/usr/share/hwdata/pci.ids
  fi

# Section A.4.9
# Add specific services for each type of product
#
config_services

# Not sure if this sound configuration is in used. It seems that from CentOS7 and CentOS8 its been removed
#Keep here in case

if [ -f /etc/modprobe.d/dist-oss.conf ] ; then
sed -i".bak" -e 's/^# install/install/' /etc/modprobe.d/dist-oss.conf
rm -f /etc/modprobe.d/dist-oss.conf.bak
fi


# Make ld.so to re-read the libraries's paths in /etc/ld.so.conf.d directory.
# If you don't run ldconfig command, the ld.so will only reference the collection of
# the libraries paths in the cach file (/etc/ld.so.cach)

/sbin/ldconfig

# Clean-up yum repos to avoid IRIS Focus installation fails on a single server configuration.
#
[[ -f /etc/yum.repos.d/iriscentos7.repo ]] && rm /etc/yum.repos.d/iriscentos7.repo
[[ -f /etc/yum.repos.d/iriscentos8.repo ]] && rm /etc/yum.repos.d/iriscentos8.repo

# Request that the radarop eject the CDROM and reboot
# the system.  This will clean out the services and start the system
# fresh.
#
echo '**********************************************************'
echo 'Remove installation media then "reboot"'
echo '**********************************************************'
