#!/bin/sh

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

# @file
#
# Vaisala Post OS Install Script     
#
# $URL: https://subversion.vaisala.com/svn/repos/sigmet/wr_iris_rda/branches/release_8.13.7/base/install_tools/sigconfig $
#
# $Id: sigconfig 31148 2017-03-27 13:55:50Z 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
#            -rvp8   : Configure RVP8 system and start RVP8 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:"
#               -6   : For CentOS6.x"
#               -7   : For CentOS7.x"
#Optional directory path where CENTOS6 or CENTOS7 is located:"
#  -instdir <DIR> : Set directory holding RDA/IRIS files"

# ==============================
# Identify OS disttribution 

OS_DIST=$(dist=`cat /etc/*release` ; echo ${dist:0:7})

#define yum repository configuration directory
YUMDIR='/etc/yum.repos.d'
YUM_BCK='repo.bck'

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


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
    if [ "${OS_VERSION}" = "7" ] ; then
    grep -q -e "^Cmnd_Alias *SERVICES" $sfile  || \
        echo "Cmnd_Alias SERVICES = /sbin/service, /sbin/chkconfig, /usr/bin/systemctl" >> $sfile
    else
    grep -q -e "^Cmnd_Alias *SERVICES" $sfile  || \
        echo "Cmnd_Alias SERVICES = /sbin/service, /sbin/chkconfig" >> $sfile
    fi 

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

    chmod u-w $sfile
}

config_ifdr_interface()
{
  # Not using for now
  # Configure network interface for RVP9 IFDR. This section should handle
  # different name of NIC interface, i.e, eth, eno, enp*s*f*. If the system
  # has the second interface and if it is not configure (down) we just replace
  # its configuration file.
 
  netinterfaces=($(ifconfig | grep flags | grep -v lo | awk '{print $1}'))
  if [ !z ${netinterface[1]} ] ; then 
     ethernet2=$(echo ${interfaces[1]} | sed s/:/""/)
     ipadd='10.0.1.213'
     if test $(cat /sys/class/net/${ethernet2}/operstate) = down ; then
     rm /etc/sysconfig/network-scripts/ifcfg-${ethenet2}
     cat <<EOF >/etc/sysconfig/network-scripts/ifcfg-${ethernet2}
TYPE="Ethernet"
BOOTPROTO="none"
DEFROUTE="yes"
IPV4_FAILURE_FATAL="no"
NAME="$ethernet2"
ONBOOT="yes"
IPADDR="$ipadd"
PREFIX="24"
EOF
    else 
        echo "No second network interface on system"
    fi
fi
}

config_localyum_repo()
{
if [ ! -d "${YUMDIR}/${YUM_BCK}" ] ; then
    install -m 644 -d ${YUMDIR}/${YUM_BCK}
    mv ${YUMDIR}/*.repo ${YUMDIR}/${YUM_BCK}/
fi
CURRENTDIR=$(pwd)
BASEURL_SEARCH_STR="BASEURL_KEYWORD"
BASEURL_KEYWORK_REPLACE="file://"${CURRENTDIR}

if [ "${OS_VERSION}" = "7" ] ; then
   # 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
   # Need to fix the path in iriscentos7.repo.conf to where the RPM files are located on the DVD.
   # Search for the $BASEURL_SEARCH_STR and replace it with $BASEURL_KEYWORK_REPLACE.
   # Then write the fixed file to ${YUMDIR}/iriscentos7.repo
   IRISCENTOS7_REPO_INPUT=${CURRENTDIR}"/iriscentos7.repo.conf"
   IRISCENTOS7_REPO_OUTPUT=${YUMDIR}"/iriscentos7.repo"
   sed -e "s|$BASEURL_SEARCH_STR|$BASEURL_KEYWORK_REPLACE|g" $IRISCENTOS7_REPO_INPUT > $IRISCENTOS7_REPO_OUTPUT
else 
   # Need to fix the path in iriscentos6.repo.conf to where the RPM files are located on the DVD.
   # Search for the $BASEURL_SEARCH_STR and replace it with $BASEURL_KEYWORK_REPLACE.
   # Then write the fixed file to ${YUMDIR}/iriscentos6.repo
    IRISCENTOS6_REPO_INPUT=${CURRENTDIR}"/iriscentos6.repo.conf"
    IRISCENTOS6_REPO_OUTPUT=${YUMDIR}"/iriscentos6.repo"
    sed -e "s|$BASEURL_SEARCH_STR|$BASEURL_KEYWORK_REPLACE|g" $IRISCENTOS6_REPO_INPUT > $IRISCENTOS6_REPO_OUTPUT
fi

}

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

if [ "${RVP}" = "rvp8" -a "${HAS_IRIS}" = "true" ] ; then
   systemctl enable rvp8.service
elif [ "${RVP}" = "rvp8" -a "${HAS_IRIS}" != "true" ] ; then
   systemctl enable rvp8.service
   systemctl enable dspexport.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

}

config_centos6_services()
{
if [ "${HAS_RDA}" = "true" ] ; then
   echo " Configuring RDA environment if we-re really an RDA"
   /sbin/chkconfig --add rdasys
fi

if [ "${RVP}" = "rvp8" ] || \
   [ "${RVP}" = "rvp900" ] || \
   [ "${RCP}" = "rcp8" ] || \
   [ "${HAS_IRIS}" = "true" ] ; then
   /sbin/chkconfig --add antennad 
fi

if [ ! -r /etc/sysconfig/rpcbind ] ;then
   echo "RPCBIND_ARG=-i" > /etc/sysconfig/rpcbind
fi

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

if [ "${RCP}" = "rcp8" ] ; then
   /sbin/chkconfig --add rcp8
fi

if [ "${HAS_IRIS}" = "true" ] ; then
   /sbin/chkconfig --add iris 
fi

if [ "${RVP}" = "rvp8" -a "${HAS_IRIS}" = "true" ] ; then
   /sbin/chkconfig --add rvp8
elif [ "${RVP}" = "rvp8" -a "${HAS_IRIS}" != "true" ] ; then
   /sbin/chkconfig --add rvp8
   /sbin/chkconfig --add dspexport
fi

if [ "${RVP}" = "rvp900" -a "${HAS_IRIS}" = "true" ] ; then
   /sbin/chkconfig --add rvp900
elif [ "${RVP}" = "rvp900" -a "${HAS_IRIS}" != "true" ] ; then
   /sbin/chkconfig --add rvp900
   /sbin/chkconfig --add dspexport
fi
}

kernel_param_config()
{
 # 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 

 #  cd ${IRIS_ROOT}/config
 #  mkfifo fifo_hostio-x fifo_hostio-y fifo_dau-x fifo_dau-y fifo_dcu-x fifo_dcu-y
 #  chown radarop:users fifo_*

}

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

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

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

  -6|-7 )
    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 "           -rvp8 : Configure RVP8 system and start RVP8 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 "              -6 : For CentOS6.x"
  echo "              -7 : For CentOS7.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_REL=`uname -r`
KERNEL_REL=`uname -r | sed -e "s/-.*//"`

if [ "${OS_VERSION}" = "7" -a "${KERNEL_REL}" = "3.10.0" ] ; then
  KERNEL_MATCH="true"
elif [ "${OS_VERSION}" = "6" -a "${KERNEL_REL}" = "2.6.32" ] ; then
  KERNEL_MATCH="true"
else
  KERNEL_MATCH="false"
fi

if [ "${KERNEL_MATCH}" = "false" ] ; then
  echo ""
  echo "#############################################################"
  echo "## Warning: Kernel release ${KERNEL_REL} 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}" = "6"  ] ; then
    echo "##          We Require kernel release 2.6.32."  
  fi
  echo "##          Current kernel release is ${CUR_KERNEL_REL}."
  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"

#echo "RVP ${RVP}"
#echo "RCP ${RCP}"
#echo "IRIS ${IRIS}"
#echo "RHEL_VERSION ${RHEL_VERSION}"
#echo "IRIS_INSTDIR ${IRIS_INSTDIR}"
#echo "RDA_INSTDIR ${RDA_INSTDIR}"
#echo "EXTRASDIR ${EXTRASDIR}"
# Figure out the redhat version number


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}" = "rvp8" -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"
   config_localyum_repo
   yum -y groupinstall "Common Extras"
   if [ "${HAS_RDA}" = "true" ] ; then
      yum -y groupinstall "Rda Extras"  
   fi           
   if [ "${HAS_IRIS}" = "true" ] ; then
      yum -y groupinstall "Iris Extras"
   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 per_source for rsh for CentOS 6.
#
if [ "${OS_VERSION}" = "6" ] ; then
grep per_source /etc/xinetd.d/rsh >/dev/null \
    || sed -i.bak -e "/^ *}/i\\\tper_source\t\t= 100" /etc/xinetd.d/rsh
rm -f /etc/xinetd.d/rsh.bak
fi

# 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" ] ; then
    ${IRIS_INSTDIR}/instiris -files ${IRIS_INSTDIR} -root ${IRIS_ROOT} \
    -new -manuals

  if [ "${HAS_RDA}" = "true" ] ; then
    ${RDA_INSTDIR}/instiris -files ${RDA_INSTDIR} -root ${IRIS_ROOT} -nodelete \
      -new -manuals -rda
  fi
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_config

# 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
#
if [ "${OS_VERSION}" = "7" ] ; then
   config_centos7_services
else
   config_centos6_services
fi

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

# Remove IRIS/RDA yum repo file,and restore CentOS yum repo files
rm -f ${YUMDIR}/*.repo
mv ${YUMDIR}/${YUM_BCK}/*.repo ${YUMDIR}/
rmdir ${YUMDIR}/${YUM_BCK}

# 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

# 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 '**********************************************************'
