#!/bin/bash
#
# USAGE: install [OPTIONS]
#
# OPTIONS:
#    -h|--help       Show this help text
#
# This script is the main TRIPsystem installation script.
#
# Before you run this script:
#   1. Make sure you are logged on as root
#   2. Create parent directory in which to install TRIP (e.g. /opt/trip/sys)
#        or
#      Choose an existing directory
#   3. Change the current directory to the one created in (2)
#   4. Unpack the distribution archive file for TRIPsystem
# 
# When the above is done, you may run this script: <version>/sbin/install
# E.g. v840/sbin/install
#
# An install.log file will be written to the <version> directory
#

if [ "x$1" = "x-h" ] || [ "x$1" = "x--help" ]; then
   head -22 $0 | tail -21 | cut -c3-
   exit
fi

# save current date and time
INST_DATE=`date '+%Y-%m-%d %H:%M:%S'`

# The current TRIP version
VERS_DIR=v843_1
VERSION=8.4-3
PATCH_NO=1

# The version string only includes the patch nr if this is a patch
if [ "$PATCH_NO" = "0" ]; then
   VERSIONP="$VERSION"
else
   VERSIONP="$VERSION:$PATCH_NO"
fi

# Which operating system are we running on?
OSNAME=`uname`
PLATFORM="`uname -p` platform"
if [ "$PLATFORM" == "unknown platform" ]; then
   PLATFORM="`uname -m` platform"
fi

# How shared object files are named on this O/S
if [ "$OSNAME" = "Darwin" ]; then
   SOEXT=dylib
else
   SOEXT=so
fi

# Determine the location of CONTROL, logs and user databases
LINK_DIR=/usr/local/trip/sys
if [ "$OSNAME" = "SunOS" ]; then
   SHARED_STATE_DIR=/var/trip
elif [ "$OSNAME" = "Darwin" ]; then
   SHARED_STATE_DIR=/usr/local/trip/var
else
   SHARED_STATE_DIR=/var/lib/trip
fi

# Which user are we running as?
WHOM=`(whoami) 2> /dev/null`
if [ $? -ne 0 ]; then
   if [ -f /usr/ucb/whoami ]; then
      WHOM=`/usr/ucb/whoami`
   fi
fi

# This script needs root privileges unless we're on macOS.
if [ "$OSNAME" != "Darwin" ]; then
   echo ""
   if [ "$WHOM" != root ]; then
      echo "You must be root to run this script!"
      echo "Exiting the installation procedure"
      echo ""
      exit 1
   fi
fi

# Determine how to have 'echo' not emit a newline character
if [ `echo "X\c"` = X ]; then
   C1=
   C2='\c'
elif [ `echo -n X` = X ]; then
   C1='-n'
   C2=
else
   C1=
   C2=
fi


##
# Verbose cp wrapper to deal with operating systems for which the cp
# command doesn't have the -v option.
#
cp_verbose()
{
if [ "$OSNAME" != "SunOS" ]; then
   cp -v $*
   RETVAL=$?
else
   echo "cp $*"
   cp $*
   RETVAL=$?
fi
   return $RETVAL
}

##
# Validator function for prompts requiring either Y or N as response
#
yesno_valid()
{
   inputval=$1
   if [ "$inputval" == "y" ] || [ "$inputval" == "Y" ] || \
      [ "$inputval" == "n" ] || [ "$inputval" == "N" ]
   then
      return 0
   elif [ "$2" != "" ] && [ "$inputval" = "?" ]; then
      return 0
   else
      return 1
   fi
}

##
# Prompt function that accepts either Y or N as response
# 
# Arguments:
#   $1: The prompt text to display
#   $2: The default value 
#   $3: Optional help function 
#
yesno()
{
   yesno_result=-1
   yesno_prompt=$1
   yesno_default=$2
   yesno_help=$3
   if [ "$yesno_default" = "Y" ]; then
      yesno_choice="[Y|n"
   elif [ "$yesno_default" = "N" ]; then
      yesno_choice="[y|N"
   else
      yesno_choice="[y|n"
   fi
   if [ "$yesno_help" != "" ]; then
      yesno_choice="$yesno_choice|?"
   fi
   yesno_choice="$yesno_choice]"
   doloop=0
   while [ "$doloop" = "0" ]
   do
      echo $C1 "$yesno_prompt $yesno_choice $C2"
      read answ
      if [ "$answ" != "" ] ; then
         if yesno_valid $answ "$yesno_help"; then
            printf "\n****** Answer: $answ\n"
         else
            continue
         fi
      elif [ "$answ" = "" ] && [ "$yesno_default" != "" ]; then
         printf "\n****** Answer: default [= $yesno_default]\n"
         answ=$yesno_default
      else
         continue
      fi
      case $answ in
         \?)
            if [ "$yesno_help" != "" ]; then
               eval $yesno_help
            fi
            ;;
         Y|y)
            yesno_result=0
            doloop=1
            ;;
         N|n)
            yesno_result=1
            doloop=1
            ;;
         *)
            ;;
      esac
   done
   return $yesno_result
}

echo "PLEASE NOTE!"
echo "  When prompted for a response, entering a ? gives a short help text"
echo ""

yesno_help_continue()
{
   echo ""
   echo ""
   echo "   Valid responses are: "
   echo ""
   echo "        Y  : you want to continue "
   echo ""
   echo "        N  : you want to exit "
   echo ""
   echo ""
   echo "   The default is Y  "
   echo ""
}

echo "Beginning installation of TRIP v$VERSIONP on a $OSNAME $PLATFORM."
if yesno "Do you wish to continue?" Y yesno_help_continue
then
   echo ""
   echo "Continuing with the installation process"
   echo ""
else
   echo ""
   echo "Exiting the installation procedure"
   echo ""
   exit 1
fi


# Check to make sure you are starting this from the right directory

if [ -d $VERS_DIR ]; then
   cd $VERS_DIR
fi

echo ""
if [ ! -d sbin ]; then
   if [ -f install ]; then
      cd ..
      if [ ! -d demo ]; then
         echo "Please run this script from one of the following directories:"
         echo ""
         echo "  <extract_dir>"
         echo "  <extract_dir>/$VERS_DIR"
         echo "  <extract_dir>/$VERS_DIR/sbin"
         echo ""
         echo "where <extract_dir> is the directory from which you issued the"
         echo "tar command to read the distribution media."
         echo "Exiting the installation procedure"
         exit 1
      fi
   else
      echo "Please run this script from one of the following directories:"
      echo ""
      echo "  <extract_dir>"
      echo "  <extract_dir>/$VERS_DIR"
      echo "  <extract_dir>/$VERS_DIR/sbin"
      echo ""
      echo "where <extract_dir> is the directory from which you issued the"
      echo "tar command to read the distribution media."
      echo "Exiting the installation procedure"
      echo ""
      exit 1
   fi
fi

# Installation home directory
TPATH=`pwd`

# Set up installation log file
LOGFILE=$TPATH/install-`date '+%Y%m%d-%H%M%S'`.log
echo ""
echo "NB! Installation log file is:"
echo "    $LOGFILE"
echo ""


##########################################################################
# If we're running on Linux, adjust the fapolicyd database as needed.
# This is required in order to avoid "operation not permitted" errors
# when using the libraries provided in the installation's lib directory
# and when TRIP programs and scripts run other TRIP programs (e.g. for
# batch job execution).
#

if [ "$OSNAME" = "Linux" ]; then
   $TPATH/sbin/chfapolicy_sys -a -p $TPATH | tee -a $LOGFILE
   echo "" | tee -a $LOGFILE
fi



##########################################################################
# For Linux, check if the distribution supported
#

if [ "$OSNAME" = "Linux" ]; then
   OSFAMILY=`$TPATH/sbin/ostype --family`
   if [ "$OSFAMILY" = "rhel" ]; then
      OSVERSION=`$TPATH/sbin/ostype --version`
      if [ "$OSVERSION" = "" ]; then
         OSVERSION=0
      fi
      if [ $OSVERSION -ne 9 ]; then
         echo "" | tee -a $LOGFILE
         echo "WARNING: Your system appears to be a RedHat Enterprise Linux, but it does" | tee -a $LOGFILE
         echo "         not look like it is version 9. TRIPsystem is not supported for" | tee -a $LOGFILE
         echo "         any other version of the RedHat Enterprise Linux distribution." | tee -a $LOGFILE
         echo "" | tee -a $LOGFILE
         if ! yesno "Are you sure you want to continue?" N ; then
            echo ""
            echo "Exiting the installation procedure"
            echo ""
            exit 1
         fi
      fi
   fi

   if [ "$OSFAMILY" != "rhel" ]; then
      echo ""
      echo "WARNING: Your system does not look like it runs RedHat Enterprise Linux." | tee -a $LOGFILE
      echo "         TRIPsystem is not supported for any other Linux distribution." | tee -a $LOGFILE
      echo ""
      if ! yesno "Are you sure you want to continue?" N ; then
         echo ""
         echo "Exiting the installation procedure"
         echo ""
         exit 1
      fi
   fi
fi
         

##########################################################################
# Check for presence of prerequisite software
#

if [ ! -f sbin/dependencies ]; then
   echo "ERROR: Unable to find the TRIPsystem 'dependencies' script." | tee -a $LOGFILE
   echo ""
   echo "Exiting the installation procedure" | tee -a $LOGFILE
   echo ""
   exit 1
fi
TDBS_HOME=$TPATH sbin/dependencies --check --from-installer
DEPRC=$?
if [ $DEPRC -ne 0 ]; then
   if [ "$OSNAME" = "Linux" ]; then
      echo ""
      if yesno "Do you wish to attempt to install the missing dependences?" Y ; then
         TDBS_HOME=$TPATH sbin/dependencies --install --from-installer
         DEPRC=$?
      fi
   else
      # Dependency installation on non-Linux operating systems must
      # be done manually.
      DEPRC=1
   fi
fi
if [ $DEPRC -ne 0 ]; then
   echo ""
   echo "Exiting the installation procedure" | tee -a $LOGFILE
   echo ""
   exit 1
fi
echo ""


##########################################################################
# Check for additional broken library dependencies
#

if [ -f lib/libtripxpi.so ]; then
    LD_LIBRARY_PATH=`pwd`/lib ldd lib/libtripxpi.so | grep -v libtdbs | grep -q "not found" > /dev/null 2>&1 
    if [ $? -eq 0 ]; then
       echo "One or more library dependencies could not be found:"
       LD_LIBRARY_PATH=`pwd`/lib ldd lib/libtripxpi.so | grep "not found"
       echo ""
       exit 1
    fi
fi


yesno_help_eula()
{
   echo ""
   echo "   You need to accept the end user license agreement"
   echo "   in order to install TRIPsystem."
   echo ""
}

##########################################################################
# Display EULA and ask for confirmation
#

EULACONF=$HOME/.tripeula/tripsystem-`echo $VERSION|cut -d- -f1`
if [ ! -f $EULACONF ]; then
clear 2> /dev/null
if [ $? -ne 0 ]; then
   echo ""
   echo ""
fi
echo END USER LICENSE AGREEMENT
echo ""
echo All rights to this software, its documentation and logotypes of the
echo TRIP product family and software \(altogether \"Software\"\) supplied
echo by DVG Operations GmbH \(DVG\) are exclusively owned by DVG.
echo ""
echo The transfer of this Software, solutions or parts thereof requires the prior
echo written agreement of DVG. Furthermore, the customer has the right to use
echo licensed Software and / or process solutions supplied by DVG to the extent
echo specified in his contract with DVG.
echo ""
echo The free-to-use non-commercial version doesn\'t require a prior written
echo agreement with DVG but such customers, organizations and/or third parties
echo agree by using the software and / or solution of DVG to be strongly
echo obliged to keep all rights to this software, documentation and logotypes of
echo the TRIP product family absolutely uninfringed and protected.
echo ""
if yesno "Do you accept these conditions?" Y yesno_help_eula ; then
   echo ""
   mkdir -p $HOME/.tripeula 2>/dev/null
   touch $EULACONF 2>/dev/null
   chmod 644 $EULACONF
else
   echo ""
   echo "Exiting the installation procedure"
   echo ""
   exit 1
fi
fi


# remove old install ctl files
rm -f $TPATH/trip-system-install-*.ctl 2> /dev/null

CVER=`strings -a lib/libtdbs.$SOEXT | grep "^$VERSIONP" | sort -u 2>/dev/null`
if [ "x$CVER" != "x$VERSIONP" -a "$OSNAME" != "AIX" ]; then
  echo "libtdbs.$SOEXT version does not match install version $VERSIONP"
  exit 1
fi


##########################################################################
# Installation proper begins here
##########################################################################

# output from here to the right curly bracket will be tee-d to $LOGFILE
{

# Set the umask for the duration of the script

OUMASK=`umask`
umask 022
echo "umask is changed to 022"

echo ""
echo "****** Install TRIP v$VERSIONP on a $OSNAME $PLATFORM"
echo ""
echo "$INST_DATE"
echo ""



##########################################################################
# Check basic installation conditions
#

HAS_CONFIG_IN_STDLOC=0
HAS_CONFIG_IN_ROOT=0
HAS_CONFIG_AS_TRIPRC=0
HAS_CONFIG_CONFLICT=0
HAS_LIBTDBS_FILE=0
HAS_LIBTDBS_LINK=0
OLD_TRIP_HOME=""

if [ -f $LINK_DIR/conf/tdbs.conf ]; then
   HAS_CONFIG_IN_STDLOC=1
   echo "Detected existing TRIP config file $LINK_DIR/conf/tdbs.conf"
fi
if [ -f /.TRIPrcs ]; then
   HAS_CONFIG_IN_ROOT=1
   echo "Detected existing TRIP config file /.TRIPrcs"
elif [ -f /.triprc ]; then
   HAS_CONFIG_IN_STDLOC=1
   HAS_CONFIG_AS_TRIPRC=1
   echo "Detected existing TRIP config file /.triprc"
fi

if [ "`uname`" = "Darwin" ]; then
  LIBTDBS_PATH=/usr/local/lib/libtdbs.$SOEXT
else
  # Pre-8.2 standard location for symlink to libtdbs
  LIBTDBS_PATH=/usr/lib/libtdbs.$SOEXT
fi
if [ ! -f $LIBTDBS_PATH ]; then
  # Standard location for libtdbs with 8.2 and later
  LIBTDBS_PATH=/usr/local/trip/sys/lib/libtdbs.$SOEXT
fi

if [ -f $LIBTDBS_PATH ]; then
   HAS_LIBTDBS_FILE=1
   echo "Found $LIBTDBS_PATH"

   LIBTDBS_ACTUAL=`readlink -f $LIBTDBS_PATH`
   if [ "$LIBTDBS_PATH" != "$LIBTDBS_ACTUAL" ]; then
      HAS_LIBTDBS_LINK=1
   fi
fi

if [ $HAS_LIBTDBS_LINK -eq 1 ]; then
   if [ -f "$LIBTDBS_ACTUAL" ]; then
      echo "$LIBTDBS_PATH links to"
      echo "    $LIBTDBS_ACTUAL"
      OLD_TDBS_LIB=`dirname $LIBTDBS_ACTUAL`
      OLD_TRIP_HOME=`dirname $OLD_TDBS_LIB`
      OLD_TDBS_EXE=$OLD_TRIP_HOME/bin

      # NB: The OLD_TDBS_LIB refers to the lib directory with TRIP 8.2
      # and later. With older versions, it refers to the bin directory.
      unset OLD_TDBS_LIB
   fi
fi

if [ $HAS_CONFIG_IN_ROOT -eq 1 ] && [ $HAS_CONFIG_IN_STDLOC -eq 1 ]; then
   echo "Two config files detected. Attempt to resolve conflict."
   HAS_CONFIG_CONFLICT=1

   TDBS_EXE1=`grep "^TDBS_EXE" $LINK_DIR/conf/tdbs.conf | ( read r; echo $r | cut -d= -f2 | tr -d '\r')`
   TDBS_CTL1=`grep "^TDBS_CTL" $LINK_DIR/conf/tdbs.conf | ( read r; echo $r | cut -d= -f2 | tr -d '\r')`

   if [ $HAS_CONFIG_AS_TRIPRC -eq 1 ]; then
      TDBS_EXE2=`grep "^TDBS_EXE" /.triprc | ( read r; echo $r | cut -d= -f2 | tr -d '\r')`
      TDBS_CTL2=`grep "^TDBS_CTL" /.triprc | ( read r; echo $r | cut -d= -f2 | tr -d '\r')`
   else
      TDBS_EXE2=`grep "^TDBS_EXE" /.TRIPrcs | ( read r; echo $r | cut -d= -f2 | tr -d '\r')`
      TDBS_CTL2=`grep "^TDBS_CTL" /.TRIPrcs | ( read r; echo $r | cut -d= -f2 | tr -d '\r')`
   fi

   if [ x"$OLD_TRIP_HOME" != "x"  ]; then
      echo "Choose the config that refer to the TDBS_EXE directory in"
      echo "which the libtdbs shared object file is physically located."

      if [ "$TDBS_EXE1" = "$OLD_TRIP_HOME/bin" ]; then
         HAS_CONFIG_IN_ROOT=0
      elif [ "$TDBS_EXE2" = "$OLD_TRIP_HOME/bin" ]; then
         HAS_CONFIG_IN_STDLOC=0
      fi
   else
      echo "No previous TRIP home detected via libtdbs shared object."
      echo "See if any of the config files refer to an existing TRIP"
      echo "installation directory."
	  
      if [ -f $TDBS_CTL1/CONTROL.BAF ] && [ ! -f $TDBS_CTL2/CONTROL.BAF ]; then
         HAS_CONFIG_IN_ROOT=0
      elif [ ! -f $TDBS_CTL1/CONTROL.BAF ] && [-f $TDBS_CTL2/CONTROL.BAF ]; then
         HAS_CONFIG_IN_ROOT=1
      fi
   fi

   # Report which one we decided to use.
   if [ $HAS_CONFIG_IN_ROOT -eq 0 ]; then
      echo "Found $LINK_DIR/conf/tdbs.conf to be the current TRIP config file"
   elif [ $HAS_CONFIG_IN_STDLOC -eq 0 ] && [ $HAS_CONFIG_AS_TRIPRC -eq 1 ]; then
      echo "Found /.triprc to be the current TRIP config file"
   elif [ $HAS_CONFIG_IN_STDLOC -eq 0 ] && [ $HAS_CONFIG_AS_TRIPRC -eq 0 ]; then
      echo "Found /.TRIPrcs to be the current TRIP config file"
   fi
fi

if [ $HAS_CONFIG_IN_ROOT -eq 1 ] && [ $HAS_CONFIG_IN_STDLOC -eq 1 ]; then

   # Still in conflict. Must ask user to specify correct config file to use.
   echo ""
   echo "Unable to determine which TRIP config file is the current."
   echo "Please specify:"
   echo " [1]  $LINK_DIR/conf/tdbs.conf"
   if [ $HAS_CONFIG_AS_TRIPRC -eq 1 ]; then
      echo " [2]  /.triprc"
   else
      echo " [2]  /.TRIPrcs"
   fi
   echo " [3]  None  -- will not upgrade existing installation"

   doloop=0
   while [ "$doloop" = "0" ]
   do
      echo ""
      echo $C1 "Please specify which existing config is in use [1] $C2"
      read answ
      if [ "x$answ" != "x" ]; then
        printf "\n****** Answer: $answ\n"
      else
        printf "\n****** Answer: default (= 1)\n"
      fi
      case $answ in
      \?)
         echo ""
         echo "Unable to determine which TRIP config file is the current."
         echo "Please specify:"
         echo " [1]  $LINK_DIR/conf/tdbs.conf"
         if [ $HAS_CONFIG_AS_TRIPRC -eq 1 ]; then
            echo " [2]  /.triprc"
         else
            echo " [2]  /.TRIPrcs"
         fi
         echo " [3]  None  -- will not upgrade existing installation"
         echo ""
         ;;
      1|"")
         HAS_CONFIG_IN_ROOT=0
         doloop=1
         ;;
      2)
         HAS_CONFIG_IN_STDLOC=0
         doloop=1
         ;;
      3)
         HAS_CONFIG_IN_STDLOC=0
         HAS_CONFIG_IN_ROOT=0
         doloop=1
         ;;
      esac
   done
fi


##########################################################################
# Make sure that the TRIP daemons (tripd and tripnetd) are stopped
#

# NOTE: This does not remove any user-configured SystemD or init services
# that were defined using different names or a different installation method
# than the "install_services" script. Such services should be removed manually
# before installation of the new version is started.

if [ "$OSNAME" = "Linux" ] &&
   [ "$OLD_TRIP_HOME" != "" ] &&
   [ ! -e /.dockerenv ] && 
   [ -f "$OLD_TDBS_EXE/install_services" ]
then
   $TPATH/sbin/install_services --remove -y
fi


##
# Verify that the PID matches the specified executable by checksumming
# the /proc/$1/[exe|object/a.out] against the actual file we expect the
# process to have been started by.
#
verify_pid()
{
   if [ -f $TPATH/sbin/pidpath ]; then
      EXPATH=`$TPATH/sbin/pidpath $1`
      CSUM1=`cksum $EXPATH`
   elif [ -e /proc/$1/exe ]; then
      CSUM1=`cksum /proc/$1/exe | cut -d" " -f1-2`
   elif [ -e /proc/$1/object/a.out ]; then
      CSUM1=`cksum /proc/$1/object/a.out | cut -d" " -f1-2`
   elif [ -e /proc/$1/execname ]; then
      grep -q $3 /proc/$1/execname
      if [ $? -eq 0 ]; then
         return 0
      fi
   elif [ "$OSNAME" = "Linux" ]; then
      echo "WARNING: Unable to get executable from /proc to verify $2" 1>&2
      return 1
   else
      # No facility for PID verification availablle on this OS
      return 0
   fi
   CSUM2=`cksum $2 | cut -d" " -f1-2`
   if [ "$CSUM1" == "$CSUM2" ]; then
      return 0
   else
      return 1
   fi
}


##
# Get the process ID of the specified process. This function may find
# more than one PID if there is multiple processes whose ps -ef output
# contains the specified name. To avoid returning the wrong one, the 
# caller must provide the fully qualified path to the binary that the
# PID is expected to use.
#
get_pidof()
{
   PIDOF_CMD=`which pidof 2> /dev/null`
   if [ "$PIDOF_CMD" = "" ]; then
      ps -ef | grep "$1" | grep -v ttymon | grep -v grep | awk '{print $2}' | while read ALT_PIDOF_VALUE; do
         if [ "$2" == "" ]; then
            # NB: This special case for omission of $2 may not return
            # the correct pid value. So, always define $2 ....
            echo $ALT_PIDOF_VALUE
            return 0
         elif verify_pid $ALT_PIDOF_VALUE $2 $1 ; then
            echo $ALT_PIDOF_VALUE
            return 0
         fi
      done
   else
      pidof $1 | awk '{print $1}'
   fi
}


##
# Check if a process is running based on info from /proc
#
is_running()
{
   if [ -d /proc/$1 ]; then
      return 0
   else
      return 1
   fi
}


##
# Wait for up to ten seconds for a process to exit.
#
waitpid()
{
   WPID=$1
   TIMELEFT=10
   while is_running $WPID
   do
      if [ $TIMELEFT -eq 0 ]; then
         return 1
      fi
      TIMELEFT=`expr $TIMELEFT - 1`
      sleep 1s
   done
   return 0
}


# For non-Linux operating systems and for older Linux installations, use the
# traditional, more brute-force way of stopping tripd and tripnetd.
#
echo ""
RUN_TRIPD=N
unset PID_TRIPD
if [ -d "$OLD_TRIP_HOME" ]; then
   PID_TRIPD=`get_pidof tripd $OLD_TRIP_HOME/bin/tripd`
fi
if [ "x$PID_TRIPD" != "x" ]; then
   echo "The TRIP daemon (tripd) is running. Trying to stop it now!"
   kill -TERM $PID_TRIPD
   if ! waitpid $PID_TRIPD ; then
      kill -KILL $PID_TRIPD
   fi
   if [ $? -eq 0 ]; then
      echo "The TRIP daemon (tripd) has been stopped."
      RUN_TRIPD=Y
   else
      echo ""
      echo "****** The TRIP daemon (tripd) is still running."
      echo "       It must be stopped before the installation."
      echo "Exiting the installation procedure"
      echo ""
      umask $OUMASK
      touch $TPATH/trip-system-install-abort.ctl
      exit 1
   fi
elif [ "$OSNAME" != "Linux" ]; then
   echo "The TRIP daemon (tripd) was not running."
fi

RUN_TRIPNETD=N
unset PID_TRIPNETD
if [ -d "$OLD_TRIP_HOME" ]; then
   PID_TRIPNETD=`get_pidof tripnetd $OLD_TRIP_HOME/bin/tripnetd`
fi
if [ "x$PID_TRIPNETD" != "x" ]; then
   echo "The TRIPnet daemon (tripnetd) is running. Trying to stop it now!"
   kill -TERM $PID_TRIPNETD
   if ! waitpid $PID_TRIPNETD ; then
      kill -KILL $PID_TRIPNETD
   fi
   if [ $? -eq 0 ]; then
      echo "The TRIPnet daemon (tripnetd) has been stopped."
      RUN_TRIPNETD=Y
   else
      echo ""
      echo "****** The TRIPnet daemon (tripned) is still running."
      echo "       It must be stopped before the installation."
      echo "Exiting the installation procedure"
      echo ""
      umask $OUMASK
      touch $TPATH/trip-system-install-abort.ctl
      exit 1
   fi
elif [ "$OSNAME" != "Linux" ]; then
   echo "The TRIPnet daemon (tripnetd) was not running."
fi


##########################################################################
# Starting the TRIP daemons (tripd and tripnetd) at end of installation.
#

yesno_help_tripdstart()
{
   echo ""
   echo "As long as the TRIP daemon isn't started, TRIP is unavailable for all"
   echo "users. You may want to control at what time TRIP is made available."
   echo "In that case you must start the TRIP daemon manually. Please refer to"
   echo "the Installation Guide for details."
   echo ""
}

yesno_help_tripnetdstart()
{
   echo ""
   echo "As long as the TRIPnet daemon isn't started, TRIP is unavailable for"
   echo "remote users. You may want to control at what time TRIP is made available."
   echo "In that case you must start the TRIP daemon manually. Please refer to"
   echo "the Installation Guide for details."
   echo ""
}

yesno_help_systemd()
{
   echo ""
   echo "Starting tripd and tripnet/tbserver automatically via systemd makes sure"
   echo "that TRIP is always running properly, even after a reboot. Even if you"
   echo "answer no at this point, you can run the install_services script at any"
   echo "time to accomplish this."
   echo ""
   echo "As long as the TRIP daemons are not started, TRIP will be unavailable"
   echo "users. You may want to control at what time TRIP is made available."
   echo "Please refer to the Installation Guide for further details."
   echo ""
}

yesno_help_init()
{
   echo ""
   echo "Starting tripd and tripnet/tbserver automatically via init makes sure"
   echo "that TRIP is always running properly, even after a reboot. Even if you"
   echo "answer no at this point, you can run the install_services script at any"
   echo "time to accomplish this."
   echo ""
   echo "As long as the TRIP daemons are not started, TRIP will be unavailable"
   echo "users. You may want to control at what time TRIP is made available."
   echo "Please refer to the Installation Guide for further details."
   echo ""
}

START_VIA_SYSTEMD=N
START_VIA_INIT=N
START_VIA_XINETD=N
START_VIA_INETADM=N
START_TRIPD=N
START_TRIPNETD=N

INITPROC=
if [ "$OSNAME" = "Linux" ]; then
   INITPROC=`ps --no-headers -o comm 1 2>/dev/null`
fi
if [ "$INITPROC" = "systemd" ]; then
   echo "The TRIP daemons can be installed for automatic start via systemd."
   if yesno "Do you wish to start the TRIP daemons via systemd?" N yesno_help_systemd
   then
      START_VIA_SYSTEMD=Y
   fi
elif [ "$INITPROC" = "init" ]; then
   echo "The TRIP daemons can be installed for automatic start via init."
   if yesno "Do you wish to start the TRIP daemons via init?" N yesno_help_init
   then
      START_VIA_INIT=Y
   else
      START_VIA_INIT=N
   fi
fi
echo ""

yesno_help_xinetd()
{
   echo ""
   echo "Starting providing network session access to TRIP via xinetd is"
   echo "an option since xinetd is already installed on this system. The"
   echo "alternative is to utilize the TRIPnet daemon (tripnetd) instead."
   echo ""
}

if [ "$OSNAME" = "Darwin" ]; then

   echo ""
   echo "The TRIP daemon (tripd) and the TRIPnet daemon (tripnetd) will not"
   echo "be started by this installer. Please start tripd manually as the"
   echo "operating system user that you intend to use with TRIPsystem."
   echo ""

elif [ "$START_VIA_SYSTEMD" = "N" ] && [ "$START_VIA_INIT" = "N" ]; then

   echo "The TRIP daemon (tripd) can be started at the end of the installation."
   echo "Note that this doesn't install tripd for automatic start at boot."
   if yesno "Do you wish to start tripd?" $RUN_TRIPD yesno_help_tripdstart
   then
      START_TRIPD=Y
   else
      START_TRIPD=N
   fi
   echo ""

   if [ "$OSNAME" = "Linux" ]; then

      if [ "$RUN_TRIPNETD" = "N" ] && $TPATH/sbin/isinstalled xinetd ; then

         echo "PLEASE NOTE! The TRIPnet daemon (tripnetd) can be started"
         echo "       instead of using the internet services daemon (x)inetd."
         echo "       Please refer to the Installation Guide for more details."
         echo ""

         # Is tbserver already configured for start via xinetd? If so,
         # just assume we'll continue doing that. If not, ask if this
         # xinetd should be used.

         if [ -f /etc/xinetd.conf ]; then
            XCOND=`sed -n 's/^[       ]*includedir[   ]*\(.*\)/\1/p' /etc/xinetd.conf`
            if [ "x$XCOND" = "x" ]; then
               XCOND=/etc/xinetd.d
            fi
            XCONF=$XCOND/pctdbs
            if [ -f $XCONF ]; then
               START_VIA_XINETD=Y
            elif yesno "Do you wish to launch tbserver via xinetd?" Y yesno_help_xinetd ; then
               START_VIA_XINETD=Y
            fi 
         fi

      fi
   fi

   if [ "$START_VIA_XINETD" = "N" ]; then

      echo "The TRIPnet daemon can be started at the end of the installation."
      echo "Note that this doesn't install tripnetd for automatic start at boot."
      if yesno "Do you wish to start tripnetd at the end of installation?" $RUN_TRIPNETD yesno_help_tripnetdstart
      then
         START_TRIPNETD=Y
      fi
      echo ""

   fi

   if [ "$OSNAME" = "SunOS" ] && [ "$START_TRIPNETD" = "N" ]; then

      # On Solaris, we always configure tbserver via inetadm if manual
      # tripnetd operation has not been selected.

      START_VIA_INETADM=Y 

   fi
fi


if [ "$START_VIA_SYSTEMD" = "Y" ]; then
   touch $TPATH/trip-system-install-start-systemd.ctl
elif [ -f $TPATH/trip-system-install-start-systemd.ctl ]; then
   rm -f $TPATH/trip-system-install-start-systemd.ctl
fi
if [ "$START_VIA_INIT" = "Y" ]; then
   touch $TPATH/trip-system-install-start-init.ctl
elif [ -f $TPATH/trip-system-install-start-init.ctl ]; then
   rm -f $TPATH/trip-system-install-start-init.ctl
fi
if [ "$START_VIA_XINETD" = "Y" ]; then
   touch $TPATH/trip-system-install-start-xinetd.ctl
elif [ -f $TPATH/trip-system-install-start-xinetd.ctl ]; then
   rm -f $TPATH/trip-system-install-start-xinetd.ctl
fi
if [ "$START_VIA_INETADM" = "Y" ]; then
   touch $TPATH/trip-system-install-start-inetadm.ctl
elif [ -f $TPATH/trip-system-install-start-inetadm.ctl ]; then
   rm -f $TPATH/trip-system-install-start-inetadm.ctl
fi
if [ "$START_TRIPD" = "Y" ]; then
   touch $TPATH/trip-system-install-start-tripd.ctl
elif [ -f $TPATH/trip-system-install-start-tripd.ctl ]; then
   rm -f $TPATH/trip-system-install-start-tripd.ctl
fi
if [ "$START_TRIPNETD" = "Y" ]; then
   touch $TPATH/trip-system-install-start-tripnetd.ctl
elif [ -f $TPATH/trip-system-install-start-tripnetd.ctl ]; then
   rm -f $TPATH/trip-system-install-start-tripnetd.ctl
fi


##########################################################################
# Upgrade or new installation
#
# A link to libtdbs.so from /usr/lib[64] is kept by all Solaris versions
# of TRIP. This is also the case for Linux versions of TRIP up to v8.1.
# TRIP 8.2 and later on Linux configures the system's dynamic linker with
# the appropriate lib directory instead.
#

OLDRC=""
if [ $HAS_CONFIG_IN_ROOT -eq 1 ]; then
  if [ $HAS_CONFIG_AS_TRIPRC -eq 1 ]; then
     OLDRC=/.triprc
  else
     OLDRC=/.TRIPrcs
  fi
elif [ $HAS_CONFIG_IN_STDLOC -eq 1 ]; then
#  Follow Link!!!
   RCLNK=`readlink -f $LINK_DIR/conf`
   OLDRC=$RCLNK/tdbs.conf
fi
if [ "x$OLDRC" != "x" ]; then
   echo "Found old TRIP configuration file: $OLDRC"
fi

if [ -e /usr/local/trip/sys/lib/libtdbs.$SOEXT ]; then
   UDIR=`readlink /usr/local/trip/sys/lib`
   ULIB=$UDIR/libtdbs.$SOEXT
   ULNK=
   NEWUSR=U
elif [ -h /usr/lib/libtdbs.$SOEXT ]; then
   UDIR=/usr/lib
   ULIB=$UDIR/libtdbs.$SOEXT
   ULNK=`readlink -f $ULIB`
   NEWUSR=U
elif [ -h /usr/local/lib/libtdbs.$SOEXT ]; then
   UDIR=/usr/local/lib
   ULIB=$UDIR/libtdbs.$SOEXT
   ULNK=`readlink -f $ULIB`
   NEWUSR=U
else
   ULIB=""
   NEWUSR=N
fi


# When the install previously has been aborted due to failure, there may not
# be a previous libtdbs link to be found. The below condition is a fallback
# to deal with that situation.

if [ -e /usr/local/trip/sys/conf ]; then
  XCFG=`readlink /usr/local/trip/sys/conf 2>/dev/null`
  if [ "$XCFG" != "" ] && [ -d "$XCFG" ]; then
     ULNK=`dirname $XCFG 2>/dev/null`/lib/libtdbs.so
     if [ ! -f "$ULNK" ]; then
        # For upgrades from 8.1 and older
        ULNK=`dirname $XCFG 2>/dev/null`/bin/libtdbs.so
     fi
     if [ ! -f "$ULNK" ]; then
        NEWUSR=U
        UDIR=`dirname $ULNK`
     fi
  fi
  unset XCFG
fi


if [ "$NEWUSR" = "U" ]; then
   echo ""
   echo "Found existing TRIP kernel library in $UDIR"
   if [ "$ULNK" != "" ]; then
      echo "linking to: $ULNK"
   fi
   doloop=0
   while [ "$doloop" = "0" ]
   do
      echo ""
      echo $C1 "Is this a [N]ew installation or an [U]pgrade? [$NEWUSR] $C2"
      read answ
      if [ "x$answ" != "x" ]; then
         printf "\n****** Answer: $answ\n"
      else
         printf "\n****** Answer: default [= $NEWUSR]\n"
      fi
      case $answ in
         \?)
            echo ""
            echo ""
            echo "   Enter either of the following: "
            echo ""
            echo "         N  : new installation"
            echo ""
            echo "         U  : upgrade installation"
            echo ""
            if [ "$NEWUSR" = "N" ]; then
               echo "   The default is a NEW installation (N)"
            else
               echo "   The default is an UPGRADE (U)"
            fi
            echo ""
            NEWT=Q
            ;;
         U|u)
            NEWT=U
            ;;
         N|n)
            NEWT=N
            ;;
         "")
            NEWT=$NEWUSR
            ;;
      esac
      if [ "$NEWT" = "$NEWUSR" ]; then
         doloop=1
      else
         if [ "$NEWT" != "Q" ]; then
            NEWCON=Y
            if yesno "Are you sure?" $NEWCON ; then
               NEWC=Y
            else
               NEWC=N
            fi
            if [ "$NEWC" = "$NEWCON" ]; then
               doloop=1
            fi
         fi
      fi
   done
else
  NEWT=N
fi
    

qrcs()
{    
   RCSNAME=$2
   STRIPNIL=$3
   RCSVALUE="<nil>"

   # The queryrcs tool may not work if the (old) installation is
   # broken or incomplete. Figure out if a workaround is needed.
   USEFALLBACK=1
   if [ $HAS_CONFIG_CONFLICT -eq 0 ]; then
      if [ -f $1/queryrcs ]; then
         $1/queryrcs -? >/dev/null 2>&1
         if [ $? -eq 0 ]; then
            USEFALLBACK=0
         fi
      fi
   fi

   if [ $HAS_CONFIG_CONFLICT -eq 0 ] && [ $USEFALLBACK -eq 0 ]; then
      RCSVALUE=`$1/queryrcs $RCSNAME | tr -d "\""`
   fi
   if [ -f "$OLDRC" ] && [ "$RCSVALUE" = "<nil>" ]; then    	  
      RCSVALUE=`grep "^$RCSNAME" $OLDRC | ( read r; echo $r | cut -d= -f2 | tr -d '\r')`
   fi
   if [ "$STRIPNIL" != "Y" ] || [ "$RCSVALUE" != "<nil>" ]; then
      echo $RCSVALUE
   fi
}

# Remove an item from a comma-separated list (such as TDBS_ASELIBS)
removeitem()
{
   echo "$1" | tr ',' '\n'|grep -v "^$2"|tr '\n' ','|sed 's/,$//g'
}


##########################################################################
# Set various config defaults based on previous version, if any.
#

echo ""
if [ "$NEWT" = "N" ]; then
   echo "Proceeding with a new installation of TRIP"
   OLDEXE=""
   OLDCTL="" 
   OLDACC="" 
   OLDACCFLG="" 
   OLDSYS="" 
   OLDPRC=""
   OLDLANG="" 
   OLDCHARS=""
   OLDBASES=""
else
   echo "Proceeding with an upgrade of TRIP"

   if [ "$ULIB" = "" ]; then
      echo ""
      echo "INTERNAL INSTALLER ERROR"
      echo ""
      echo "    Upgrade selected, but no previous TRIP kernel library was found."
      echo "    Please contact TRIP support for assistance."
      echo ""
      echo "Installation aborted."
      echo ""
      touch $TPATH/trip-system-install-abort.ctl
      exit 1
   fi

   XLIBDIR=$(dirname `readlink -f $ULIB 2>/dev/null` 2>/dev/null)
   OLDEXE=`dirname $XLIBDIR`/bin

   if [ ! -f "$OLDEXE/queryrcs" ]; then 
      echo ""
      echo "UNABLE TO UPGRADE"
      echo ""
      echo "    The previous TRIP installation is incomplete or corrupted."
      echo "    Restart the installer and choose to perform a new install."
      echo "    You must migrate any previous databases manually. Contact"
      echo "    TRIP support for assistance."
      echo ""
      echo "Installation aborted."
      echo ""
      touch $TPATH/trip-system-install-abort.ctl
      exit 1
   fi

   # Save the old variables
   if [ "$OLDRC" != "" ]; then
      OLDCTL=`qrcs "$OLDEXE" TDBS_CTL`
      echo $OLDCTL | grep "\<nil\>" > /dev/null
      if [ $? -eq 0 ]; then
        OLDCTL=""
      fi
      OLDACC=`qrcs "$OLDEXE" TDBS_ACCDIR`
      echo $OLDACC | grep "\<nil\>" > /dev/null
      if [ $? -eq 0 ]; then
        OLDACC=""
      fi
      OLDACCFLG=`qrcs "$OLDEXE" TDBS_ACCFLG`
      echo $OLDACCFLG | grep "\<nil\>" > /dev/null
      if [ $? -eq 0 ]; then
        OLDACCFLG=""
      fi
      OLDSYS=`qrcs "$OLDEXE" TDBS_SYS`
      echo $OLDSYS | grep "\<nil\>" > /dev/null
      if [ $? -eq 0 ]; then
        OLDSYS=""
      fi
      OLDPRC=`qrcs "$OLDEXE" TDBS_PRC`
      echo $OLDPRC | grep "\<nil\>" > /dev/null
      if [ $? -eq 0 ]; then
        OLDPRC=""
      fi
      OLDLANG=`qrcs "$OLDEXE" TDBS_LANG`
      echo $OLDLANG | grep "\<nil\>" > /dev/null
      if [ $? -eq 0 ]; then
        OLDLANG=""
      fi
      OLDCHARS=`qrcs "$OLDEXE" TDBS_CHARS`
      echo $OLDCHARS | grep "\<nil\>" > /dev/null
      if [ $? -eq 0 ]; then
        OLDCHARS=""
      fi
      OLDBASES=`qrcs "$OLDEXE" TDBS_BASES`
      echo $OLDBASES | grep "\<nil\>" > /dev/null
      if [ $? -eq 0 ]; then
        OLDBASES=""
      fi
   fi
fi

# Change install name for private libraries on MacOS
if [ "$OSNAME" = "Darwin" ]; then
   OPWD=`pwd`
   cd $TPATH/lib
   ls *.so *.dylib | while read F; do install_name_tool -id $TPATH/lib/$F $F; done
   cd $OPWD

   # Change modcon's libtdbs dependency so that it will work correctly during
   # the upgrade check further below.
   install_name_tool -change /usr/local/trip/sys/lib/libtdbs.dylib $TPATH/lib/libtdbs.dylib $TPATH/bin/modcon
fi


##########################################################################
# Check if the migration path is valid.  
#
SHOULD_MIGRATE_CONTROL=Y
if [ "$OLDCTL" != "" ] && [ -f "$OLDCTL/CONTROL.BAF" ]; then
   export OLDCTL
   TDBS_LIB_INSTALL=$TPATH/lib $TPATH/bin/modcon --check --quiet -t "$TPATH/sys/P_CONTROL.BAF" -s "$OLDCTL/CONTROL.BAF"
   if [ $? -ne 1 ]; then
      echo "WARNING: You are attempting an unsupported migration path."
      echo ""
      echo "You are advised to abort this installation. If you are sure you wish"
      echo "to continue anyway, you should create a full backup of your CONTROL"
      echo "database files first."
      echo ""
      if yesno "Do you wish to abort?" Y ; then
         echo "Installation aborted."
         echo ""
         touch $TPATH/trip-system-install-abort.ctl
         exit 1
      else
         echo "WARNING: Continuing installation with unsupported CONTROL migration path!"
      fi
   else
      TDBS_LIB_INSTALL=$TPATH/lib $TPATH/bin/modcon --check --needs-upgrade --quiet -f "$OLDCTL/CONTROL.BAF"
      if [ $? -eq 42 ]; then
         # The CONTROL is already up to date
         SHOULD_MIGRATE_CONTROL=N
      fi
   fi
fi


##########################################################################
# Check if this is a new or upgrade installation in the same directory
# structure as the previously installed TRIP version.
#
# This is not a problem but as it is not a common use case, this is
# emitted as a warning of sorts.
#

if [ "$TPATH/bin" = "$OLDEXE" ]; then
   echo ""
   echo "Upgrade installed in the same directory as current installation"
fi


##########################################################################
# For a new installation or an upgrade installed in the same directory
# structure.
#

if ([ "$NEWT" = "N" ] || [ "$TPATH/bin" = "$OLDEXE" ]); then

   # set up file ownership (user)

   doloop=0
   while [ "$doloop" = "0" ]
   do
      echo ""
      echo $C1 "Which user should own the TRIP files? [root] $C2"
      read answ
      if [ "x$answ" != "x" ]; then
         printf "\n****** Answer: $answ\n"
      else
         printf "\n****** Answer: default [= root]\n"
      fi
      case $answ in
      \?)
         echo ""
         echo ""
         echo "   Enter the name of the user who should own all files"
         echo "   and directories in the $VERS_DIR directory structure."
         echo ""
         echo "   The default is root."
         echo ""
         ;;
      *)
         if [ "$answ" = "" ]; then
            OWNER=root
         else
            OWNER=$answ
         fi
         doloop=1
         ;;
      esac
   done

   # set up file ownership (group)

   doloop=0
   while [ "$doloop" = "0" ]
   do
      echo ""
      echo $C1 "Which group should own the TRIP files? $C2"
      read answ
      printf "\n****** Answer: $answ\n"
      case $answ in
      \?)
         echo ""
         echo ""
         echo "   Enter the name of the group that should own all files"
         echo "   and directories in the $VERS_DIR directory structure."
         echo ""
         ;;
      "")
         ;;
      *)
         GROUP=$answ
         doloop=1
         ;;
      esac
   done

   # Set up the user as which to use to run the tbserver processes. This
   # only applies if tbserver is to be launched via xinetd or inetadm.

   if [ "$START_VIA_XINETD" = "Y" ] ||
      [ "$START_VIA_INETADM" = "Y" ]
   then
      doloop=0
      while [ "$doloop" = "0" ]
      do
         echo ""
         echo $C1 "Which user should run the TRIPserver (tbserver)? [root] $C2"
         read answ
         if [ "x$answ" != "x" ]; then
            printf "\n****** Answer: $answ\n"
         else
            printf "\n****** Answer: default [= root]\n"
         fi
         case $answ in
         \?)
            echo ""
            echo ""
            echo "   Enter the name of the user who should run the TRIPserver."
            echo "   Even if any user can be chosen for this, it is recommended"
            echo "   to choose root as that user."
            echo ""
            echo "   The default is root."
            echo ""
            ;;
         *)
            if [ "$answ" = "" ]; then
               TBUSER=root
               doloop=1
            else
               grep -q ^$answ /etc/passwd
               if [ $? -ne 0 ]; then
                  echo ""
                  echo "ERROR: User $answ is not known. Please specify another."
                  echo ""
               else
                  TBUSER=$answ
                  doloop=1
               fi
            fi
            ;;
         esac
      done

      TBGROUP=$GROUP
   fi

   PREV=""


##########################################################################
# Upgrade installation (in different directory structure)
#

else

   # Get file ownership (user + group) from previous installation.

   PREV="(copied from previous installation)"
   OWNER=`ls -l $OLDEXE/trip | tr -s ' ' | cut -d" " -f3`
   GROUP=`ls -l $OLDEXE/trip | tr -s ' ' | cut -d" " -f4`

   # Define the user who should run tbserver - copied from previous version
   TBUSER=""
   TBGROUP=$GROUP
fi


# The user and group that tripd and tripnetd should run as
# when started under systemd or init. These values default
# to the owner and group of the files.

if [ "$START_VIA_SYSTEMD" = "Y" ] || [ "$START_VIA_INIT" = "Y" ]; then
   doloop=0
   while [ "$doloop" = "0" ]
   do
      echo ""
      echo $C1 "Which user should run the TRIP daemons? [$OWNER] $C2"
      read answ
      if [ "x$answ" != "x" ]; then
         printf "\n****** Answer: $answ\n"
      else
         printf "\n****** Answer: default [= $OWNER]\n"
      fi
      case $answ in
      \?)
         echo ""
         echo "The named user will run the TRIP daemon processes tripd and tripnetd"
         echo "as well as any of their child processes (e.g. tbserver)."
         echo ""
         echo "The default is $OWNER."
         echo ""
         ;;
      *)
         if [ "$answ" = "" ]; then
            TBUSER=$OWNER
            doloop=1
         else
            grep -q ^$answ /etc/passwd
            if [ $? -ne 0 ]; then
               echo ""
               echo "ERROR: User $answ is not known. Please specify another."
               echo ""
            else
               TBUSER=$answ
               doloop=1
            fi
         fi
         ;;
      esac
   done

   doloop=0
   while [ "$doloop" = "0" ]
   do
      echo ""
      echo $C1 "Which group should run the TRIP daemons? [$GROUP] $C2"
      read answ
      if [ "x$answ" != "x" ]; then
         printf "\n****** Answer: $answ\n"
      else
         printf "\n****** Answer: default [= $GROUP]\n"
      fi
      case $answ in
      \?)
         echo ""
         echo "The named group will be the group associated with the TRIP"
         echo "daemon processes tripd and tripnetd as well as any of their"
         echo "child processes (e.g. tbserver)."
         echo ""
         echo "The system administrator must give this group read and write"
         echo "access to all TRIP database directories and files. In addition,"
         echo "all local operating system users who will run trip processes"
         echo "must be assigned to this group (this minimally applies to $TBUSER)."
         echo ""
         echo "The relevant files are all fils associated with TRIP databases"
         echo "(BAF/BIF/VIF/LOG) as well as system-wide accounting files."
         echo ""
         ;;
      *)
         if [ "$answ" = "" ]; then
            TBGROUP=$GROUP
            doloop=1
         else
            grep -q ^$answ /etc/group
            if [ $? -ne 0 ]; then
               echo ""
               echo "ERROR: Group $answ is not known. Please specify another."
               echo ""
            else
               TBGROUP=$answ
               doloop=1
            fi
         fi
         ;;
      esac
   done
fi

echo "TBUSER=$TBUSER" > $TPATH/service-args.ctl
echo "TBGROUP=$TBGROUP" >> $TPATH/service-args.ctl


# New installation

if [ "$NEWT" = "N" ]; then

   ##########################################################################
   # Determine the system language
   #

   doloop=0
   while [ "$doloop" = "0" ]
   do
      echo ""
      echo "What is the default language when running TRIP?"
      echo ""
      echo "[E]nglish / [S]wedish / [G]erman / [F]innish / [C]hinese / [N]orwegian [E] $C2"
      read answ
      if [ "x$answ" != "x" ]; then
         printf "\n****** Answer: $answ\n"
      else
         printf "\n****** Answer: default [= E]\n"
      fi
      case $answ in
         \?)
            echo ""
            echo ""
            echo "   Valid language choices are: "
            echo ""
            echo "        E : English "
            echo "        S : Swedish "
            echo "        G : German "
            echo "        F : Finnish "
            echo "        C : Chinese "
            echo "        N : Norwegian"
            echo ""
            echo "   The default language is English (E) "
            echo ""
            ;;
         S|s)
            TDBS_LANG=SWE
            TDBS_CHARS=LA1
            doloop=1
            ;;
         G|g)
            TDBS_LANG=GER
            TDBS_CHARS=LA1
            doloop=1
            ;;
         F|f)
            TDBS_LANG=FIN
            TDBS_CHARS=LA1
            doloop=1
            ;;
         C|c)
            TDBS_LANG=CHI
            TDBS_CHARS=CHI
            doloop=1
            ;;
         N|n)
            TDBS_LANG=NOR
            TDBS_CHARS=LA1
            doloop=1
            ;;
         E|e|"")
            TDBS_LANG=ENG
            TDBS_CHARS=LA1
            doloop=1
            ;;
      esac
   done

   echo ""
   echo "The TRIP language selected was $TDBS_LANG"
   echo "( Setting the character set to $TDBS_CHARS )"

   export TDBS_LANG TDBS_CHARS

   # TODO: Ask for default user database location
   TDBS_BASES=$SHARED_STATE_DIR/db ; export TDBS_BASES


# Upgrade installation

else

   if [ -f "$OLD_TDBS_EXE/tbserver" ]; then
      if [ "stat $OLD_TDBS_EXE/tbserver -c %a| cut -c1-2" = "27" ]; then
         echo ""
         echo "UPGRADE NOTICE"
         echo "--------------"
         echo "Your previous installation appears to have the Set-Group-Id bit set"
         echo "on some of the TRIP binaries. This used to be default but is no longer"
         echo "recommended. The Set-Group-Id bit will not be set by this installer."
         echo ""
         echo "IMPORTANT: You should set the file permissions on the TRIP database files"
         echo "so that all operating system users that run the TRIP processes (tripd,"
         echo "tripnetd, trip (classic), tbserver, etc) have proper read/write access."
         echo ""
         echo "[Press enter to continue]"
         read answ
      fi
   fi

   echo ""
   if [ "$OLDLANG" != "" ]; then
      TDBS_LANG=$OLDLANG ; export TDBS_LANG
      echo "The TRIP language is set to $TDBS_LANG"
   fi

   if [ "$OLDCHARS" != "" ]; then
      TDBS_CHARS=$OLDCHARS ; export TDBS_CHARS
      echo "The TRIP character set is set to $TDBS_CHARS"
   fi

   if [ "$OLDBASES" != "" ]; then
      TDBS_BASES=$OLDBASES ; export TDBS_BASES
      echo "The default location for TRIP databases is set to $TDBS_BASES"
   else
      # TODO: Ask for default user database location
      TDBS_BASES=$SHARED_STATE_DIR/db; export TDBS_BASES
      echo "The default location for TRIP databases is set to $TDBS_BASES"
   fi

fi


# Make sure that TDBS_BASES exists
mkdir -p $TDBS_BASES


##########################################################################
# set up directory and file protections
#

echo ""
echo "Setting TRIP file protections" 

chmod 755 $TPATH ase bin demo include lib sys trm
chmod 755 share share/conf
if [ -e share/init ]; then
chmod 755 share/init
fi
if [ -e share/systemd ]; then
chmod 755 share/systemd
fi
chmod 644 ase/*
chmod 755 bin/*
chmod 664 demo/*
chmod 644 include/*
chmod 755 lib/*
chmod 644 trm/*
chmod ug+rwx $TDBS_BASES
chmod o+rx $TDBS_BASES

# change file ownership (user + group)

echo "Setting TRIP file ownership to:"
echo "        \"$OWNER:$GROUP\" $PREV" 

chown -hR $OWNER:$GROUP $TPATH
if [ $? -eq 0 ]; then
   echo "Giving user \"$OWNER\" ownership of the TRIP files"
   echo "Giving group \"$GROUP\" group ownership of the TRIP files"
else
   echo "****** Could not change the ownership of installed files!"
   echo "Exiting the installation procedure"
   echo ""
   umask $OUMASK
   touch $TPATH/trip-system-install-abort.ctl
   exit 1
fi

chown $OWNER:$GROUP $TDBS_BASES

echo ""
echo "The user who should run TRIPserver is:"
echo "    $TBUSER $PREV"


##########################################################################
# Adjust libtdbs links and ldconfig setup
#

# Remove old libtdbs links
pushd $TPATH/bin
if [ "$OSNAME" = "Darwin" ]; then
   KERNLIB=`ls libtdbs.dylib 2> /dev/null`
   KPATH=/usr/local/lib
else
   KERNLIB=`ls libtdbs.?? 2> /dev/null`
   KPATH=/usr/lib
fi
popd
if [ -f $KPATH/$KERNLIB ]; then rm -f $KPATH/$KERNLIB; fi
if [ -f /usr/lib64/$KERNLIB ]; then rm -f /usr/lib64/$KERNLIB; fi
if [ -f /usr/lib/64/$KERNLIB ]; then rm -f /usr/lib/64/$KERNLIB; fi

# Configure ld.so.conf if possible on Linux
LIBTDBS_LINKED=0
if [ "$OSNAME" = "Linux" ] && [ -f /etc/ld.so.conf ]; then

   LIBTDBS_LINKED=0
   LDSOINC=`grep ^include /etc/ld.so.conf 2>/dev/null|cut -d" " -f2- |rev|cut -d/ -f2-|rev`
   if [ "$LDSOINC" != "" ]; then
      pushd /etc > /dev/null 2>&1
      cd $LDSOINC 2> /dev/null
      if [ $? -eq 0 ]; then
         LDSOINC=`pwd`
      else
         unset LDSOINC
      fi
      popd > /dev/null 2>&1
   fi

   if [ "$LDSOINC" != "" ] && [ -d "$LDSOINC" ]; then
      cp share/conf/tripsystem-libpath.conf $LDSOINC/
   else
      # Must configure /etc/ld.so.conf itself
      grep -q '/usr/local/trip/sys/lib' /etc/ld.so.conf
      if [ $? -ne 0 ]; then
         echo "" >> /etc/ld.so.conf
         echo /usr/local/trip/sys/lib >> /etc/ld.so.conf
      fi
   fi

   LDCONFIG=`which ldconfig 2>/dev/null`
   if [ "$LDCONFIG" = "" ]; then
      LDCONFIG=/sbin/ldconfig
   fi
   $LDCONFIG
   if [ $? -eq 0 ]; then
      echo ""
      echo "Path to libtdbs.so added to ld.so.conf"
      LIBTDBS_LINKED=1
   else
      echo ""
      echo "WARNING: ldconfig failed"
      echo "         Falling back on symbolic link from /usr/lib"
   fi

fi

# We're not doing any libtdbs linking on macOS
if [ "$OSNAME" = "Darwin" ]; then
   LIBTDBS_LINKED=1
fi

if [ -e /usr/lib/libtdbs.so ]; then
   rm -f /usr/lib/libtdbs.so
fi
if [ -e /usr/lib64/libtdbs.so ]; then
   rm -f /usr/lib64/libtdbs.so
fi

if [ $LIBTDBS_LINKED -eq 0 ]; then

   # On non-Linux platforms and if the runtime linker config is not 
   # possible to access, add links to the standard /usr/lib directory
   # instead.

   LINK_TARGET_DIR=/usr/lib
   if [ ! -w $LINK_TARGET_DIR ]; then
      LINK_TARGET_DIR=/usr/local/lib
      if [ ! -w $LINK_TARGET_DIR ]; then
         echo "WARNING: Unable to create libtdbs.$SOEXT link"
         echo "         The /usr tree is not writable."
         echo "         Some TRIP applications may not work properly."
         LINK_TARGET_DIR=""
      fi
   fi

   if [ $LINK_TARGET_DIR != "" ]; then

      echo ""
      echo "Creating link from $LINK_TARGET_DIR/libtdbs.$SOEXT to:"
      echo "                   $TPATH/lib/libtdbs.$SOEXT"
      ln -s -f $TPATH/lib/libtdbs.$SOEXT $LINK_TARGET_DIR/libtdbs.$SOEXT

      if [ -d /usr/lib64 ]; then
         echo "Creating link from /usr/lib64/libtdbs.$SOEXT to:"
         echo "                   $TPATH/lib/libtdbs.$SOEXT"
         ln -s -f $TPATH/lib/libtdbs.$SOEXT /usr/lib64/libtdbs.$SOET
      fi

   fi

fi


##########################################################################
# Set up the shared state directories for TRIP
#

mkdir -p $SHARED_STATE_DIR/db
mkdir -p $SHARED_STATE_DIR/ctl
mkdir -p $SHARED_STATE_DIR/log/acc
mkdir -p $SHARED_STATE_DIR/log/sys

dirchmod()
{
   chmod ug+rwx $1
   chmod o+rx $1
}

dirchmod $SHARED_STATE_DIR/db
dirchmod $SHARED_STATE_DIR/ctl
dirchmod $SHARED_STATE_DIR/log
dirchmod $SHARED_STATE_DIR/log/acc
dirchmod $SHARED_STATE_DIR/log/sys

chown -hR $OWNER:$GROUP $SHARED_STATE_DIR


##########################################################################
# Set the environment variables
#

TDBS_CTL=$SHARED_STATE_DIR/ctl ; export TDBS_CTL
TDBS_SYS=$TPATH/sys ; export TDBS_SYS
TDBS_EXE=$TPATH/bin ; export TDBS_EXE
TDBS_SBIN=$TPATH/sbin ; export TDBS_SBIN
TDBS_PRC=$TPATH/prc ; export TDBS_PRC
TDBS_TRM=$TPATH/trm ; export TDBS_TRM
TDBS_LOG=$SHARED_STATE_DIR/log/sys ; export TDBS_LOG
TDBS_SCRATCH=$SHARED_STATE_DIR/log/sys; export TDBS_SCRATCH
TDBS_BATCH=dummy ; export TDBS_BATCH
TRIP_DEMO=$TPATH/demo ; export TRIP_DEMO
TDBS_PRINT=lp ; export TDBS_PRINT
TDBS_BLOCK_SIZE=2048; export TDBS_BLOCK_SIZE


##########################################################################
# Run 3rd-party installation now (separate script)
#

echo ""
echo "Setting up symbolic link for TRIPsystem libraries:"
echo ""

# Create Link directory if not already present
if [ ! -d $LINK_DIR ]; then
   echo "Creating link directory: $LINK_DIR"
   mkdir -p $LINK_DIR
else
   if [ 0 -ne `ls -1 $LINK_DIR/lib 2> /dev/null | wc -l` ]; then
      rm -f $LINK_DIR/lib
      echo "Current TRIPsystem library link removed from $LINK_DIR"
   fi
fi

# Make link to 3rd-party directory
ln -s -f $TPATH/lib $LINK_DIR/lib
echo "Creating new TRIPsystem library link: $LINK_DIR/lib -> $TPATH/lib"


##########################################################################
# CONTROL database initialization (for new installs) and migration (for
# upgrade installs).
#

DO_MIGRATE_CONTROL=Y

yesno_help_oldcontrol()
{
   echo ""
   echo "   If you are performing a reinstallation or if you wish to use the data"
   echo "   from a previously uninstalled version of TRIPsystem, you should allow"
   echo "   the installer to use the found CONTROL database."
   echo ""
   echo "   If you wish to perform a clean, new installation, you may answer no to"
   echo "   this question."
   echo ""
   echo "   A backup copy of the found CONTROL is created in any case."
   echo ""
}

echo ""
echo "Distributed CONTROL template file is $TDBS_SYS/P_CONTROL.*" 
if [ "$TDBS_SYS" != "$TDBS_CTL" ]; then
   echo " - copying to $TDBS_CTL"
   cp $TDBS_SYS/P_CONTROL.BAF $TDBS_CTL/
   cp $TDBS_SYS/P_CONTROL.BIF $TDBS_CTL/
   cp $TDBS_SYS/P_CONTROL.VIF $TDBS_CTL/
fi

# Determine if CONTROL migration should be done also for a new install.
if [ "$NEWT" = "N" ]; then

   if [ -f $TDBS_CTL/CONTROL.BAF ] && [ -f $TDBS_CTL/CONTROL.BIF ]; then
      echo ""
      echo "A CONTROL database from a previous installation was found"
      echo "in $TDBS_CTL"
      if yesno "Do you wish to use it?" Y yesno_help_oldcontrol
      then
         OLDCTL=$TDBS_CTL
      else
         echo ""
         echo "Backing up the old CONTROL database files"
         CTLTSTAMP=`date '+%Y%m%d%H%M%S'`
         cp_verbose $TDBS_CTL/CONTROL.BAF $TDBS_CTL/CONTROL.BAF-$CTLTSTAMP
         cp_verbose $TDBS_CTL/CONTROL.BIF $TDBS_CTL/CONTROL.BIF-$CTLTSTAMP
         if [ -f $TDBS_CTL/CONTROL.VIF ]; then
            cp_verbose $TDBS_CTL/CONTROL.VIF $TDBS_CTL/CONTROL.VIF-$CTLTSTAMP
         fi
         echo ""
         DO_MIGRATE_CONTROL=N
      fi
   else
      DO_MIGRATE_CONTROL=N
   fi
fi

# New installation: Initialize CONTROL
if [ "$DO_MIGRATE_CONTROL" = "N" ]; then

   echo ""
   echo "Initializing new CONTROL database from template in $TDBS_CTL"
   cp $TDBS_SYS/P_CONTROL.BAF $TDBS_CTL/CONTROL.BAF
   cp $TDBS_SYS/P_CONTROL.BIF $TDBS_CTL/CONTROL.BIF
   cp $TDBS_SYS/P_CONTROL.VIF $TDBS_CTL/CONTROL.VIF

   touch $TPATH/trip-system-install-new.ctl


# Upgrade installation: CONTROL migration
else

   if [ "$OLDCTL" != "" ]; then
      echo "Distributed CONTROL template file is $TDBS_CTL/P_CONTROL.*" 
      if [ "$OLDCTL" != "$TDBS_CTL" ]; then
         echo "Copying $OLDCTL/CONTROL.* to"
         echo "        $TDBS_CTL/CONTROL.*"
         cp $OLDCTL/CONTROL.BAF $TDBS_CTL/CONTROL.BAF
         cp $OLDCTL/CONTROL.BIF $TDBS_CTL/CONTROL.BIF
         cp $OLDCTL/CONTROL.VIF $TDBS_CTL/CONTROL.VIF
      else
         echo "Reusing existing CONTROL database location $TDBS_CTL" 
         echo ""
         if [ "$SHOULD_MIGRATE_CONTROL" = "N" ]; then
            # Since migrate_control won't be called, we'll back up the
            # current CONTROL database files here.
            echo "Backing up the CONTROL database files"
            CTLTSTAMP=`date '+%Y%m%d%H%M%S'`
            cp_verbose $TDBS_CTL/CONTROL.BAF $TDBS_CTL/CONTROL.BAF-$CTLTSTAMP
            cp_verbose $TDBS_CTL/CONTROL.BIF $TDBS_CTL/CONTROL.BIF-$CTLTSTAMP
            if [ -f $TDBS_CTL/CONTROL.VIF ]; then
               cp_verbose $TDBS_CTL/CONTROL.VIF $TDBS_CTL/CONTROL.VIF-$CTLTSTAMP
            fi
         fi
         if [ ! -f $TDBS_CTL/CONTROL.VIF ]; then
            cp $TDBS_SYS/P_CONTROL.VIF $TDBS_CTL/CONTROL.VIF
         fi
         echo ""
      fi

      if [ "$SHOULD_MIGRATE_CONTROL" = "Y" ]; then
         OCHARS=$TDBS_CHARS
         TDBS_CHARS=LA1
         $TDBS_SBIN/migrate_control -y
         MIGRATERC=$?
         TDBS_CHARS=$OCHARS
         if [ $MIGRATERC -ne 0 ]; then
            echo ""
            echo "****** Unable to migrate the CONTROL database from the previous TRIP"
            echo "       installation. Check the installation log for more information"
            echo "       and contact TRIP Support for questions and assistance."
            echo ""
            echo "Exiting the installation process"
            echo ""
            umask $OUMASK
            touch $TPATH/trip-system-install-abort.ctl
            exit 1
         fi
      else
         echo ""
         echo "****** CONTROL database migration skipped as it was not needed."
         echo "       If you still wish to do this, use the tool migrate_control"
         echo "       that you can find in the sbin directory of the installation."
         echo ""
      fi

   else
      echo ""
      echo "****** Cannot find CONTROL files for upgrade."
      echo "       Please check your existing TRIP installation."
      echo ""
      echo "Exiting the installation process"
      echo ""
      umask $OUMASK
      touch $TPATH/trip-system-install-abort.ctl
      exit 1
   fi

fi

# Upgrade installation: accounting log and prn files
if [ "$NEWT" = "U" ]; then

   ##########################################################################
   # Copying DEBIT.LOG to new area
   #

   if [ "$OLDACC" = "" ]; then 
      if [ "$OLDSYS" != "" ]; then
         if [ -f $OLDSYS/DEBIT.LOG ]; then
            echo "DEBIT.LOG exists in $OLDSYS" 
            if [ "$OLDSYS" != "$TDBS_SYS" ]; then
               cp $OLDSYS/DEBIT.LOG $TDBS_SYS/DEBIT.LOG
               echo "   copying the file to $TDBS_SYS"
            fi 
	    chmod 664 $TDBS_SYS/DEBIT.LOG
	    chown $OWNER $TDBS_SYS/DEBIT.LOG
	    chgrp $GROUP $TDBS_SYS/DEBIT.LOG
         fi
      fi
   else
      if [ -f $OLDACC/DEBIT.LOG ]; then
         echo ""
         echo "A DEBIT.LOG file exists in $OLDACC. This will NOT be moved automatically"
      fi
   fi


   ##########################################################################
   # Copying PRC and PRN files to new area
   #
    
   if [ "$OLDPRC" != "" -a -d "$OLDPRC" ]; then
      if [ ! -d "$TDBS_PRC" ]; then
         mkdir $TDBS_PRC
      fi
      if ls $OLDPRC/*.PRC > /dev/null 2>&1; then
      	 echo ""
	 echo "PRC files exists in $OLDPRC"
         if [ "$OLDPRC" != "$TDBS_PRC" ]; then
            cp $OLDPRC/*.PRC $TDBS_PRC
	    echo "   copying these files to $TDBS_PRC"
         fi
      fi
      if ls $OLDPRC/*.PRN > /dev/null 2>&1; then
      	 echo ""
	 echo "PRN files exists in $OLDPRC"
         if [ "$OLDPRC" != "$TDBS_PRC" ]; then
            cp $OLDPRC/*.PRN $TDBS_PRC
	    echo "   copying these files to $TDBS_PRC"
         fi
      fi
      chown -R $OWNER $TDBS_PRC
      chgrp -R $GROUP $TDBS_PRC
   fi


   ##########################################################################
   # Inform about old TRIPdaemon password file
   #

   if [ -f $OLDEXE/TRIPD.DAT ]; then
      echo ""
      echo "****** Found an old TRIP daemon password file in $OLDEXE"
      echo "       This behavior is obsoleted and no longer recommended."
      echo "       The password file will therefore not be migrated."
      echo ""
   fi

fi

#
#########################################################################
# Make sure CONTROL is accessible
#

chmod 664 $TDBS_CTL/CONTROL.*
chown $OWNER $TDBS_CTL/CONTROL.*
chgrp $GROUP $TDBS_CTL/CONTROL.*


##########################################################################
# Create template for the new tdbs.conf file
#
#
echo ""
echo "Creating environment definition scripts/config file" 


TEMPRCS=$TPATH/TRIPrcs.temp
TMPRCS=$TPATH/TRIPrcs.tmp
TRIPRCS=$TPATH/TRIPrcs.template

if [ "$NEWT" = "N" ] && [ -f $TPATH/conf/tdbs.conf ]; then
  echo "Reusing existing configuration file in $TPATH/conf"
  cp $TPATH/conf/tdbs.conf $TEMPRCS

elif [ "$NEWT" = "N" ] || [ "$OLDRC" = "/.triprc" ]; then
  echo "Generating new configuration file (tdbs.conf)"

  echo "[Privileged]" > $TEMPRCS
  echo "TDBS_ACCDIR=$OLDACC" >> $TEMPRCS
  echo "TDBS_ACCFLG=$OLDACCFLG" >> $TEMPRCS
  echo "TDBS_SYS=" >> $TEMPRCS
  echo "TDBS_EXE=$TDBS_EXE" >> $TEMPRCS

  if [ "$OSNAME" = "Darwin" ]; then
    echo "TripNetPort=$TDBS_TRIPNETPORT" >> $TEMPRCS
  fi
  echo "" >> $TEMPRCS

  echo "[NonPrivileged]" >> $TEMPRCS
  echo "TDBS_CTL=$TDBS_CTL" >> $TEMPRCS
  echo "TDBS_EXE=$TDBS_EXE" >> $TEMPRCS
  echo "TDBS_SYS=$TDBS_SYS" >> $TEMPRCS
  echo "TDBS_BASES=$TDBS_BASES" >> $TEMPRCS
  echo "TDBS_PRC=$TDBS_PRC" >> $TEMPRCS
  echo "TDBS_TRM=$TDBS_TRM" >> $TEMPRCS
  echo "TDBS_LOG=$TDBS_LOG" >> $TEMPRCS
  echo "TDBS_SCRATCH=$TDBS_LOG" >> $TEMPRCS
  echo "TDBS_SIF=$TDBS_LOG" >> $TEMPRCS
  echo "TDBS_CHARS=$TDBS_CHARS" >> $TEMPRCS
  echo "TDBS_LANG=$TDBS_LANG" >> $TEMPRCS
  echo "TRIP_DEMO=$TRIP_DEMO" >> $TEMPRCS
  echo "TRIP_TERMINAL=vt200" >> $TEMPRCS
  echo "" >> $TEMPRCS

else
  echo "Copying configuration file from $OLDRC"
  cp_verbose $OLDRC $TEMPRCS

fi


##########################################################################
# Make update-specific adjustments to the configuration file
#

adjustdir()
{
  if [ "$1" = "$2" ]; then
    if [ "$OLD_TRIP_HOME/$4" = "$3" ]; then
      if [ "$5" = "" ]; then
         echo "$2=$TPATH/$4" >> $TMPRCS
      else
         echo "$2=$5" >> $TMPRCS
      fi
      return 0
    fi
  fi
  return 1
}

cat $TEMPRCS | (

  ORIGIFS=$IFS
  unset IFS
  while read -r LINE; do

    CFGSYM=`echo $LINE|cut -d= -f1`
    CFGVAL=`echo $LINE|cut -d= -f2-|sed 's,/$,,g'`

    # Always set to their new values
    if [ "$CFGSYM" = "TDBS_EXE" ]; then
      echo "TDBS_EXE=$TPATH/bin" >> $TMPRCS
      continue
    fi
    if [ "$CFGSYM" = "TDBS_SYS" ]; then
      echo "TDBS_SYS=$TPATH/sys" >> $TMPRCS
      continue
    fi
    if [ "$CFGSYM" = "TDBS_CTL" ]; then
      if [ "$CFGVAL" = "$OLD_TRIP_HOME/sys" ]; then
         echo "TDBS_CTL=$SHARED_STATE_DIR/ctl" >> $TMPRCS
      else
         echo $LINE >> $TMPRCS
      fi
      continue
    fi

    # Move the log directory if it is under the old installation.
    adjustdir $CFGSYM "TDBS_LOG" "$CFGVAL" "log" "$SHARED_STATE_DIR/log/sys"
    if [ $? -eq 0 ]; then continue; fi

    # Move the API log directory if it is under the old installation.
    adjustdir $CFGSYM "TDBS_APILOG" "$CFGVAL" "log" "$SHARED_STATE_DIR/log/sys"
    if [ $? -eq 0 ]; then continue; fi

    # Move the scratch directory if it is under the old installation.
    adjustdir $CFGSYM "TDBS_SCRATCH" "$CFGVAL" "log" "$SHARED_STATE_DIR/log/sys"
    if [ $? -eq 0 ]; then continue; fi

    # Move the sif directory if it is under the old installation.
    adjustdir $CFGSYM "TDBS_SIF" "$CFGVAL" "log" "$SHARED_STATE_DIR/log/sys"
    if [ $? -eq 0 ]; then continue; fi

    # Move the prc directory if it is under the old installation.
    adjustdir $CFGSYM "TDBS_PRC" "$CFGVAL" "prc"
    if [ $? -eq 0 ]; then continue; fi

    # Move the trm directory if it is under the old installation.
    adjustdir $CFGSYM "TDBS_TRM" "$CFGVAL" "trm"
    if [ $? -eq 0 ]; then continue; fi

    # Move the demo directory if it is under the old installation.
    adjustdir $CFGSYM "TRIP_DEMO" "$CFGVAL" "demo"
    if [ $? -eq 0 ]; then continue; fi

    # TDBS_CTL is from version 8.2 under /var/lib/trip/ctl by default.
    # Adjust if the old value refers to the old installation.

    # Move reference to standard stemming library
    if [ "$CFGSYM" = "TDBS_CONFLATORS" ]; then
      NEWCFGVAL=`echo "$CFGVAL" | tr ',' '\n'|grep -v "^$OLD_TRIP_HOME/bin/tripstem.so"|tr '\n' ','|sed 's/,$//g'`
      NEWCFGVAL=`echo "$NEWCFGVAL" | tr ',' '\n'|grep -v "^$OLD_TRIP_HOME/lib/libtripstem.so"|tr '\n' ','|sed 's/,$//g'`
      NEWCFGVAL=`echo "$NEWCFGVAL" | tr ',' '\n'|grep -v "^$TPATH/lib/libtripstem.so"|tr '\n' ','|sed 's/,$//g'`
      if [ "$NEWCFGVAL" = "" ]; then
        echo "TDBS_CONFLATORS=$TPATH/lib/libtripstem.so" >> $TMPRCS
      else
        echo "TDBS_CONFLATORS=$TPATH/lib/libtripstem.so:$NEWCFGVAL" >> $TMPRCS
      fi
      continue
    fi

    # Remove TRIPsql and TRIPxml ASE libraries from TDBS_ASELIBS, since they
    # are now integrated into TRIPsystem slightly differently.
    if [ "$CFGSYM" = "TDBS_ASELIBS" ]; then
      CFGVAL=`removeitem "$CFGVAL" "TDBS_XMLSHR"`
      CFGVAL=`removeitem "$CFGVAL" "TRIPSQL_ENGINE"`
      echo "TDBS_ASELIBS=$CFGVAL" >> $TMPRCS
      continue
    fi

    # The TDBS_XMLSHR symbol is no longer used. Comment it out.
    if [ "$CFGSYM" = "TDBS_XMLSHR" ]; then
      echo "# TDBS_XMLSHR=$CFGVAL" >> $TMPRCS
      continue
    fi

    # The TRIPSQL_ENGINE symbol is no longer used. Comment it out.
    if [ "$CFGSYM" = "TRIPSQL_ENGINE" ]; then
      echo "# TRIPSQL_ENGINE=$CFGVAL" >> $TMPRCS
      continue
    fi

    # Just perform a copy of all other lines
    echo $LINE >> $TMPRCS

  done

  if [ "$ORIGIFS" != "" ]; then
    IFS=$ORIGIFS
  fi
)


ensureconf()
{
  grep "^$1" $TMPRCS > /dev/null
  if [ $? -ne 0 ]; then
    echo "$1=$2" >> $TMPRCS
  fi
}

ensureconf "TDBS_LOG" "$SHARED_STATE_DIR/log/sys"
ensureconf "TDBS_SCRATCH" "$SHARED_STATE_DIR/log/sys"
ensureconf "TDBS_SIF" "$SHARED_STATE_DIR/log/sys"
ensureconf "TDBS_BASES" "$TDBS_BASES"
ensureconf "TDBS_PRC" "$TPATH/prc"
ensureconf "TDBS_TRM" "$TPATH/trm"
ensureconf "TDBS_LANG" "ENG"
ensureconf "TRIP_TERMINAL" "vt200"
ensureconf "TDBS_CONFLATOR_LANG" "ENG"
ensureconf "TDBS_CONFLATORS" "$TPATH/lib/libtripstem.so"

cp $TMPRCS $TRIPRCS
rm -f $TMPRCS
rm -f $TEMPRCS


##########################################################################
# Copy the config file to $TPATH/conf (make a backup first)
#

echo ""
if [ ! -d $TPATH/conf ]; then
   echo "Make installation conf directory"
   mkdir $TPATH/conf
fi
if [ -f $TPATH/conf/tdbs.conf ]; then
   echo "Backup old config file to $TPATH/conf/tdbs.conf~"
   cp $TPATH/conf/tdbs.conf $TPATH/conf/tdbs.conf~
fi
echo "Copying $TRIPRCS to"
echo "        $TPATH/conf/tdbs.conf"
cp $TRIPRCS $TPATH/conf/tdbs.conf
chown $OWNER:$GROUP $TPATH/conf/tdbs.conf

if [ ! -d $LINK_DIR ]; then
   echo "Make link directory $LINK_DIR"
   mkdir -p $LINK_DIR
fi
echo ""
if [ -d $LINK_DIR/conf ] && [ ! -h $LINK_DIR/conf ]; then
   echo "$LINK_DIR/conf exists as a physical directory"
   if [ -f $LINK_DIR/conf/tdbs.conf ]; then
      echo "Backup old config file to $LINK_DIR/conf/tdbs.conf~"
      cp $LINK_DIR/conf/tdbs.conf $LINK_DIR/conf/tdbs.conf~
      echo "Remove old config file $LINK_DIR/conf/tdbs.conf"
      rm -f $LINK_DIR/conf/tdbs.conf
   fi
   echo "Creating link $LINK_DIR/conf/tdbs.conf to:"
   echo "              $TPATH/conf/tdbs.conf"
   ln -s -f $TPATH/conf/tdbs.conf $LINK_DIR/conf/tdbs.conf
else
   echo "Normal case - $LINK_DIR/conf is a directory link"
   if [ -h $LINK_DIR/conf ] || [ -f $LINK_DIR/conf ]; then
      echo "Removing link from $LINK_DIR/conf to:"
      echo "                   `readlink $LINK_DIR/conf`"
      rm -f $LINK_DIR/conf
   fi
   echo "Creating link $LINK_DIR/conf to:"
   echo "              $TPATH/conf"
   ln -s -f $TPATH/conf $LINK_DIR/conf
fi

# Rename old-style config file if present
if [ -f /.TRIPrcs ]; then
   mv /.TRIPrcs /.TRIPrcs.OBSOLETE
   if [ $? -eq 0 ]; then
      echo "Renamed /.TRIPrcs to /.TRIPrcs.OBSOLETE"
      echo "NOTE: New TRIP config file is $LINK_DIR/conf/tdbs.conf"
   fi
fi


##########################################################################
# copy CORR to P_CORR for the user guide examples
#

cp demo/CORR.BAF demo/P_CORR.BAF
cp demo/CORR.BIF demo/P_CORR.BIF
cp demo/CORR.VIF demo/P_CORR.VIF

chmod 644 demo/P_CORR.*
chown $OWNER demo/P_CORR.*
chgrp $GROUP demo/P_CORR.*


##########################################################################
# Set password for the TRIP user SYSTEM
#

if [ -f $TPATH/trip-system-install-new.ctl ] && [ "$OSNAME" != "Darwin" ]; then

  if [ -x $TDBS_EXE/setspwd ]; then
      $TDBS_EXE/setspwd
      if [ $? -ne 1 ]; then
         echo ""
         echo "****** Failed to set system password."
         echo "Exiting the installation process"
         echo ""
         umask $OUMASK
	 touch $TPATH/trip-system-install-abort.ctl
         exit 1
      else
         echo "" | tee -a $LOGFILE
         echo "Password set for TRIP system"
      fi
  else
      echo ""
      echo "****** Unable to run program to set system password. Contact TRIP Support"
      echo "Exiting the installation process"
      echo ""
      umask $OUMASK
      touch $TPATH/trip-system-install-abort.ctl
      exit 1
  fi

   rm -f $TPATH/trip-system-install-new.ctl

fi


##########################################################################
# Configure listening port for tripnetd / tbserver
#

port_in_services()
{
   RETVAL=1
   DOECHO=1
   if [ "$1" = "N" ]; then
      DOECHO=0
   fi
   if [ -f /etc/services ]; then
      #  is there already a service called pctdbs ?
      TRIPNETPORT_SERVICES=`grep '^[     ]*pctdbs[       ].' /etc/services 2> /dev/null | awk '{print $2}' | cut -d/ -f1`
      if [ "$TRIPNETPORT_SERVICES" != "" ]; then
         if [ $DOECHO -eq 1 ]; then
            echo ""
            echo "Service pctdbs(n) already configured in file /etc/services as $TRIPNETPORT_SERVICES"
         fi
         RETVAL=0
      fi
   fi
   return $RETVAL
}

PORT_IN_SERVICES=0
PORT_IN_CONFIG=0

echo ""
if [ -f /etc/services ]; then
   #  is there already a service called pctdbs ?
   TRIPNETPORT_SERVICES=`grep '^[     ]*pctdbs[       ].' /etc/services 2> /dev/null | awk '{print $2}' | cut -d/ -f1`
   if [ "$TRIPNETPORT_SERVICES" != "" ]; then
      echo ""
      echo "Service pctdbs(n) already configured in file /etc/services as $TRIPNETPORT_SERVICES"
      PORT_IN_SERVICES=1
   fi
fi

TRIPNETPORT_CONFIG=`qrcs $TPATH/bin TripNetPort Y`
if [ "$TRIPNETPORT_CONFIG" != "" ]; then
   echo ""
   echo "tripnetd listen port set in tdbs.conf to $TRIPNETPORT_CONFIG"
   PORT_IN_CONFIG=1
fi

if [ $PORT_IN_SERVICES -eq 1 ] && [ $PORT_IN_CONFIG -eq 1 ]; then
   echo ""
   echo "WARNING: The listening port is set in both tdbs.conf and /etc/services" 
   if [ "$TRIPNETPORT_SERVICES" != "$TRIPNETPORT_CONFIG" ]; then
      echo "WARNING: Conflicting listening port values in tdbs.conf and /etc/services"
   fi
fi

if [ $PORT_IN_SERVICES -eq 0 ] && [ $PORT_IN_CONFIG -eq 0 ] && [ "$OSNAME" != "Darwin" ]; then

   TDBS_PORT=23457
   DEFP=`grep "23457/tcp" /etc/services | grep -v "^[     ]*#"`
   if [ "x$DEFP" != "x" ]; then
      echo ""
      echo "Service Port 23457 already in use in file /etc/services"
      echo "*********************************************************"
      grep "23457/tcp" /etc/services | grep -v "^[     ]*#"
      echo "*********************************************************"

      NTPORT=23567
      doloop=0
      while [ "$doloop" = "0" ]
      do
         echo ""
         echo $C1 "Which port number should pctdbs use? [$NTPORT] $C2"
         read answ
         if [ "x$answ" != "x" ]; then
           echo "\n****** Answer: $answ"
         else
           echo "\n****** Answer: default [= $NTPORT]"
         fi
         case $answ in
            \?)
               echo ""
               echo ""
               echo "   Enter a new port number instead of the default port "
               echo "   number 23457, which already is used by another service."
               echo "   A new default port number is suggested [$NTPORT]"
               echo ""
               echo "   If you want to abort the installation, enter EXIT or"
               echo "   exit. The installation will then be incomplete,"
               echo "   i.e. it will be a mix between the old and the new"
               echo "   installation, which will have to be manually"
               echo "   changed into a working installation."
               echo ""
               ;;
            "")
               TDBS_PORT=$NTPORT
               doloop=1
               ;;
            EXIT|exit)
               TDBS_PORT=0
               RCODE=1
               doloop=1
               ;;
            *)
               TDBS_PORT=$answ
               doloop=1
               ;;
         esac
      done
   fi
   echo "File /etc/services is copied to /etc/cp.services.1 for backup"
   cp -fp /etc/services /etc/cp.services.1
   echo "Service pctdbs is added last in file /etc/services :"
   chmod a+w /etc/services
   echo "pctdbs          $TDBS_PORT/tcp   # TRIP Network Service ; `date '+%Y-%m-%d %H:%M:%S'`" >> /etc/services
   chmod a=r /etc/services
   tail -1 /etc/services
fi


##########################################################################
# set umask back to what it was before running the script
#

echo ""
umask $OUMASK
echo "umask is reset to old value: $OUMASK"

} 2>&1 | tee -a $LOGFILE
# output from the left curly bracket to here will be tee-d to $LOGFILE


# Did the inner shell fail?
if [ -f $TPATH/trip-system-install-abort.ctl ]; then

   echo ""
   echo "Installation FAILED!"
   echo ""
   echo "Please check the installation log file for error messages!"
   echo ""

   # remove install ctl files
   rm -f $TPATH/trip-system-install-*.ctl
   exit 1
   
fi 


##########################################################################
# Install daemons and network services
#

# Need to redefine these because the previous definitions
# are done within the tee-block.
TPATH=`pwd`
TDBS_EXE=$TPATH/bin
TBUSER=`grep ^TBUSER= $TPATH/service-args.ctl | cut -d= -f2`
TBGROUP=`grep ^TBGROUP= $TPATH/service-args.ctl | cut -d= -f2`

TRIPD_IS_STARTED=0
TRIPNET_IS_STARTED=0

# Start daemons as systemd or init services (Linux)
if [ -f $TPATH/trip-system-install-start-init.ctl ] || \
   [ -f $TPATH/trip-system-install-start-systemd.ctl ]; then
   echo ""
   $TPATH/sbin/install_services -y -u $TBUSER -g $TBGROUP -l $LOGFILE
   TRIPD_IS_STARTED=1 
   TRIPNET_IS_STARTED=1 
fi

# Start tbserver via xinetd
if [ -f $TPATH/trip-system-install-start-xinetd.ctl ]; then

   XCOND=`sed -n 's/^[       ]*includedir[   ]*\(.*\)/\1/p' /etc/xinetd.conf`
   if [ "x$XCOND" = "x" ]; then
      XCOND=/etc/xinetd.d
   fi
   XCONF=$XCOND/pctdbs
   if [ -f $XCONF ]; then
      # The service is already configured. Edit it to suit this version.

      echo "Updating xinetd service file $XCONF" | tee -a $LOGFILE

      TBUSER=`grep '^[  ]*user[       ].' $XCONF | awk '{print $3}'`
      XCONC=$XCOND/cp.pctdbs.1
      echo "File $XCONF is copied to $XCONC for backup"  | tee -a $LOGFILE
      mv $XCONF $XCONC

      # Create pctdbs.awk

      DBSAWK=$TPATH/pctdbs.awk
      DBSTMP=$TPATH/pctdbs.tmp

      echo '# --- pctdbs.awk ---' > $DBSTMP
      echo 'BEGIN { ST = 0; US = 0; SV = 0; WT = 0; LF = 0; }' >> $DBSTMP
      echo '($1 == "socket_type") { print("    socket_type = stream"); ST = 1; next }' >> $DBSTMP
      echo '($1 == "user") { if (length(USR) > 0) { printf("    user = %s+++",USR); US = 1; next } else { print } }' >> $DBSTMP
      echo '($1 == "server") { printf("    server = %s/tbserver+++",EXE); SV = 1; next }' >> $DBSTMP
      echo '($1 == "wait") { print("    wait = no"); WT = 1; next }' >> $DBSTMP
      echo '($1 == "log_on_failure") { print("    log_on_failure += USERID"); LF = 1; next }' >> $DBSTMP
      echo '($1 != "}") { print }' >> $DBSTMP
      echo 'END { if (ST == 0) { print("    socket_type = stream"); }' >> $DBSTMP
      echo '      if (US == 0) { printf("    user = %s+++",USR); }' >> $DBSTMP
      echo '      if (SV == 0) { printf("    server = %s/tbserver+++",EXE); }' >> $DBSTMP
      echo '      if (WT == 0) { print("    wait = no"); }' >> $DBSTMP
      echo '      if (LF == 0) { print("    log_on_failure += USERID"); }' >> $DBSTMP
      echo '{ print "}" }' >> $DBSTMP
      echo '}' >> $DBSTMP

      sed s/+++/\\\\n/g $DBSTMP > $DBSAWK
      rm -f $DBSTMP
      awk -f $DBSAWK EXE=$TDBS_EXE USR=$TBUSER $XCONC > $XCONF
      rm -f $DBSAWK
   else
      echo "Adding service \"pctdbs\" in file $XCONF" | tee -a $LOGFILE
      echo "# default: on" > $XCONF
      echo "# description: TRIP server for client sessions via the TRIPnet protocol." >> $XCONF
      echo "service pctdbs" >> $XCONF
      echo "{" >> $XCONF
      echo "    socket_type = stream" >> $XCONF
      if [ "x$TBUSER" = "x" ]; then
         TBUSER=root
      fi
      echo "    user = $TBUSER" >> $XCONF
      echo "    server = $TDBS_EXE/tbserver" >> $XCONF
      echo "    wait = no" >> $XCONF
      echo "    log_on_failure += USERID" >> $XCONF
      echo "}" >> $XCONF
   fi

   chmod a=r $XCONF
   echo ""

   # list content of $XCONF
   cat $XCONF | tee -a $LOGFILE

   #  inform the xinetd process to read /etc/xinetd.conf again
   XINETD_START_RC=99
   echo "" | tee -a $LOGFILE
   echo "Restarting xinetd" | tee -a $LOGFILE
   if [ -f /etc/init.d/xinetd ]; then
      /etc/init.d/xinetd reload
      XINETD_START_RC=$?
   else
      PROCID=`ps -ef | grep xinetd | grep -v grep | awk '{print $2}'`
      if [ "x$PROCID" != "x" ]; then
         kill -s HUP $PROCID
         XINETD_START_RC=$?
         if [ $XINETD_START_RC -ne 0 ]; then
            kill -HUP $PROCID
            XINETD_START_RC=$?
            if [ $XINETD_START_RC -ne 0 ]; then
               echo "PLEASE NOTE! Could not restart xinetd process!"  | tee -a $LOGFILE
            fi
         fi
      else
         echo "PLEASE NOTE! No xinetd process found!" | tee -a $LOGFILE
         XINETD_START_RC=1
      fi
   fi

   if [ $XINETD_START_RC -eq 0 ]; then
      TRIPNET_IS_STARTED=1
   fi
 
fi

# Configure tbserver for launch via inetadm - Solaris only
if [ -f $TPATH/trip-system-install-start-inetadm.ctl ]; then

   IADM=`which inetadm 2> /dev/null`
   if [ "qaz$IADM" != "qaz" ]; then
      IADM=`echo $IADM | cut -d" " -f1 | grep "^/"`
   fi
   if [ "qaz$IADM" != "qaz" ]; then
      if inetadm | grep pctdbs > /dev/null
      then
         inetadm -m pctdbs/tcp exec="$TDBS_EXE/tbserver"
         errc=$?
         if [ $errc -eq 0 ]; then
            echo "Updating inetd-managed (inetadm) service pctdbs" | tee -a $LOGFILE
         else
            echo "Error code $errc returned from inetadm" | tee -a $LOGFILE
            RCODE=1
         fi
      else
         if [ "x$TBUSER" = "x" ]; then
            TBUSER=root
         fi
         echo "pctdbs stream tcp nowait $TBUSER $TDBS_EXE/tbserver tbserver" > $TPATH/inetd.conf
         inetconv -i $TPATH/inetd.conf
         errc=$?
         if [ $errc -eq 0 ]; then
            echo "Adding pctdbs to inetd-managed (inetconv) services" | tee -a $LOGFILE
         else
            echo "Error code $errc returned from inetconv" | tee -a $LOGFILE
            RCODE=1
         fi
      fi
      if [ $errc -eq 0 ]; then
         ITXT=`inetadm | grep pctdbs`
         if [ "qaz$ITXT" != "qaz" ]; then
            echo $ITXT
            TRIPNET_IS_STARTED=1
         else
            echo "Problems adding/updating inetd-managed service pctdbs" | tee -a $LOGFILE
            RCODE=1
         fi
      fi
   fi
fi


# Start the TRIP daemon w/o autostart
if [ -f $TPATH/trip-system-install-start-tripd.ctl ]; then
   echo "" | tee -a $LOGFILE
   echo "The TRIP daemon (tripd) is not running. Trying to start it now!" | tee -a $LOGFILE
   $TDBS_EXE/tripd
   sleep 2
   PROCID=`ps -ef | grep tripd | grep -v grep | awk '{print $2}'`
   if [ "x$PROCID" != "x" ]; then
      echo "" | tee -a $LOGFILE
      echo "The TRIP daemon (tripd) has been started." | tee -a $LOGFILE
      ps -ef | grep tripd | grep -v grep
   else
      echo "****** The TRIP daemon (tripd) did not start!" | tee -a $LOGFILE
      echo "       Please check the installation and then" | tee -a $LOGFILE
      echo "       start the TRIP daemon manually. Refer to" | tee -a $LOGFILE
      echo "       the Installation Guide for details. If the" | tee -a $LOGFILE
      echo "       problem persists please contact TRIP support." | tee -a $LOGFILE
      echo "" | tee -a $LOGFILE
   fi

elif [ $TRIPD_IS_STARTED -eq 0 ]; then
   echo "****** The TRIP daemon (tripd) was not started. You must start" | tee -a $LOGFILE
   echo "       it manually to make TRIP available to the users." | tee -a $LOGFILE
fi



# Start the TRIPnet daemon w/o autostart
if [ -f $TPATH/trip-system-install-start-tripnetd.ctl ]; then
   echo "" | tee -a $LOGFILE
   echo "The TRIPnet daemon (tripnetd) is not running. Trying to start it now!" | tee -a $LOGFILE
   echo "TDBS_EXE = $TDBS_EXE" | tee -a $LOGFILE
   $TDBS_EXE/tripnetd
   sleep 2
   PROCID=`ps -ef | grep tripnetd | grep -v grep | awk '{print $2}'`
   if [ "x$PROCID" != "x" ]; then
      echo "" | tee -a $LOGFILE
      echo "The TRIPnet daemon has been started" | tee -a $LOGFILE
      ps -ef | grep tripnetd | grep -v grep
   else
      echo "PLEASE NOTE! Unable to start the TRIPnet daemon (tripnetd)!" | tee -a $LOGFILE
      echo "             There is no Internet Services Daemon running!" | tee -a $LOGFILE
      echo "             It will not be possible to run TRIP client/server" | tee -a $LOGFILE
      echo "             applications. Please refer to the " | tee -a $LOGFILE
      echo "             Installation Guide for more details." | tee -a $LOGFILE
      echo "             If needed please contact the TRIP support." | tee -a $LOGFILE
      echo ""
   fi
elif [ $TRIPNET_IS_STARTED -eq 0 ]; then
   echo "****** The TRIPnet daemon (tripnetd) was not started." | tee -a $LOGFILE
   echo "       If you intend to use it you must start it manually." | tee -a $LOGFILE
   echo "       In case of problems, please contact TRIP support." | tee -a $LOGFILE
fi



echo "" | tee -a $LOGFILE
echo "****** End of installing TRIP v$VERSIONP on $OSNAME" | tee -a $LOGFILE

echo "" | tee -a $LOGFILE
echo "Before using the new TRIP installation," | tee -a $LOGFILE
echo "please log out and then log in again!" | tee -a $LOGFILE

echo "" | tee -a $LOGFILE
echo "End of install script!" | tee -a $LOGFILE
echo "" | tee -a $LOGFILE

echo "NB!"
echo "Please check the installation log file for error messages!"
echo ""

# remove install ctl files
rm -f $TPATH/trip-system-install-*.ctl

exit 0
