#!/bin/bash
#
# Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
#
# RPM post installation script
#

# This is a generic product script used to establish an environment
# before starting/stopping a product or component.
# This script was built from shell library
#   $Id$
# This script has to run on every platform we support.  Any suggestions
# for improvement are welcome (but must be portable!)

# Version numbers
PRODUCT_VERSION="5.60.514"
PRODUCT_VERSION_FULL="5.60.514"
PRODUCT_VERSION_MAJOR=5
PRODUCT_VERSION_FEATURE=6
PRODUCT_VERSION_BUG=0
PRODUCT_VERSION_BUILD=514
PRODUCT_VERSION_BUILD_DECIMAL=514
PRODUCT_VERSION_AS_NUMBER=560514
PRODUCT_VERSION_CAB=5,6,0,514
PRODUCT_VERSION_RPM=5.60-514

# Product names
PRODUCT_FULL_NAME="Oracle Secure Global Desktop"
PRODUCT_SHORT_NAME="Secure Global Desktop"
PRODUCT_IDENT="SSGD"
PRODUCT_SHORT_FILENAME="Tarantella"
PRODUCT_LSBSCRIPTNAME="sun.com-sgd-base"
PRODUCT_LSBSCRIPT_RUN_LEVEL="90"
TSP_FULL_NAME="Oracle Secure Global Desktop Security Pack"
TSP_SHORT_NAME="Security Pack"
WCP_FULL_NAME="Oracle Secure Global Desktop Windows Connectivity Pack"
WCP_SHORT_NAME="Windows Connectivity Pack"
TN3270_FULL_NAME="Oracle Secure Global Desktop Mainframe Connectivity Pack"
TN3270_SHORT_NAME="Mainframe Connectivity Pack"
AS400_FULL_NAME="Oracle Secure Global Desktop AS/400 Connectivity Pack"
AS400_SHORT_NAME="AS/400 Connectivity Pack"
S1PSTK_FULL_NAME="Oracle Secure Global Desktop Channel for Sun ONE Portal Server"
S1PSIP_FULL_NAME="Oracle Secure Global Desktop Integration Pack for Sun ONE Portal Server"
S1PSTK_SHORT_NAME="Secure Global Desktop Channel for Sun ONE Portal Server"
S1PSIP_SHORT_NAME="Secure Global Desktop Integration Pack for Sun ONE Portal Server"

OBJECT_MGR_NAME="Object Manager"
ARRAY_MGR_NAME="Array Manager"
NATIVE_WIN16_FULL_NAME="Oracle Secure Global Desktop Native Client for Windows 3.1"
NATIVE_WIN16_SHORT_NAME="Native Client for Windows 3.1"
NATIVE_WIN32_FULL_NAME="Oracle Secure Global Desktop Native Client for Windows 95, 98 and NT"
NATIVE_WIN32_SHORT_NAME="Native Client for Windows 95, 98 and NT"
NATIVE_WYSE_FULL_NAME="Oracle Secure Global Desktop Native Client for Wyse"
NATIVE_WYSE_SHORT_NAME="Native Client for Wyse"
NATIVE_FULL_NAME="Oracle Secure Global Desktop Native Client"
NATIVE_SHORT_NAME="Native Client"
NATIVE_REGISTRY_NAME="Tarantella Native Client"
INTCLI_FULL_NAME="Oracle Secure Global Desktop Client"
INTCLI_SHORT_NAME="Client"
TCC_FULL_NAME="Oracle Secure Global Desktop Client"
TCC_HELPER_NAME="Oracle Secure Global Desktop Client Helper"
TCC_ACTIVEX_NAME="Oracle Secure Global Desktop ActiveX Control"
TCC_PLUGIN_NAME="Oracle Secure Global Desktop Netscape Plug-in"
T3COMPONENT_WIN_NAME="Oracle Secure Global Desktop Enhancement Module for Windows"
T3COMPONENT_UNIX_NAME="Oracle Secure Global Desktop Enhancement Module for UNIX(TM) and Linux Platforms"
T3COMPONENT_SHORT_UNIX_NAME="tem"
T3COMPONENT_NAME="Oracle Secure Global Desktop Enhancement Module"
T3COMPONENT_LSBSCRIPTNAME="sun.com-sgd-em"
T3COMPONENT_LSBSCRIPT_RUN_LEVEL="90"
GWCOMPONENT_UNIX_NAME="Oracle Secure Global Desktop Gateway for UNIX(TM) and Linux Platforms"
GWCOMPONENT_NAME="Oracle Secure Global Desktop Gateway"
GWCOMPONENT_SHORTNAME="SGD Gateway"
GWCOMPONENT_LSBSCRIPTNAME="sun.com-sgd-gw"
GWCOMPONENT_LSBSCRIPT_RUN_LEVEL="91"

# Watch the length of these names: IE refuses to remove packages if
# the name is too long.
ARCHIVE_NAME_ttalw="TCC Helper, version"
ARCHIVE_NAME_asad="3.x Framework Java Archive"
#ARCHIVE_NAME_tta="3.x Java Archive"
#ARCHIVE_NAME_tta="3.x Combined Java Archive"
ARCHIVE_NAME_tta="Client, "
ARCHIVE_NAME_tsp="3.x Security Java Archive"
ARCHIVE_NAME_proxy="3.x Proxy Java Archive"
WEBSTART_JAR_NAME="sgdwscs"
ARCHIVE_SUFFIX="K"

NS_REGKEY="java/download/com/tarantella/tta"

PRODUCT_VENDOR="Oracle Corporation, Inc."
PRODUCT_SHORT_VENDOR="Oracle"

# Capabilities:
# The format for the capabilities required by the client end of a
# connection is: CAPABILITIES_protocol_type_REQUIRED="expression"

# The format for the capabilities provided by the server end of a
# connection is: CAPABILITIES_protocol_type_PROVIDED="c1 c2 ... c3"

# Asad between a webtop client and server:
CAPABILITIES_ASAD_WEBTOPCLIENT_REQUIRED="(1.1 || 1.2)"
CAPABILITIES_ASAD_WEBTOPCLIENT_PROVIDED="1.1 1.2"

# Asad between two peer servers, or an admin tool and a server:
# 1.1 is core E3 array functionality.
# 1.2 is 3.01 array interoperability functionality.
# 2.1 is core Pisa client device mapping functionality (not a requirement)
CAPABILITIES_ASAD_PEER_REQUIRED="(1.1 || 1.2)"
CAPABILITIES_ASAD_PEER_PROVIDED="1.1 1.2 2.1"

# Client versions of server strings; same format, name prefixed by CLIENT
# Asad between a webtop client and server:
CLIENTCAPABILITIES_ASAD_WEBTOPCLIENT_REQUIRED="(1.1 || 1.2)"
CLIENTCAPABILITIES_ASAD_WEBTOPCLIENT_PROVIDED="1.1 1.2"

# Top-level item names in ENS datastore
DEFAULT_ROOT_ENS="organization"
SYSTEM_ROOT_ENS="Tarantella System Objects"
APP_ROOT_ENS="applications"
APPSERVER_ROOT_ENS="appservers"

WEB_SERVICES_VERSION=1.9


N=""
C=""
if echo -n | grep n > /dev/null
then
  C="\c"
else
  N="-n"
fi
case "$MACHINEARCH" in
i3li*|ppli*) N="$N -e" ;;
esac
_ss_headlines="--------------------------------------------------------------------------"

PATCH_CFG=${TTAINSTDIR}/var/info/patch.cfg
PATCH_VERSION="PATCHED_VERSION"

GetSGDVersion() {
    TTAVERSION="${TTAINSTDIR}/etc/pkg/ttaversion"
    
    if [ ! -s "${TTAVERSION}" ]; then
	return
    fi
    
    SGD_VERSION=`tail -1 ${TTAVERSION}`
    echo "${SGD_VERSION}"
}

PATCH_LIST=${TTAINSTDIR}/var/info/patch.list
PATCH_LOG=${TTAINSTDIR}/var/log/patch.log
BACKUP_BIN_DIR=${TTAINSTDIR}/bin/bin/backups
BACKUP_JSERVER_DIR=${TTAINSTDIR}/bin/java/backups
BACKUP_WEBSERVER_DIR=${TTAINSTDIR}/webserver/backups
BACKUP_FILE_DIR=${TTAINSTDIR}/var/patchbackups
DELIM="|"
ACTIVE="active"
INACTIVE="inactive"

AddedPatch() {
   echo "$1 - Added patch : $2 $3" >> ${PATCH_LOG}
}

RemovedPatch() {
   echo "$1 - Removed patch : $2 $3" >> ${PATCH_LOG}
}

Check_sgd_running() {
    # ps output only gives limited characters in the command so truncate
    # the install directory if it's too long
    match=`echo $2 | cut -c1-25`

  # Count the number of lines in the file
  entries=`wc -l "$1" 2> /dev/null | awk '{print $1}'`
  if [ ! -s "$1" ]; then
      # Delete an empty file
      rm -f "$1" 2> /dev/null
      return 2;
  elif [ $entries -eq 1 ]; then
      ThePid=`tail -1 "$1" 2>/dev/null | sed 's/ //g'`
      if [ ! -n "${ThePid}" ]; then
          # No pid in the file
	  rm -f "$1" 2> /dev/null
	  return 1
      elif [ -n "`ps -fp${ThePid} 2>/dev/null | egrep \"$match\" | egrep -v egrep`" ] ; then
          # Single pid and the process is still running
	  return 0
      fi

      # The file exists but the process isn't one we expect
      rm -f "$1" 2> /dev/null
      return 1
  else
      # Multiple entries in the file - write all the pids for our processes
      # into a "running" file
      while read Pid ; do
         [ -n "`ps -fp${Pid} 2>/dev/null | egrep \"$match\" | egrep -v egrep`" ] && echo ${Pid} >> running
      done < $1

      if [ -s running ]; then
          # Move the "running" file back to the correct location
          mv -f running $1
          running_entries=`wc -l "$1" 2> /dev/null | awk '{print $1}'`
          ThePid=`tail -1 "$1" 2>/dev/null | sed 's/ //g'`
          if [ $running_entries -eq 1 ]; then
              # Single running process
	      return 0
          else
              # Multiple running processes
              return 3
          fi
      else
          rm -f "$1" 2> /dev/null
          return 1
      fi
  fi
}

ExitIfRunning() {
    DIR=$4

    Check_sgd_running $1 $2
    result=$?
    if [ ${result} -eq 0 -o ${result} -eq 3 ]; then
	echo "$3"
	cd ${TTAINSTDIR}/bin
	rm -rf ${DIR} 2> /dev/null
	exit 1
    fi
}

# Delete all the patches of the given type from the patch list
DeleteRedundantPatches () {
    [ -f "${PATCH_LIST}" ] || {
        return
    }

    TYPE=$1

    # Find and delete the redundant patches from the old version
    [ -x "/usr/bin/nawk" ] && AWK="nawk" || AWK="awk"
    LIST=`grep "${DELIM}${TYPE}${DELIM}" ${PATCH_LIST} |
    ${AWK} -F "${DELIM}" -v version=${FILE_VERSION} '{
        if ($6 == version)
          print $1
    }' | tr ' ' '|'`

    if [ -n "${LIST}" ]; then
	egrep -v "${LIST}" ${PATCH_LIST} > ${TTAINSTDIR}/var/info/patch.list.tmp
	mv -f ${TTAINSTDIR}/var/info/patch.list.tmp ${PATCH_LIST}
    fi
}


# If the SGD server has been upgraded, delete any patches which have
# been superseded by the new version.
TidyUpAfterUpgrade() {
    # If patch config file doesn't exist there is nothing to do here.
    [ -f "${PATCH_CFG}" ] || {
        return;
    }
    
    FILE_VERSION=`grep "${PATCH_VERSION}" ${PATCH_CFG} 2> /dev/null | awk '{print $3}'`
    CURRENT_VERSION=`GetSGDVersion`

    case "${CURRENT_VERSION}" in
	${FILE_VERSION})
            return
	    ;;
	*)
	    DeleteRedundantPatches "binary" 
	    DeleteRedundantPatches "jserver"
	    DeleteRedundantPatches "webserver"
	    DeleteRedundantPatches "webcomp"
	    DeleteRedundantPatches "file"
	    ;;
    esac
}

# Modifies a entry in the patch list
# By default, it changes the status from active -> inactive.
# If a second parameter is supplied, it swaps entry for the new 
# entry without any other changes
UpdateEntry() {
    FROM_ENTRY=$1
    TO_ENTRY=$2

    if [ -z "${TO_ENTRY}" ]; then
	TO_ENTRY=`echo ${FROM_ENTRY} | sed -e 's/'${DELIM}${ACTIVE}${DELIM}'/'${DELIM}${INACTIVE}${DELIM}'/g'`
    fi

    grep -v "${FROM_ENTRY}" ${PATCH_LIST} > patch.list.tmp
    echo ${TO_ENTRY} >> patch.list.tmp
    mv -f patch.list.tmp ${PATCH_LIST}	
}

# Update the patch name for a patch command
UpdateRef() {
    COMMAND=$1
    NAME=$2
    PATCH_CFG=$3

    grep -v "^${COMMAND} :" ${PATCH_CFG} > patch.cfg.tmp
    mv -f patch.cfg.tmp ${PATCH_CFG}
    echo "${COMMAND} : ${NAME}" >> ${PATCH_CFG}
}

lf_nomessages="No message files installed for LANG="
l_langdefault="Attempting to use default English (en-us) messages"
l_langunknown="Unrecognized \$LANG: "
l_langunset="\$LANG is not set."
lf_langright="Please check the \$LANG variable is correct."
l_langsetto="\$LANG is currently set to: "
l_gottheselangs="Message files are installed for the following languages:"
l_usinglang="Using messages in"
[ -z "$LANG" ] && LANG="C"

TTALANG=$LANG
case "$TTALANG" in
C)  TTALANG="en-us"
    ;;
[a-z][a-z]_[A-Z][A-Z])
    # convert LANG format from ab_CD to ab-cd
    TTALANG=`echo "$TTALANG" | LANG=C LC_ALL=C tr '[A-Z]_' '[a-z]-'`
esac

if [ ! -d $TTALANG -o -z "$TTALANG" ]; then
  [ ! -z "$TTALANG" ] && posslangs=`find . -type d -name "$TTALANG*" -print 2>/dev/null | sed 's;.*\/.*\/.*;;'`

  [ -z "$posslangs" ] && posslangs=`find . -type d -name '[a-z][a-z]-[a-z][a-z]*' -print 2>/dev/null | sed 's;.*\/.*\/.*;;'`

  nposslangs=`echo $posslangs | wc -w`
  if [ "$nposslangs" -gt 1 ]; then
    case "$TTALANG" in ?) TTALANG=en-us;; esac
    tmpTTALANG=$TTALANG
    for a_lang in $posslangs; do
      output=`echo $a_lang | sed -e 's/.*\///'`
      if [ -f $output/common -o -f ../$output/common ]; then
	[ "$tmpTTALANG" != "en-us" ] && tmpTTALANG=$output
      fi
    done
    [ "$TTALANG" = "$tmpTTALANG" ] && TTALANG=en-us || TTALANG=$tmpTTALANG	
  elif [ "$nposslangs" -eq 1 ]; then
    TTALANG=`echo $posslangs | sed -e 's/.*\///'`
  else
    echo "$lf_reinst"
    exit 5
  fi
fi

TTAMSG=`pwd`/$TTALANG
export TTAMSG TTALANG
if [ $trace ]; then echo "   trace: Language dir = $TTAMSG"; fi


ans_host=`hostname`
if [ -f "$INSTDIR/$ans_host.answers" ]; then
    . "$INSTDIR/$ans_host.answers"
fi


OK=0
FAIL=1
CANT_DOWNGRADE=2
CANT_UPGRADE=3
QUIT=4
FORCE_UPGRADE=5

setPkgLang()
{
     posslangs=`(cd "${REQDIR}" ; ls ??-??_setup 2>/dev/null)`
     case $posslangs in
       "" )                                          # no languages!
         PKGLANG=""
         echo "Can't find any language files in directory $REQDIR" >>$LOGFILE
         exit 1
       ;;
       ??-??_setup )                                         # Good; just one
         PKGLANG=`expr "$posslangs" : "\(..-..\)"`
       ;;
       * )                                           # Choices, choices
         case $LANG in
           ""|C|POSIX )
           ;;                                        # Ignored
           * )                                       # Some OS specific string
             LA=`expr $LANG : "\(..\)"`              # 1st two chars
             # must ensure tr uses C locale to lower case!
             la=`echo $LA | LANG=C LC_ALL=C tr '[A-Z]' '[a-z]'`
             goodlangs=`echo "$posslangs" | grep "^$la"`
             if [ -n "$goodlangs" ]
             then
               posslangs=$goodlangs                  # ones that match $LANG
             fi
             ;;
         esac
         # Pick the first language in posslangs, or en-us if that is empty
         if [ -z "$posslangs" ]; then
            PKGLANG="en-us"
         else
            PKGLANG=`expr "$posslangs" : "\(..-..\)"`
         fi
     ;;
     esac

     if [ -n "$PKGLANG" ]; then
       # read the strings in
       . ${REQDIR}/${PKGLANG}_setup
     fi
}


# This should only be executed if the server has not been configured
configure=${INSTDIR}/var/configure
TTA_CONFIGURE=`cat ${configure} 2>/dev/null`
if [ -z "${TTA_CONFIGURE}" ]; then
  exit
fi

# Get ${prvusr} and ${prvgrp}
GetPrivUsrGrp()
{
    cat $installdir/var/serverconfig/global/array.properties 2>/dev/null | awk -F= \
	'BEGIN { u="ttasys"; wu="ttaserv"; g="ttaserv" }
	$1 == "tarantella.config.array.privilegeduser" { u = $2 }
	$1 == "tarantella.config.array.webserveruser" { wu = $2 }
	$1 == "tarantella.config.array.privilegedgroup" { g = $2 }
	END { print u " " wu " " g }'
}
_privusrgrp=`GetPrivUsrGrp`
privusr=`expr "$_privusrgrp" : '\([^ ]*\) .*'`
webservusr=`expr "$_privusrgrp" : '.* \([^ ]*\) .*'`
privgrp=`expr "$_privusrgrp" : '.* \([^ ]*\)$'`


# Secure by default
InstSecure='t'
InstSecureAlready='t'

# Set the package and architecture env variables
PKG_NAME=`awk '{print $1}' $configure`
SHORT_ARCH=`expr ${SCOARCH} : '\(....\).*'`

# Set up the environment
[ "${TTA_DEVINSTALL}" = "tx" ] && set -x
[ -n "${TTA_DEVINSTALL}" ] && TTA_DEVINSTALL_INSTDIR="${INSTDIR}" || TTA_DEVINSTALL_INSTDIR=""
case "${SHORT_ARCH}" in
i3li) TTA_RPM="t" TTA_TMPDIR=${TTA_DEVINSTALL_INSTDIR}/tmp/ttarpm export TTA_RPM TTA_TMPDIR ;;
*)    TTA_RPM=""  TTA_TMPDIR=${TTA_DEVINSTALL_INSTDIR}/tmp/ttapkg export TTA_RPM TTA_TMPDIR
esac
DATADIR="${INSTDIR}/var" export DATADIR
INST_DATADIR="${INSTDIR}/etc/pkg" export INST_DATADIR
PKG=${PKG_NAME} export PKG
if [ -n "${TTA_DEVINSTALL_INSTDIR}" ]; then
    PKGINST=${PKG_NAME}
elif [ -n "${TTA_RPM}" ]; then
    PKGINST=${PKG_NAME}
else
# find the latest instance of the package
INSTVER=0
PKGINST=''
# get the package name
shortpkgname=`echo tta | sed 's,^\(.*\)\..*$,\1,'`
# get info on instances of this package
pkginfo=`pkginfo $shortpkgname.\* 2>/dev/null`
res=$?
if [ $res -eq 0 ]; then
    pkginfo=`echo "$pkginfo" | awk '{printf (" %s ",$2)}'`
    # return the first one (in case none have INSTVER set)
    PKGINST=`echo $pkginfo | awk '{print $1}'`
    for inst in $pkginfo
    do
	thisinst=`pkgparam $inst INSTVER 2>/dev/null`
	if [ -n "$thisinst" ]; then
	    [ "$thisinst" -ge 999999 ] && thisinst=1
	    if [ "$thisinst" -gt "$INSTVER" ]; then
		INSTVER=$thisinst
		PKGINST=$inst
	    fi
	fi
    done
fi

fi
export PKGINST
REQDIR=${INST_DATADIR}/${PKG_NAME}/install export REQDIR
xflag=""; [ -f "${HOME}/install.debug" ] && { trace=x export trace; xflag="-x"; }
mkdir -p ${TTA_TMPDIR} 2>/dev/null

# Make the post installed tmp dir
mkdir -p ${INSTDIR}/var/tmp 2>/dev/null
chmod 770 ${INSTDIR}/var/tmp 2>/dev/null

# Set the defaults for a pkg install 
if [ -z "${TTA_DEVINSTALL}" ]
then
    setPkgLang

    # We're not the tta pkg, set the defaults
    . ${INSTDIR}/bin/scripts/install_scripts/set_install_defaults

    # Write the security settings to a setup_response file for any security
    # enabling we need to do after the postinstall
    cat > ${INSTDIR}/var/tmp/setup_response << xxxEOFxxx
a_InstSecure='${a_InstSecure}'
a_InstSecureCert='${a_InstSecureCert}'
xxxEOFxxx
fi

# reset the tmpdir
case "${SHORT_ARCH}" in
i3li) TTA_TMPDIR=${TTA_DEVINSTALL_INSTDIR}/tmp/ttarpm export TTA_RPM TTA_TMPDIR ;;
*)    TTA_TMPDIR=${TTA_DEVINSTALL_INSTDIR}/tmp/ttapkg export TTA_RPM TTA_TMPDIR
esac
# call the postinstall scripts
for suffix in '' .arch .${SHORT_ARCH}
do
    postinstall=${INST_DATADIR}/${PKG_NAME}/install${suffix}/postinstall
    [ -f ${postinstall} ] && sh ${xflag} ${postinstall} 2>&1 | tee -a ${INSTALL_LOG}
done

dev_subpacks=""
if [ -n "${TTA_DEVINSTALL}" ]
then
    dev_subpacks="pip"
fi

for subpack in $dev_subpacks tsp
do
    postinstall=${INSTDIR}/bin/scripts/install_scripts/${subpack}/postinstall
    [ -f ${postinstall} ] && sh ${xflag} ${postinstall} 2>&1 | tee -a ${INSTALL_LOG}
done

### Create any missing files required by the patch commands
# On upgrade clean up existing patches
if ${UPGRADE:?}
then
    TidyUpAfterUpgrade
fi

# Delete any existing patch cfg
rm -f ${PATCH_CFG} 2> /dev/null
# Create a new patch cfg with the correct version
CURRENT_VERSION=`GetSGDVersion`
echo "${PATCH_VERSION} : ${CURRENT_VERSION}" > ${PATCH_CFG}
# Create patch.list if not present.
[ ! -f ${PATCH_LIST} ] && touch ${PATCH_LIST} 2>/dev/null
chmod 640 ${PATCH_CFG} ${PATCH_LIST} 2>/dev/null

# Clear the config file so the server is now configured
echo "" > "${configure}"

[ -n "${TTA_RPM}" -a -z "${TTA_DEVINSTALL}" ] && {
    ${UPGRADE:?} && ${INSTDIR}/bin/scripts/postupgrade ${INSTDIR} 2>&1 | tee -a ${INSTALL_LOG}
    [ -n "${TTA_TMPDIR}" -a "${TTA_TMPDIR}" != "/" -a -f "${TTA_TMPDIR}/locale.tar" ] && rm -rf $TTA_TMPDIR/locale $TTA_TMPDIR/locale.tar 2>/dev/null
}

_parent=`dirname "${TTA_TMPDIR}"`
_base=`basename "${TTA_TMPDIR}"`
case "${_base}" in
ttainst_[0-9]*|ttarpm*) (
    dashes="=========================================================================="
    cd ${_parent}
    for log in ttainst_[0-9]*/*.log ttarpm*/*.log; do
	[ -s "${log}" ] && {
	    echo "${dashes}" >>tta_inst.log
	    echo "${log}" >>tta_inst.log
	    echo "${dashes}" >>tta_inst.log
	    cat "${log}" >>tta_inst.log 2>/dev/null
	    rm -rf "${log}" >>tta_inst.log 2>/dev/null
	}
    done
    rmdir ttainst_[0-9]* ttarpm* 2>/dev/null
)
esac


exit 0
