#!/bin/sh

##C
#
# Vaisala software source code file
#
# Copyright (c) Vaisala Oyj 1993, 1995, 1997, 1998, 1999, 2000, 2001, 2002,
# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013.
# All rights reserved.
#
##/C

# @file
#
# Complete IRIS Installation/Upgrade
#
# $URL: https://subversion.vaisala.com/svn/repos/sigmet/wr_iris_rda/trunk/base/install_tools/instiris $
#
# $Id: instiris 31597 2017-11-27 15:12:02Z vch $


# Note the invocation directory, and its parent, on entry.
#
RUNDIR=`pwd`
cd .. ; RUNDIRUP=`pwd`

# List of apps potentially requiring X app-default files:
#
IRISAPPS="antenna ascope bitex color_setup dspx_scope errdiag iris irisnet manuals overlay ribsetup rtdisp runways setup sigaudio sigbru sigxbell tsarchive tsswitch utils vribbon window zauto7"
if [ -r /usr/lib/X11/app-defaults ] ; then
  X11APPDIR=/usr/lib/X11/app-defaults
else
  X11APPDIR=/usr/share/X11/app-defaults
fi

# Remove any troublesome aliases that we may have entered with.
#
unalias cp 2> /dev/null ; unalias mv 2> /dev/null
unalias ls 2> /dev/null ; unalias rm 2> /dev/null

USER="operator"
GROUP="users"

# ==============================
# Process argument list
#
MACHINE="`uname -s`"
if [ "$MACHINE" != 'Linux' ] ; then
  echo "Warning: Only Linux machines are supported" 1>&2
fi

   TARGNODE="`uname -n`" ; OPERATION="" ; VERBOSE="" ; MEDIA=""
    FILEDIR="${RUNDIR}"  ;   ROOTDIR="" ;  RDAOPT=""

      COPY="false" ;     HEADERS="false" ;    OBJECTS="false"
    SOURCE="false" ;      SETOWN="false" ;   TARGETED="false" ;  MANUALS="false"
  EXAMPLES="false" ; IRISWEBVIEW="false" ; IRIS3DVIEW="false" ; NODELETE="false"
  RHEL_VERSION=""  ;

if [ "$1" = "" ] ; then HELP="true" ; else HELP="false" ; fi

while [ ! "$1" = "" ] ; do
  OPT="$1" ; shift

  if [ "${OPT}" = "-help" ] ; then
    HELP="true"

  elif [ "${OPT}" = "-new" ] ; then
    if [ "${OPERATION}" = "upgrade" ] ; then
      echo "Can not specify both -new and -upgrade" 1>&2 ; exit 1
    fi
    OPERATION="new"

  elif [ "${OPT}" = "-upgrade" ] ; then
    if [ "${OPERATION}" = "new" ] ; then
      echo "Can not specify both -new and -upgrade" 1>&2 ; exit 1
    fi
    OPERATION="upgrade"

  elif [ "${OPT}" = "-setown" ] ; then
    SETOWN="true"

  elif [ "${OPT}" = "-manuals" ] ; then
    MANUALS="true"

#  elif [ "${OPT}" = "-webview" ] ; then
#    IRISWEBVIEW="true"

  elif [ "${OPT}" = "-3dview" ] ; then
    IRIS3DVIEW="true"

  elif [ "${OPT}" = "-nodelete" ] ; then
    NODELETE="true"

  elif [ "${OPT}" = "-rda" ] ; then
    RDAOPT="-rda"

  elif [ "${OPT}" = "-examples" ] ; then
    if [ "$1" = "" ] ; then
      echo "'-examples' requires args for the PRODUCT and PRODUCT_RAW directories." 1>&2
      exit 1
    else
      PRODUCT_DIR="$1" ; shift
      if [ "$1" = "" ] ; then
        echo "'-examples' requires args for the PRODUCT and PRODUCT_RAW directories." 1>&2
        exit 1
      else
        PRODUCT_RAW_DIR="$1" ; shift
        if [ "${PRODUCT_DIR##/*}" != "" -o "${PRODUCT_RAW_DIR##/*}" != "" ] ; then
          echo "PRODUCT and PRODUCT_RAW directories for examples must begin with '/'" 1>&2
          exit 1
        fi
      fi
    fi
    EXAMPLES="true"

  elif [  "${OPT}" = "-v" ] ; then
    VERBOSE="v"

  elif [  "${OPT}" = "-copy" ] ; then
    if [ "${MEDIA}" != "" ] ; then
      echo "Can not specify -copy with -files." 1>&2 ; exit 1
    fi
    COPY="true"

  elif [  "${OPT}" = "-files" ] ; then
    if [ "${COPY}" = "true" -o "(" "${MEDIA}" != "files" -a "${MEDIA}" != "" ")" ] ; then
      echo "Can not specify -files with -copy." 1>&2 ; exit 1
    fi
    MEDIA="files"
    if [ "$1" != "" -a "${1#-*}" = "$1" ] ; then
      FILEDIR="$1" ; shift
    fi

  elif [  "${OPT}" = "-group" ] ; then
    if [ "$1" = "" ] ; then
      echo "Missing group name" 1>&2 ; exit 1
    else
      GROUP="$1" ; shift
    fi

  elif [  "${OPT}" = "-user" ] ; then
    if [ "$1" = "" ] ; then
      echo "Missing user name" 1>&2 ; exit 1
    else
      USER="$1" ; shift
    fi

  elif [  "${OPT}" = "-target" ] ; then
    if [ "$1" = "" ] ; then
      echo "'-target' requires a network node name" 1>&2 ; exit 1
    else
      TARGETED="true" ; TARGNODE="$1" ; shift
    fi

  elif [  "${OPT}" = "-root" ] ; then
    if [ "$1" = "" ] ; then
      echo "'-root' requires a root point for IRIS" 1>&2 ; exit 1
    else
      ROOTDIR="$1" ; shift
      if [ "${ROOTDIR##/*}" != "" ] ; then
        echo "Root point for IRIS must begin with '/'" 1>&2 ; exit 1
      fi
      if [ "${ROOTDIR%%*/}" = "" ] ; then
        echo "Root point for IRIS must not end with '/'" 1>&2 ; exit 1
      fi
      if [ "${ROOTDIR##*//*}" != "${ROOTDIR}" ] ; then
        echo "Root point for IRIS must not contain repeated '/'" 1>&2 ; exit 1
      fi
    fi

  else
    echo "Unknown option: '${OPT}'" 1>&2 ; HELP="true"
  fi

done

# Print HELP messages if these were requested, either directly or
# indirectly.
#
if [ "${HELP}" = "true" ] ; then
  echo "Command Line Options:"
  echo "                     -new : Install a new IRIS from scratch"
  echo "                 -upgrade : Upgrade IRIS, preserving previous configurations"
  echo "                 -manuals : Install Manuals"
  echo "                -nodelete : Keep all old files from prior installations"
  echo "   -examples <prod> <raw> : Install example products"
  echo "                     -rda : We are installing RDA (default IRIS)"
#  echo "                 -webview : Install IRIS WebView"
  echo "                  -3dview : Install IRIS 3DView"
  echo ""
  echo "                    -copy : Install from an existing installation"
  echo "       -files [directory] : Individual files  /    is read from."
  echo ""
  echo "                  -setown : Set all file ownerships and modes"
  echo "            -group <name> : Set specific group, rather than users"
  echo "             -user <name> : Set specific user, rather than operator"
  echo "           -target <node> : Choose the node name of the target computer"
  echo "        -root <directory> : Choose IRIS root directory (e.g. /usr/sigmet)"
  echo "                       -v : Verbose (print progress messages)"
  exit 0
fi

# Fix out which version of RHEL we are installing.
# RHEL5 or RHEL6.  Force to RHEL6 if we can't figure it out.
# This is only required when installing IRIS3DVIEW and IRISWEBVIEW
KERNEL_REL=`uname -r | sed -e "s/-.*//"`

if [ "${KERNEL_REL}" = "2.6.32" ] ; then
  RHEL_VERSION="6"
  echo "RHEL6"
elif [ "${KERNEL_REL}" = "3.10.0" ] ; then
  RHEL_VERSION="7"
  echo "RHEL7"
else #Force to 7 for now
  RHEL_VERSION="7"
  echo "Default RHEL7"
fi


if [ -r /etc/group ] ; then
  GROUPLINE=`egrep "^${GROUP}:" /etc/group`
  if [ "${GROUPLINE}" = "" ] ; then
      echo " = = = = = = = = = = = = = = = = = = = = = = = = = = = ="     1>&2
      echo "ERROR: Could not locate '${GROUP}' in /etc/group file."       1>&2
      echo "Please override using -g option."                             1>&2
      echo " = = = = = = = = = = = = = = = = = = = = = = = = = = = ="     1>&2
      exit 1
  fi
fi


# ==============================
# Do some checking
# if ${OPERATION} = new or ${OPERATION} = upgrade
# then add HEADERS, OBJECTS and SOURCE
#

if [ "${OPERATION}" != "" ] ; then 
  HEADERS="true"
  OBJECTS="true"
  SOURCE="true"
fi

# ==============================
# Determine whether the command line options actually request that
# something be installed.
#
INSTALL_SOMETHING="false"

if [ "${OPERATION}" != ""     -o \
     "${MANUALS}"     = "true" -o \
     "${EXAMPLES}"    = "true" -o \
     "${IRISWEBVIEW}" = "true" -o \
     "${IRIS3DVIEW}"  = "true"    ] ; then
  INSTALL_SOMETHING="true"
fi ;

# ==============================
# Do some simple sanity checks on what has been requested
#
if [ "${INSTALL_SOMETHING}" = "true" ] ; then
  if [ "$COPY" = "false" -a "$MEDIA" = "" ] ; then
    echo "Must specify installation source (-copy, or -files)." 1>&2 
    exit 1
  fi
else
  if [ "${SETOWN}" = "false" ] ; then
    echo "Nothing to install; Nothing to setown.  Exiting..." 1>&2 
    exit 1
  fi
fi

if [ "$COPY" = "true" -a "$TARGETED" = "false" ] ; then
  echo "For a copy, must specify a remote target with -target." 1>&2
  exit 1
fi

# ==============================
# Check for problems in defining the root point for the installation.
# The IRISROOT variable will be get defined here if all goes well.
#
if [ "${ROOTDIR}" != "" ] ; then
  # Always use any root point that was specifed on the command line.
  #
  IRISROOT="${ROOTDIR%/}"
else
  # Targeted installations must specify the root -- give up if not.
  #
  if [ "${TARGETED}" = "true" ] ; then
    echo "For targeted installations you must also use '-root'." 1>&2
    exit 1
  fi
  # If the IRIS_ROOT external environment variable is already defined
  # but does not match the parent of the directory that we are running
  # in, then do not use either as the root point.
  #
  if [ "${IRIS_ROOT}" != "" ] ; then
    if [ "${IRIS_ROOT%/}" != "${RUNDIRUP%/}" ] ; then
      echo "You do not appear to be running in IRIS_ROOT (${IRIS_ROOT})." 1>&2
      echo "Please specify the installation directory with '-root'." 1>&2
      exit 1
    fi
  else
    echo "Cowardly refusing to infer the intended root point." 1>&2
    echo "Please specify the installation directory with '-root'." 1>&2
    exit 1
  fi
  # If no root point was chosen on the command line, but an IRIS_ROOT
  # definition exists that matches our parent directory, then use the
  # parent directory as the root point.
  #
  IRISROOT="${RUNDIRUP%/}"
fi

# Force SETOWN if we are installing anything, except IRIS WebView or IRIS 3DView.
# IRIS WebView and IRIS 3DView are not install in /usr/sigmet/... 
#
if [ "${INSTALL_SOMETHING}" = "true" ] ; then
  if [ "${IRISWEBVIEW}" = "true" -o \
       "${IRIS3DVIEW}"  = "true"    ] ; then
    SETOWN="false"
  else
    SETOWN="true"
  fi
fi

# ==============================
#   1) Define the remote shell command on the local machine.
#   2) Define the 'tar' command that can read from its standard input and
#      extract the necessary files.
#
alias REMSH="rsh ${TARGNODE} -l ${USER}"
TAR="tar x${VERBOSE}f -"


# Handle targeted versus local installations. 
#
if [ "$TARGETED" = "true" ] ; then

  if [ "$COPY" = "true" ] ; then
    if [ "${TARGNODE}" = "`uname -n`" ] ; then
      echo "Can't Copy/Install onto the same machine." 1>&2
      exit 1
    fi
  fi

fi

# ==============================
# Setup the name of the source directory that holds the installation
# files, and the aliases for reading and skipping those files.
#
if [ "${COPY}" = "true" ] ; then
  if [ "${RDAOPT}" = "-rda" ] ; then
    if [ ! -r ${IRIS_ROOT}/bin/rvp9 ] ; then
      echo "Can not make an RDA release from this machine" 1>&2 ; exit 1
    fi
  else
    if [ ! -r ${IRIS_ROOT}/bin/siris ] ; then
      echo "Can not make an IRIS release from this machine" 1>&2 ; exit 1
    fi
  fi
  alias READFILE='${RUNDIR}/make_iris_tape ${RDAOPT} -stdout ${RECNUM}'

else
  SOURCEDIR="${FILEDIR%/}/"
  alias READFILE='cat ${SOURCEFILE} | gunzip -c'
fi

alias SKIPRECORD='echo "Skipping ${THISRECORD}..."'
alias MISSINGRECORD='echo "${THISRECORD} not installed because ${SOURCEFILE} is missing"'

# Function to set the SOURCEFILE variable to the input file having
# either a ".tgz" (prefered) or ".gz" suffix (secondary).
#
setSourceFile() {
  SOURCEFILE="${SOURCEDIR}$1.tgz"
  if [ ! -r "${SOURCEFILE}" ] ; then
    SOURCEFILE="${SOURCEDIR}$1.gz"
  fi
}

# ==============================
# Make sure destination directory exists and is writable
# Only applicable if we are installing something in ${IRISROOT},
# which you can detect by checking ${SETOWN}.
#
if [ "${SETOWN}" = "true" ] ; then
    if [ "${TARGETED}" = "true" ] ; then
	TEST=`REMSH if test -d ${IRISROOT} -a -w ${IRISROOT} ';' then echo okay ';' fi 2>/dev/null`
    else
	TEST=`if test -d ${IRISROOT} -a -w ${IRISROOT} ; then echo okay ; fi`
    fi
    if [ "${TEST}" != "okay" ] ; then
	echo "Can not access '${IRISROOT}' on node '${TARGNODE}'" 1>&2 ; exit 1
    fi
fi

if [ "$EXAMPLES" = "true" ] ; then
  if [ "${TARGETED}" = "true" ] ; then
    TEST1=`REMSH if test -d ${PRODUCT_DIR}     -a -w ${PRODUCT_DIR}     ';' then echo okay ';' fi 2>/dev/null`
    TEST2=`REMSH if test -d ${PRODUCT_RAW_DIR} -a -w ${PRODUCT_RAW_DIR} ';' then echo okay ';' fi 2>/dev/null`
  else
    TEST1=`if test -d ${PRODUCT_DIR}     -a -w ${PRODUCT_DIR}     ; then echo okay ; fi`
    TEST2=`if test -d ${PRODUCT_RAW_DIR} -a -w ${PRODUCT_RAW_DIR} ; then echo okay ; fi`
  fi
  if [ "${TEST1}" != "okay" -o "${TEST2}" != "okay" ] ; then
    echo "Can not access '${PRODUCT_DIR}' and '${PRODUCT_RAW_DIR}' on node '${TARGNODE}'" 1>&2 ; exit 1
  fi
  TMP_DIR=${IRISROOT}"/tmp_prod"
  if [ "${TARGETED}" = "false" ] ; then
    rm -rf ${TMP_DIR} 1>/dev/null 2>/dev/null
    TEST1=`if test -d ${TMP_DIR} ; then echo okay ; fi 2>/dev/null`
    mkdir ${TMP_DIR} 1>/dev/null 2>/dev/null
    TEST2=`if test -d ${TMP_DIR} ; then echo okay ; fi 2>/dev/null`
  fi
  if [ "${TEST1}" = "okay" -o "${TEST2}" != "okay" ] ; then
    echo "Can not create temporary directory '${TMP_DIR}' on node '${TARGNODE}'" 1>&2 ; exit 1
  fi
fi

# ==============================
# If it looks like there is an IRIS already installed at the target point,
# then check to make sure that none of those processes are currently running.
#
PSIRIS=""
if [ "${TARGETED}" = "true" ] ; then
  TEST=`REMSH if test -r ${IRISROOT}/bin/ps_iris ';' then echo okay ';' fi 2>/dev/null`
  if [ "${TEST}" = "okay" ] ; then
    if [ "${VERBOSE}" = "v" ] ; then
      echo "Checking for IRIS already running on node '${TARGNODE}'..." ; fi
    PSIRIS="`REMSH export IRIS_BIN=${IRISROOT}/bin/ \; ${IRISROOT}/bin/ps_iris 2>/dev/null`"
  fi
else
  if [ -r ${IRISROOT}/bin/ps_iris ] ; then
    if [ "${VERBOSE}" = "v" ] ; then
      echo "Checking for local IRIS already running..." ; fi
    PSIRIS="`export IRIS_BIN=${IRISROOT}/bin/ ; ${IRISROOT}/bin/ps_iris`"
  fi
fi

TEST=`echo "${PSIRIS}" | sed 's/^IRIS Activity on.*$//'`
if [ "${TEST}" != "" ] ; then
  echo "" 1>&2
  echo "Sorry, processes are still running on node '${TARGNODE}'" 1>&2
  echo "" 1>&2
  echo "${PSIRIS}" 1>&2
  exit 1
fi

# ==============================
# Prevent various lossages associated with trying to install the manual
# pages on systems that are symbolically linked back to the original source.
# Also, do not allow the original source to be clobbered during any kind of
# installation.
#
if [ "${MANUALS}" = "true" ] ; then
  if [ "${TARGETED}" = "true" ] ; then
    TEST=`REMSH if '[' -h ${IRISROOT}/manuals ']' ';' then echo symlink ';' fi 2>/dev/null`
    if [ "${TEST}" = "symlink" ] ; then
      echo "Can not install manuals on top of a symbolic link" 1>&2 ; exit 1
    fi
  fi
  if [ "${TARGNODE}" = "wes-haze" -a "${IRISROOT}" = "/usr/sigmet" ] ; then
    echo "Can not overwrite source version of manuals" 1>&2 ; exit 1
  fi
fi

# ==============================
# If we are eventually going to be doing a "setown", then verify right
# away that we are running as root.
#
if [ "${SETOWN}" = "true" -a "${TARGETED}" = "false" ] ; then
  if [ ! -w / ] ; then
    echo "Can not perform 'setown' operations -- please run as 'root'." 1>&2 ; exit 1
  fi
fi

# ==============================
# Print diagnostics and possibly exit here for debugging
#
DEBUG="false"
if [ "${DEBUG}" = "true" ] ; then
  echo "         IRISROOT = '${IRISROOT}'"
  echo "        OPERATION = '${OPERATION}'"
  echo "             COPY = '${COPY}'"
  echo "          HEADERS = '${HEADERS}'"
  echo "          OBJECTS = '${OBJECTS}'"
  echo "           SOURCE = '${SOURCE}'"
  echo "           SETOWN = '${SETOWN}'"
  echo "         TARGETED = '${TARGETED}'"
  echo "          MANUALS = '${MANUALS}'"
  echo "         EXAMPLES = '${EXAMPLES}'"
  echo "      IRISWEBVIEW = '${IRISWEBVIEW}'"
  echo "       IRIS3DVIEW = '${IRIS3DVIEW}'"
  echo "          FILEDIR = '${FILEDIR}'"
  echo "        SOURCEDIR = '${SOURCEDIR}'"
  echo "            MEDIA = '${MEDIA}'"
  echo "INSTALL_SOMETHING = '${INSTALL_SOMETHING}'"
  exit 0
fi

#        ***************************
#        *                         *
#        * Extract Data from Media *
#        *                         *
#        ***************************

# Skip this section entirely if we are not installing anything at all.
#
if [ "${INSTALL_SOMETHING}" = "true" ] ; then

  if [ "${RDAOPT}" = "-rda" ] ; then
      PACKAGE="RDA"
  else
      PACKAGE="IRIS"
  fi

  if [ "${OPERATION}" = "new" ] ; then
      echo ""
      echo "===== Installing New ${PACKAGE} on '${TARGNODE}' rooted at '${IRISROOT}' ====="
      echo ""
      echo "  (This is a complete installation, and will overwrite any ${PACKAGE}"
      echo "   customization that you may have done already)"
      echo ""

  elif [ "${OPERATION}" = "upgrade" ] ; then
      echo ""
      echo "===== Upgrading ${PACKAGE} on '${TARGNODE}' rooted at '${IRISROOT}' ====="
      echo ""
      echo "  (This is an incremental upgrade, and will preserve all ${PACKAGE}"
      echo "   customization that you have done already)"
      echo ""
  fi

# ============================================================
# Always read in the first "installation" record.  You should
# never be executing from this target directory.
#
  THISRECORD="IRIS installation files" ; RECNUM="1"
  setSourceFile "install"

  if [ "${OPERATION}" != "" ] ; then
    if [ "${COPY}" = "true" -o -r "${SOURCEFILE}" ] ; then
      if [ "${TARGETED}" = "true" ] ; then
        echo "Extracting ${THISRECORD}..."

	if [ "${NODELETE}" = "false" ] ; then
          TEST=`REMSH cd ${IRISROOT} ';' rm -rf 'install/*' ';' echo '$?' 2>/dev/null`
          if [ "${TEST}" != "0" ] ; then exit 1 ; fi
        fi
        READFILE 2>/dev/null | REMSH cd ${IRISROOT} ';' ${TAR}
        if [ "${VERBOSE}" = "v" ] ; then echo "" ; fi

      else
	if [ "${NODELETE}" = "false" ] ; then
          TEST=`cd ${IRISROOT} ; rm -rf install/* ; echo $?`
          if [ "${TEST}" != "0" ] ; then exit 1 ; fi
        fi
        READFILE 2>/dev/null | ( cd ${IRISROOT} ; ${TAR} )
      fi
    else
      MISSINGRECORD
    fi

  else
    SKIPRECORD
  fi

# ============================================================
# Extract files that are needed for upgrades as well as initial
# installations.
#
  THISRECORD="IRIS executables and app-defaults" ; RECNUM="2"
  setSourceFile "app"

  BIN_STOPLIST="bin/ls|bin/grep|bin/find|bin/login|bin/mail|bin/spell|bin/tar"

  if [ ! "${OPERATION}" = "" ] ; then
    if [ "${COPY}" = "true" -o -r "${SOURCEFILE}" ] ; then
      echo "Extracting ${THISRECORD}..."

      FILES=""
      if [ "${TARGETED}" = "true" ] ; then
        TEST=`REMSH if test -d ${IRISROOT}/bin ';' then echo okay ';' fi 2>/dev/null`
        if [ "${TEST}" = "okay" ] ; then
          FILES="`REMSH cd ${IRISROOT} ';' find bin -type f -print 2>/dev/null`"
        fi
        echo ${FILES} | egrep ${BIN_STOPLIST} > /dev/null
        if [ "$?" = "0" ] ; then
          echo "ERROR: ${TARGNODE}:${IRISROOT}/bin contains UNIX system files." 1>&2 ; exit 1
        else
	  if [ "${NODELETE}" = "false" ] ; then
            TEST=`REMSH cd ${IRISROOT} ';' rm -rf bin ';' echo '$?' 2>/dev/null`
            if [ "${TEST}" != "0" ] ; then exit 1 ; fi
          fi
          READFILE 2>/dev/null | REMSH cd ${IRISROOT} ';' ${TAR}
        fi

      else
        if [ -d ${IRISROOT}/bin ] ; then
          FILES="`cd ${IRISROOT} ; find bin -type f -print`"
        fi
        echo ${FILES} | egrep ${BIN_STOPLIST} > /dev/null
        if [ "$?" = "0" ] ; then
          echo "ERROR: ${IRISROOT}/bin contains UNIX system files." 1>&2 ; exit 1
        else
	  if [ "${NODELETE}" = "false" ] ; then
            TEST=`cd ${IRISROOT} ; rm -rf bin ; echo $?`
            if [ "${TEST}" != "0" ] ; then exit 1 ; fi
          fi
          READFILE 2>/dev/null | ( cd ${IRISROOT} ; ${TAR} )
        fi
      fi

      if [ "${VERBOSE}" = "v" ] ; then echo "" ; fi

    else
      MISSINGRECORD
    fi
  else
    SKIPRECORD
  fi

# ============================================================
# Manuals 
#
  THISRECORD="Manuals..." ; RECNUM="4"
  setSourceFile "man"

  if [ "${MANUALS}" = "true" ] ; then
    if [ "${COPY}" = "true" -o -r "${SOURCEFILE}" ] ; then
      echo "Extracting ${THISRECORD}..."

      if [ "${TARGETED}" = "true" ] ; then
	if [ "${NODELETE}" = "false" ] ; then
          TEST=`REMSH cd ${IRISROOT} ';' rm -rf manuals ';' echo '$?' 2>/dev/null`
          if [ "${TEST}" != "0" ] ; then exit 1 ; fi
        fi
        READFILE 2>/dev/null | REMSH cd ${IRISROOT} ';' ${TAR}
      else
	if [ "${NODELETE}" = "false" ] ; then
          TEST=`cd ${IRISROOT} ; rm -rf manuals ; echo $?`
          if [ "${TEST}" != "0" ] ; then exit 1 ; fi
        fi
        READFILE 2>/dev/null | ( cd ${IRISROOT} ; ${TAR} )
      fi

      if [ "${VERBOSE}" = "v" ] ; then echo "" ; fi
    
    else
      MISSINGRECORD
    fi
  else
    SKIPRECORD
  fi

# ============================================================
# Optionally extract headers
#
  THISRECORD="headers" ; RECNUM="7"
  setSourceFile "headers"

  if [ "${HEADERS}" = "true" ] ; then
    if [ "${COPY}" = "true" -o -r "${SOURCEFILE}" ] ; then
      echo "Extracting ${THISRECORD}..."

      if [ "${TARGETED}" = "true" ] ; then
	if [ "${NODELETE}" = "false" ] ; then
          TEST=`REMSH cd ${IRISROOT} ';' rm -rf include ';' echo '$?' 2>/dev/null`
          if [ "${TEST}" != "0" ] ; then exit 1 ; fi
        fi
        READFILE 2>/dev/null | REMSH cd ${IRISROOT} ';' ${TAR}
      else
	if [ "${NODELETE}" = "false" ] ; then
          TEST=`cd ${IRISROOT} ; rm -rf include ; echo $?`
          if [ "${TEST}" != "0" ] ; then exit 1 ; fi
        fi
        READFILE 2>/dev/null | ( cd ${IRISROOT} ; ${TAR} )
      fi

      if [ "${VERBOSE}" = "v" ] ; then echo "" ; fi

    else
      MISSINGRECORD
    fi
  else
    SKIPRECORD
  fi
    
# ============================================================
# Optionally extract source
#
  THISRECORD="source files" ; RECNUM="8"
  setSourceFile "source"

  if [ "${SOURCE}" = "true" ] ; then
    if [ "${COPY}" = "true" -o -r "${SOURCEFILE}" ] ; then
      echo "Extracting ${THISRECORD}..."

      if [ "${TARGETED}" = "true" ] ; then
	if [ "${NODELETE}" = "false" ] ; then
          TEST=`REMSH cd ${IRISROOT} ';' rm -rf src/* ';' echo '$?' 2>/dev/null`
          if [ "${TEST}" != "0" ] ; then exit 1 ; fi
        fi
        READFILE 2>/dev/null | REMSH cd ${IRISROOT}/src ';' ${TAR}
      else
	if [ "${NODELETE}" = "false" ] ; then
          TEST=`cd ${IRISROOT} ; rm -rf src/* ; echo $?`
          if [ "${TEST}" != "0" ] ; then exit 1 ; fi
        fi
        READFILE 2>/dev/null | ( if [ ! -d ${IRISROOT}/src ]; then mkdir ${IRISROOT}/src; fi ; cd ${IRISROOT}/src ; ${TAR} )
      fi

      if [ "${VERBOSE}" = "v" ] ; then echo "" ; fi

    else
      MISSINGRECORD
    fi
  else
    SKIPRECORD
  fi

# ============================================================
# Optionally extract objects
#
  THISRECORD="library files" ; RECNUM="9"
  setSourceFile "objects"

  if [ "${OBJECTS}" = "true" ] ; then
    if [ "${COPY}" = "true" -o -r "${SOURCEFILE}" ] ; then
      echo "Extracting ${THISRECORD}..."

      if [ "${TARGETED}" = "true" ] ; then
	if [ "${NODELETE}" = "false" ] ; then
          TEST=`REMSH cd ${IRISROOT} ';' rm -rf lib ';' echo '$?' 2>/dev/null`
          if [ "${TEST}" != "0" ] ; then exit 1 ; fi
        fi
        READFILE 2>/dev/null | REMSH cd ${IRISROOT} ';' ${TAR}
      else
	if [ "${NODELETE}" = "false" ] ; then
          TEST=`cd ${IRISROOT} ; rm -rf lib ; echo $?`
          if [ "${TEST}" != "0" ] ; then exit 1 ; fi
        fi
        READFILE 2>/dev/null | ( cd ${IRISROOT} ; ${TAR} )
      fi

      if [ "${VERBOSE}" = "v" ] ; then echo "" ; fi

    else
      MISSINGRECORD
    fi

  else
    SKIPRECORD
  fi

# ============================================================
# Extract patch and template files that are needed for upgrades as
# well as initial installations.  These are broken off from the
# primary APP section to make the later smaller.
#
  THISRECORD="templates and dt" ; RECNUM="A"
  setSourceFile "tplates"

  if [ ! "${OPERATION}" = "" ] ; then
    if [ "${COPY}" = "true" -o -r "${SOURCEFILE}" ] ; then
      echo "Extracting ${THISRECORD}..."

      if [ "${TARGETED}" = "true" ] ; then
	if [ "${NODELETE}" = "false" ] ; then
          TEST=`REMSH cd ${IRISROOT} ';' rm -rf config_template dt ';' echo '$?' 2>/dev/null`
          if [ "${TEST}" != "0" ] ; then exit 1 ; fi
        fi
        READFILE 2>/dev/null | REMSH cd ${IRISROOT} ';' ${TAR}
      else
	if [ "${NODELETE}" = "false" ] ; then
          TEST=`cd ${IRISROOT} ; rm -rf config_template dt ; echo $?`
          if [ "${TEST}" != "0" ] ; then exit 1 ; fi
        fi
        READFILE 2>/dev/null | ( cd ${IRISROOT} ; ${TAR} )
      fi

      if [ "${VERBOSE}" = "v" ] ; then echo "" ; fi
    
    else
      MISSINGRECORD
    fi
  else
    SKIPRECORD
  fi

# ============================================================
# Skip user and site files if this is an incremental upgrade
#
  THISRECORD="user and site configurations" ; RECNUM="3"
  setSourceFile "tplates"

  if [ "${OPERATION}" = "new" ] ; then
    if [ "${COPY}" = "true" -o -r "${SOURCEFILE}" ] ; then
      echo "Copying ${THISRECORD} from config_templates..."

      if [ "${TARGETED}" = "true" ] ; then
	  if [ "${NODELETE}" = "false" ] ; then
	      TEST=`REMSH cd ${IRISROOT} ';' rm -rf config ';' echo '$?' 2>/dev/null`
	      if [ "${TEST}" != "0" ] ; then exit 1 ; fi
	  fi
	  REMSH mkdir ${IRISROOT}/config
	  REMSH cp -r ${IRISROOT}/config_template/* ${IRISROOT}/config
      else
	if [ "${NODELETE}" = "false" ] ; then
          TEST=`cd ${IRISROOT} ; rm -rf config ; echo $?`
          if [ "${TEST}" != "0" ] ; then exit 1 ; fi
        fi
	  [ -d ${IRISROOT}/config ] || mkdir ${IRISROOT}/config
	  cp -r ${IRISROOT}/config_template/* ${IRISROOT}/config
      fi

      if [ "${VERBOSE}" = "v" ] ; then echo "" ; fi

    else
      MISSINGRECORD
    fi
  else
    SKIPRECORD
  fi


# ============================================================
# Optionally Webserver
#
  THISRECORD="IRIS WebView" ; RECNUM="X"

  if [ "${IRISWEBVIEW}" = "true" ] ; then
    echo "Extracting ${THISRECORD}..."

# For testing on wes-dp-laptop put in GUI "Read from" /home/doug/RHEL5/extras
    IRISWEBVIEWROOT="${FILEDIR%/*}/extras/RPMS"
    if [ -d ${IRISWEBVIEWROOT} ] ; then 
      cd ${IRISWEBVIEWROOT}
    fi

    CURIRISWEBVIEWROOT=`pwd`
    echo "Current Dir: ${CURIRISWEBVIEWROOT}"

#   Add java.  Java already installed on RHEL6
    if [ "${RHEL_VERSION}" = "5" ] ; then
      rpm -Uvh java-1.6.0-sun-1.6*
      rpm -Uvh java-1.6.0-sun-plugin-1.6*
    fi

#   Add Flash
    rpm -Uvh flash-plugin-*

#   Install tomcat6 startup/shutdown script (tomcat6.rc) to /etc/init.d
#   Install tomcat6 to /var/lib, setup link, remove unused directories
#   Tomcat already installed on RHEL6
    if [ "${RHEL_VERSION}" = "5" ] ; then
      if [ ! -d /var/lib/tomcat6 ] ; then 
        cp tomcat6.rc /etc/init.d/tomcat6
        TOMCATDIR=/var/lib
        cp apache-tomcat-6.0.* ${TOMCATDIR} 
        cd ${TOMCATDIR}
        tar -zxvf apache-tomcat-6.0.*
        rm apache-tomcat-6.0.*.gz
        ln -s apache-tomcat-6.0.26 tomcat6
        cd tomcat6/webapps
        rm -rf docs/ examples/ host-manager/ manager/
      fi
    fi

#   Add geoserver.war, ROOT.war and iris.war to tomcat6/webapps/
    cd /var/lib/tomcat6/webapps
    if [ ! -r geoserver ] ; then 
      cp ${CURIRISWEBVIEWROOT}/../../Webview/geoserver*.zip .
      unzip -u geoserver-1.7.7-war.zip
      rm geoserver-1.7.7-war.zip GPL.txt LICENSE.txt
    fi
    rm -rf ROOT* iris*
    cp -u ${CURIRISWEBVIEWROOT}/../../Webview/ROOT.war .
    cp -u ${CURIRISWEBVIEWROOT}/../../Webview/iris.war .

#   startup postgresql and tomcat6
    if [ "${RHEL_VERSION}" = "5" ] ; then
      service postgresql start
      service tomcat6 start
    else # RHEL6
#     Need to change owner:group on some tomcat6 directories
#     because of permissions errors.
#     Also on newly install postgres you need to type 
#     "service postgresql initdb"
      chown -R tomcat:tomcat /var/log/tomcat6
      chown -R tomcat:tomcat /var/lib/tomcat6
      if [ ! -d /var/lib/pgsql/base ] ; then
        service postgresql initdb
      fi
      service postgresql start
      service tomcat6 start
    fi
#   Sleep 5 just to let geoserver.war and iris.war unpack
    sleep 5
  
#   Test if database vsowebdb is already created.
    DBCHECK=$((su postgres -c "psql vsowebdb -c \"\q\"") 2>&1)
    if [[ "${DBCHECK}" =~ "\"vsowebdb\" does not exist" ]] ; then
#     set postgres password to xxxxxx
      echo 'xxxxxx' | passwd --stdin postgres 
 
#     login to postgres.  create vsowebdb, create vsowebuser with password vsoweb, load vsowebdb 
      su postgres -c "createdb vsowebdb"
      su postgres -c "psql vsowebdb -c \"create user vsowebuser with password 'vsoweb';\""
      su postgres -c "psql vsowebdb -c \"grant all privileges on database vsowebdb to vsowebuser;\""
      su postgres -c "psql vsowebdb -c \"\i ${CURIRISWEBVIEWROOT}/../../Webview/vsowebdb.sql;\""

#     Configuring the system for local or host to "trust" authentication.
#     This allows any user to connect as any PostgreSQL user.
#     Must remove "sameuser" first and then replace "ident" with "trust"
      cd /var/lib/pgsql/data
      cp pg_hba.conf  pg_hba.conf.bak
      sed '
        s/ sameuser//g 
        s/ ident/ trust/g' <pg_hba.conf.bak >pg_hba.conf

#     Automatic startup of postgres, httpd and tomcat6 when logging in
      chkconfig postgresql on
      chkconfig --level 345 httpd on
      chkconfig --level 345 tomcat6  on
    fi 
  else
    SKIPRECORD
  fi


# ============================================================
# Optionally extract 3DView
#
  THISRECORD="IRIS 3DView" ; RECNUM="X"

  if [ "${IRIS3DVIEW}" = "true" ] ; then
    echo "Installing  ${THISRECORD}..."

    IRIS3DROOT="${FILEDIR%/*}/extras/RPMS"
    if [ -d ${IRIS3DROOT} ] ; then 
      cd ${IRIS3DROOT}
    fi
    echo "Current dir: `pwd`"

    if [ "${RHEL_VERSION}" = "6" ] ; then
    rpm -Uvh xorg-x11-server*
    rpm -Uhv proj-*
    rpm -Uhv gl2ps*
    rpm -Uhv qt-mobility*
    rpm -Uhv qtwebkit*
    rpm -Uhv vtk*
    rpm -Uhv iris3dview-1.0*
    fi

# This will print out the rpm name and the rpm version
#    RPMS="vtk
#          vtk-qt
#          qt4
#          boost"
#
#    for RPM in ${RPMS} ; do
#      OUT=`rpm -q ${RPM}`
#      echo "RPM ${OUT}"
#      echo "NAME ${OUT%%-*}"
#      echo "VER ${OUT##*${RPM}}"
#    done

  else
    SKIPRECORD
  fi

# ============================================================
# Optionally extract examples, make sure you have the source files
#
  THISRECORD="example product files" ; RECNUM="X"

  if [ "${EXAMPLES}" = "true" ] ; then
    echo "Extracting ${THISRECORD}..."

    setSourceFile "prod"

    if [ "${TARGETED}" = "true" ] ; then
      READFILE 2>/dev/null | REMSH cd ${PRODUCT_DIR} ';' ${TAR}
    else
      READFILE 2>/dev/null | ( cd ${TMP_DIR} ; ${TAR} )
      find ${TMP_DIR} -type f -exec chown ${USER} {} ';'
      find ${TMP_DIR} -type f -exec chgrp ${GROUP} {} ';'
      find ${TMP_DIR} -type f -exec chmod ug+w,ugo+r {} ';'
      mv ${TMP_DIR}/* ${PRODUCT_DIR} 
      rm -rf ${TMP_DIR}/* 
    fi
     
    setSourceFile "prod_raw"

    if [ "${TARGETED}" = "true" ] ; then
      READFILE 2>/dev/null | REMSH cd ${PRODUCT_RAW_DIR} ';' ${TAR}
      REMSH mv ${TMP_DIR}"/*" ${PRODUCT_RAW_DIR}
      REMSH rm -rf ${TMP_DIR}
    else
      READFILE 2>/dev/null | ( cd ${TMP_DIR} ; ${TAR} )
      find ${TMP_DIR} -type f -exec chown ${USER} {} ';'
      find ${TMP_DIR} -type f -exec chgrp ${GROUP} {} ';'
      find ${TMP_DIR} -type f -exec chmod ug+w,ugo+r {} ';'
      mv ${TMP_DIR}/* ${PRODUCT_RAW_DIR}
      rm -rf ${TMP_DIR}
    fi
   
    if [ "${VERBOSE}" = "v" ] ; then echo "" ; fi

  else
    SKIPRECORD
  fi

# ============================================================
# All done
#

fi # Ends overall test on media usage...


#        *********************************
#        *                               *
#        * Set File Ownerships and Modes *
#        *                               *
#        *********************************

# This procedure will be executed whenever we do a new or upgrade
# installation, or when it is explicitly asked for on the command
# line.

if [ "${SETOWN}" = "true" ] ; then
  echo "Setting file ownerships and modes..."

  # If this is a targeted install, then try to execute "instiris -setown" as
  # root on the remote system.
  #
  if [ "${TARGETED}" = "true" ] ; then
    TEST1=`REMSH "/usr/bin/sudo ${IRISROOT}/install/instiris -setown -root ${IRISROOT}" 2>/dev/null`
    TEST2=`echo ${TEST1} | grep "Setting file ownerships"`
    if [ "${TEST2}" = "" ] ; then
      echo ""
      echo "Can not set file ownerships on ${TARGNODE}."
      echo "To finish installation, login to ${TARGNODE} as root and type:"
      echo ""
      echo "# ${IRISROOT}/install/instiris -setown -root ${IRISROOT}"
    fi

  else

# ------------------------------
# Make sure that the IRIS root directory has correct permissions
#
    echo "   Setting ${IRISROOT} root directory..."

    chown ${USER} ${IRISROOT}
    chgrp ${GROUP} ${IRISROOT}
    chmod 775      ${IRISROOT}

# ------------------------------
# Set owners, groups, and modes appropriately for everything in the
# main installation tree.
#
    DIRS="bin config config_template dt include install \
          lib manuals src"

    for ITEM in ${DIRS} ; do

      # Must be an existing directory 
      #
      if [ -d ${IRISROOT}/${ITEM} ] ; then 

        # Must not be symbolic link
        #
        if [ ! -h ${IRISROOT}/${ITEM} ] ; then
          if [ "${VERBOSE}" = "v" ] ; then echo "   Scanning $ITEM..." ; fi

	  # Set default owner and group in all cases
	  #
          cd ${IRISROOT}
          find ${ITEM} -exec chown ${USER} {} ';'
          find ${ITEM} -exec chgrp ${GROUP} {} ';'

          # Set default modes in all directories except for those
          # which we assume had better be right from the start.
	  #
	  case ${ITEM} in
	    install|libs) ;;
	    *)
	      find ${ITEM} -type f | xargs chmod 664
	      find ${ITEM} -type d | xargs chmod 6775
	      ;;
	  esac

          # ------------------------
          # Set x bits back on for config/pipes and for init files
          #
	  if [ "${ITEM}" = "config" ] ; then 
            cd ${IRISROOT}/${ITEM}
	    for INITFILE in *_init ; do
              if [ "${INITFILE}" != "*_init" ] ; then chmod +x ${INITFILE} ; fi
	    done
            if [ -d "pipes" ] ; then
              cd pipes ; chmod +x *
            fi
          fi

          # ------------------------
	  # Set x bits back on for config_template/pipes.  This is
	  # because these may be used in symbolic links.  Also for
	  # config_template/extras.
          #
	  if [ "${ITEM}" = "config_template" ] ; then 
            cd ${IRISROOT}/${ITEM}
            if [ -d "pipes" ] ; then
              cd pipes ; chmod +x *
            fi
            cd ${IRISROOT}/${ITEM}
            if [ -d "extras" ] ; then
              cd extras ; chmod +x *
            fi
            cd ${IRISROOT}/${ITEM}
            if [ -d "rc.d" ] ; then
              cd rc.d ; install --mode=755 * /etc/init.d/
            fi
            cd ${IRISROOT}/${ITEM}
            if [ -d "systemd" -a ${RHEL_VERSION} = "7" ] ; then
              cd systemd ; install --mode=644 * /usr/lib/systemd/system/
            fi
            cd ${IRISROOT}/${ITEM}
            if [ -d "LINUX/etc/ld.so.conf.d" -a ${RHEL_VERSION} = "7" ] ; then
              cd LINUX/etc/ld.so.conf.d ; install --mode=644 * /etc/ld.so.conf.d/
            fi
          fi
        fi
      fi
    done

# ------------------------------
# Get modes and owners correct in the "bin" directory.  Note that the
# owner and group have already been set to the defaults for '${USER}',
# so we only need to make the changes from there.
#
    if [ "${VERBOSE}" = "v" ] ; then echo "   Setting modes and owners in bin..." ; fi
    cd ${IRISROOT}/bin

    # First set default mode on all executable files to normal
    # execution.  Then, correct any files that must run with
    # set-uid-on-execute.
    #
    chmod +x *
    
    # This list is for files which run as ${USER}.
    #
    SET_OPER_UIDS="
      gaintest
      rtd_nids3_xmt
      rtd_v1_xmt
      rtd_v2_xmt
      show_iris
      show_machine_code
      signal_iris
      speed
      tags
      rvpts_example
      TsArchExec
      TsArchWatch
      "
    for ITEM in ${SET_OPER_UIDS} ; do
      if [ -r ${ITEM} ] ; then
        chmod 6775 ${ITEM}
      fi
    done
    unset SET_OPER_UIDS

    # Set mode and ownership on IRIS files that must run as root.
    # This list must match the utils/misc/sigmet_env list.
    #
    SET_ROOT_UIDS="
      archive
      copy_data_tape
      init_iris_dvd
      init_iris_lda
      init_iris_mo
      init_iris_tape
      init_sigbru_dvd
      rcp8 
      rtnice 
      rvp9
      rvp9proc
      tsexport
      tsimport
      rib_rcv
      rib_xmt
      tapex
      "
    for ITEM in ${SET_ROOT_UIDS} ; do
      if [ -r ${ITEM} ] ; then 
        chown root ${ITEM} ; chmod 6775 ${ITEM}
      fi
    done
    unset SET_ROOT_UIDS

# Special files on RDA systems only:
    if [ -r ${IRIS_ROOT}/bin/rvp9 ] ; then
# Note that the "-f" option does not work on RHEL5
	chmod -f 644 rda-*.ko
	chmod -f 644 *.jbc
	chmod -f 644 *.srec
    fi


    cd ${IRISROOT}/bin/dynamic
    # Now do dynamic libraries.  Must have execute turned on.
    #
    chmod +x *

# ------------------------------
# Handle special files.
#
    if [ "${VERBOSE}" = "v" ] ; then echo "   Checking special files..." ; fi

    for ITEM in "/dev/gkscsi" "/dev/scsi/gkscsi" ; do
      if [ -c ${ITEM} -o -b ${ITEM} ] ; then
        chown ${USER} ${ITEM}
        chgrp ${GROUP} ${ITEM}
        chmod 664      ${ITEM}
      fi
    done

# ------------------------------
# Make sure library directories exist if the rest of the tree does.
#
    if [ "${VERBOSE}" = "v" ] ; then echo "   Checking library directories..." ; fi

    cd ${IRISROOT}
    for ITEM in "base" "iris" "rda" ; do
      if [ -d ${ITEM} ] ; then
        if [ ! -d ${ITEM}/lib ] ; then
          mkdir          ${ITEM}/lib
          chown ${USER} ${ITEM}/lib
          chgrp ${GROUP} ${ITEM}/lib
          chmod 775      ${ITEM}/lib
        fi
      fi
    done

# ------------------------------
# Install APP-Defaults.
#
    echo "Installing Application Defaults..."

    REALAPPS=""
    for ITEM in ${IRISAPPS} ; do
      if [ -r ${IRISROOT}/bin/app-defaults/${ITEM} ] ; then
        REALAPPS="${REALAPPS} ${ITEM}"
      fi
    done
    cd ${IRISROOT}/bin/app-defaults ; cp ${REALAPPS} ${X11APPDIR}

    cd ${X11APPDIR} ; chmod 444 ${REALAPPS}
    chown ${USER} ${REALAPPS} ; chgrp ${GROUP} ${REALAPPS}


#-------------------------------
# 
    echo "Installing login profile files..."

    if [ ! -d /etc/profile.d ] ; then
	install --mode=755 -d /etc/profile.d
    fi
    install --mode=644 ${IRISROOT}/config_template/LINUX/etc/profile.d/* /etc/profile.d

    if [ ! -d /etc/sigmet ] ; then
	install --mode=755 -d /etc/sigmet
    fi
    install --mode=644 ${IRISROOT}/config_template/LINUX/etc/sigmet/profile.conf /etc/sigmet

# Installing the config file for the ipp library path

  install --mode=644 ${IRISROOT}/config_template/LINUX/etc/ld.so.conf.d/sigmet-ipp.conf /etc/ld.so.conf.d

# Install readme file for how to access logging for IRIS's daemon on CentOS 7
   if [ -d /usr/iris_data ] ; then
       install --mode=755 ${IRISROOT}/config_template/LINUX/etc/sigmet/CentOS7_readme /usr/iris_data/log
    fi

# ------------------------------
# Install logrotate files
#
    echo "Installing Logrotate files..."

    install --mode=644 ${IRISROOT}/config_template/logrotate.d/sigmet* /etc/logrotate.d


  fi # Ends else of 'if [ "${TARGETED}" = "true" ] ;'
fi # Ends test on setown
