#!/bin/bash
# Copyright (c) 2008, 2020, Oracle and/or its affiliates.
# 
# Postinstall script for the SGD gateway installation
#

. "${INSTDIR}/bin/scripts/common"

[ "${trace}" = "x" ] && set -x

# 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


#versioninfo
# 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
# Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
# Modify these lists whenever the list of supported upgrades changes.
#
# The lists are egrep regular expressions.  Spaces can be inserted
# for readability: they are squeezed out at run time.
#
# POSSIBLE_UPGRADES is a full list of previous versions which stand
# a reasonable chance of being upgradable, although they may not
# necessarily all be supported.
#
# SUPPORTED_UPGRADES are the previous versions from which upgrades
# are officially supported.  SUPPORTED_UPGRADES should either be
# identical to POSSIBLE_UPGRADES, or a subset of POSSIBLE_UPGRADES.
#
POSSIBLE_UPGRADES='4\.63\.9[0-9][0-9] | 4\.71\.9[0-9][0-9] | 5\.(00|10|20|30)\.9[0-9][0-9]'
SUPPORTED_UPGRADES="${POSSIBLE_UPGRADES}"

#Marks RPM as obsoleting this version and below.
RPM_OBSOLETES=5.10
# the License Product Code
PRODUCT_LICENSE_PRODUCT_CODE="8388608"
TSP_US_LICENSE_PRODUCT_CODE="4194304"
TSP_INTL_LICENSE_PRODUCT_CODE="2097152"
USER_RESTRICTION="1"


#packageinfo
# 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
# The special name values are limited to 53 characters (including "Tarantella")
# well only 53 characters of the complete name is displayed in the --info
# option of the shx file

PRODUCT_PACKAGE_TYPES="pkg rpm"

PRODUCT_TTA_PKGNAME="tta"
PRODUCT_TSP_PKGNAME="ttasecure"
PRODUCT_WCP_PKGNAME="ttawcp"
PRODUCT_PIP_PKGNAME="ttapip"
PRODUCT_3270_PKGNAME="tta3270"
PRODUCT_5250_PKGNAME="tta5250"
PRODUCT_TEM_PKGNAME="tem"
PRODUCT_TIER3TEM_PKGNAME="tem"
PRODUCT_GW_PKGNAME="SUNWsgdg"

PRODUCT_S1PSTK_PKGNAME="tcs1"
PRODUCT_S1PSIP_PKGNAME="tis1"

PRODUCT_PACKAGELIST_S1PSTK="tcs1"
PRODUCT_PACKAGELIST_S1PSIP="tis1"
PRODUCT_PACKAGE_SPECIAL_PRENAME_tcs1pt=""
PRODUCT_PACKAGE_SPECIAL_NAME_tcs1pt=" $S1PSTK_SHORT_NAME patch $PRODUCT_VERSION_FULL"
PRODUCT_PACKAGE_CATEGORY_tcs1pt="application"

PRODUCT_PACKAGE_SPECIAL_NAME_tis1pt=" $S1PSIP_SHORT_NAME patch $PRODUCT_VERSION_FULL"
PRODUCT_PACKAGE_CATEGORY_tis1pt="application"

PRODUCT_PACKAGE_SPECIAL_PRENAME_tcs1=""
PRODUCT_PACKAGE_SPECIAL_NAME_tcs1=" $S1PSTK_SHORT_NAME"
PRODUCT_PACKAGE_CATEGORY_tcs1="application"

PRODUCT_PACKAGE_SPECIAL_PRENAME_tis1=""
PRODUCT_PACKAGE_SPECIAL_NAME_tis1=" $S1PSIP_SHORT_NAME"
PRODUCT_PACKAGE_CATEGORY_tis1="application"

PRODUCT_PACKAGELIST_BASE="tta ttapip ttawcp ttasecure tta3270 tta5250 ttafandr ttafhang ttaficl ttaforie ttafscot"
PRODUCT_PACKAGELIST_TSP="ttasecure"
PRODUCT_PACKAGELIST_WCP="ttawcp"
PRODUCT_PACKAGELIST_3270="tta3270"
PRODUCT_PACKAGELIST_5250="tta5250"
PRODUCT_PACKAGELIST_TEM="tem"
PRODUCT_PACKAGELIST_TIER3TEM="tem"
PRODUCT_PACKAGELIST_ARCHIVE=""
PRODUCT_PACKAGELIST_NULL="ttafandr ttafhang ttaficl ttaforie ttafscot"
PRODUCT_PACKAGELIST_FONTS="ttafandr ttafhang ttaficl ttaforie ttafscot"

PRODUCT_PACKAGE_SPECIAL_PRENAME_tta=""
PRODUCT_PACKAGE_SPECIAL_NAME_tta=""
PRODUCT_PACKAGE_CATEGORY_tta="application"

PRODUCT_PACKAGE_SPECIAL_PRENAME_ttasecure=""
PRODUCT_PACKAGE_SPECIAL_NAME_ttasecure=" Security Pack"
PRODUCT_PACKAGE_CATEGORY_ttasecure="application"

PRODUCT_PACKAGE_SPECIAL_PRENAME_ttawcp=""
PRODUCT_PACKAGE_SPECIAL_NAME_ttawcp=" Windows Connectivity Pack"
PRODUCT_PACKAGE_CATEGORY_ttawcp="application"

PRODUCT_PACKAGE_SPECIAL_PRENAME_ttafandr=""
PRODUCT_PACKAGE_SPECIAL_NAME_ttafandr=" Andrew Fonts"
PRODUCT_PACKAGE_CATEGORY_ttafandr="graphics"
PRODUCT_PACKAGE_DIR_ttafandr="fonts/andrew"

PRODUCT_PACKAGE_SPECIAL_PRENAME_ttafhang=""
PRODUCT_PACKAGE_SPECIAL_NAME_ttafhang=" Hangul Fonts"
PRODUCT_PACKAGE_CATEGORY_ttafhang="graphics"
PRODUCT_PACKAGE_DIR_ttafhang="fonts/hangul"

PRODUCT_PACKAGE_SPECIAL_PRENAME_ttaficl=""
PRODUCT_PACKAGE_SPECIAL_NAME_ttaficl=" ICL Fonts"
PRODUCT_PACKAGE_CATEGORY_ttaficl="graphics"
PRODUCT_PACKAGE_DIR_ttaficl="fonts/icl"

PRODUCT_PACKAGE_SPECIAL_PRENAME_ttaforie=""
PRODUCT_PACKAGE_SPECIAL_NAME_ttaforie=" Oriental Fonts"
PRODUCT_PACKAGE_CATEGORY_ttaforie="graphics"
PRODUCT_PACKAGE_DIR_ttaforie="fonts/oriental"

PRODUCT_PACKAGE_SPECIAL_PRENAME_ttafscot=""
PRODUCT_PACKAGE_SPECIAL_NAME_ttafscot=" SCO Term Fonts"
PRODUCT_PACKAGE_CATEGORY_ttafscot="graphics"
PRODUCT_PACKAGE_DIR_ttafscot="fonts/scoterm"

PRODUCT_PACKAGE_SPECIAL_PRENAME_ttapatch=""
PRODUCT_PACKAGE_SPECIAL_NAME_ttapatch=" Patch $PRODUCT_VERSION_FULL"
PRODUCT_PACKAGE_CATEGORY_ttapatch="application"

PRODUCT_PACKAGE_SPECIAL_PRENAME_tta3270pt=""
PRODUCT_PACKAGE_SPECIAL_NAME_tta3270pt=" $TN3270_SHORT_NAME patch $PRODUCT_VERSION_FULL"
PRODUCT_PACKAGE_CATEGORY_tta3270pt="application"

PRODUCT_PACKAGE_SPECIAL_PRENAME_tta5250pt=""
PRODUCT_PACKAGE_SPECIAL_NAME_tta5250pt=" $AS400_SHORT_NAME patch $PRODUCT_VERSION_FULL"
PRODUCT_PACKAGE_CATEGORY_tta5250pt="application"

PRODUCT_PACKAGE_SPECIAL_PRENAME_tsppatch=""
PRODUCT_PACKAGE_SPECIAL_NAME_tsppatch=" Security Pack Patch $PRODUCT_VERSION_FULL"
PRODUCT_PACKAGE_CATEGORY_tsppatch="application"

PRODUCT_PACKAGE_SPECIAL_PRENAME_gunzip="GNU gunzip for "
PRODUCT_PACKAGE_SPECIAL_NAME_gunzip=""
PRODUCT_PACKAGE_CATEGORY_gunzip="application"

PRODUCT_PACKAGE_SPECIAL_PRENAME_tta3270=""
PRODUCT_PACKAGE_SPECIAL_NAME_tta3270=" $TN3270_SHORT_NAME"
PRODUCT_PACKAGE_CATEGORY_tta3270="application"

PRODUCT_PACKAGE_SPECIAL_PRENAME_tta5250=""
PRODUCT_PACKAGE_SPECIAL_NAME_tta5250=" $AS400_SHORT_NAME"
PRODUCT_PACKAGE_CATEGORY_tta5250="application"

PRODUCT_PACKAGE_SPECIAL_PRENAME_ttapip=""
PRODUCT_PACKAGE_SPECIAL_NAME_ttapip=" Platform Identity Pack"
PRODUCT_PACKAGE_CATEGORY_ttapip="application"

PRODUCT_PACKAGE_SPECIAL_PRENAME_tem=""
PRODUCT_PACKAGE_SPECIAL_NAME_tem=" Enhancement Module"
PRODUCT_PACKAGE_CATEGORY_tem="application"

PRODUCT_PACKAGE_SPECIAL_PRENAME_SUNWsgdg=""
PRODUCT_PACKAGE_SPECIAL_NAME_SUNWsgdg=" Gateway"
PRODUCT_PACKAGE_CATEGORY_SUNWsgdg="application"

# be paranoid about the current path
if [ -d /bin ]; then
  PATH=/bin:$PATH
fi
if [ -d /sbin ]; then
  PATH=/sbin:$PATH
fi
if [ -d /usr/bin ]; then
  PATH=/usr/bin:$PATH
fi
if [ -d /usr/sbin ]; then
  PATH=/usr/sbin:$PATH
fi
if [ -d /etc ]; then
  PATH=/etc:$PATH
fi
export PATH

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="--------------------------------------------------------------------------"

# get our ported package tools on the head of the path
if [ -d /usr/package/sadm/install/bin ]
then
    PATH=/var/sadm/install/bin:$PATH
fi

if [ -z "$0" ]; then
  who_i_am=""
else
  who_i_am=`expr "//$0" : '.*/\(.*\)' `
fi

TTAINSTDIR=${INSTDIR}

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}
}

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}"
}

privusr="sgdgsys"
privgrp="sgdgserv"

mode=750


OPENSSL_HELPER=${INSTDIR}/bin/scripts/openssl_lib.sh

msgfile="${INSTDIR}/etc/pkg/gateway/install/en-us_setup"
[ -s "${msgfile}" ] && . ${msgfile}

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

FORMAT_PKCS12="pkcs12"

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

# Set the package and architecture env variables
case `uname` in
    "Linux")
        SCOARCH="i3li0206"
    ;;
    "SunOS")
        VER=`uname -r | tr -d "."`
        case `uname -p` in
            "sparc")
            SCOARCH="spso0${VER}"
            ;;
            "i386")
            SCOARCH="i3so0${VER}"
            ;;
        esac
    ;;
esac

PKG_NAME=`awk '{print $1}' $configure`
SHORT_ARCH=`expr ${SCOARCH} : '\(....\).*'`

# Set up the environment
TTA_TMPDIR=/tmp/ttarpm export TTA_TMPDIR
DATADIR="${INSTDIR}/var" export DATADIR
INST_DATADIR="${INSTDIR}/etc/pkg" export INST_DATADIR
PKG=${PKG_NAME} export PKG
PKGINST=${PKG_NAME}
export PKGINST
REQDIR=${INST_DATADIR}/${PKG_NAME}/install export REQDIR
xflag=""; [ -f /tmp/pkgadd.debug ] && { trace=x export trace; xflag="-x"; }
mkdir ${TTA_TMPDIR} 2>/dev/null

_DEPS="${INSTDIR}/var/info/_dependencies"
[ -n "${TTA_RPM}" -a -s "${_DEPS}" ] && (
    cd ${INSTDIR}
    for _f in `cat ${_DEPS}`; do
	[ -f "${_f}" ] || continue
	f=`expr "${_f}" : '.\(.*\)'`
	f=`echo "${_f}" | sed 's|/_\([^/]*\)$|/\1|'`
	rm -f ${f} 2>/dev/null
	cp -p ${_f} ${f}
	dd bs=2 skip=1 if=${_f} of=${f} >/dev/null 2>&1
	rm -f ${_f} 2>/dev/null
    done
    rm -f ${_DEPS} 2>/dev/null
)


# Get the config from the user
mkdir -p ${INSTDIR}/var/tmp 2>/dev/null
chmod ${mode} ${INSTDIR}/var/tmp 2>/dev/null
chown ${privusr}:${privgrp} "${INSTDIR}/var/tmp" 2>/dev/null

INSTALL_LOG="/tmp/tta_inst.log"
rm -rf ${INSTALL_LOG} 2>/dev/null

LSB_INST_RCFILE="S91${GWCOMPONENT_LSBSCRIPTNAME}"
LSB_INST_RCFILE_OLD="S90${GWCOMPONENT_LSBSCRIPTNAME}"

PREVIOUS_VERSION=""
[ -s "${INSTDIR}/etc/version.prev" ] && {
    PREVIOUS_VERSION=`sed '/^VERSION_SUNWsgdg=/!d;s/VERSION_SUNWsgdg="//;s/".*//' ${INSTDIR}/etc/version.prev`
}

# defaults
BINDADDR="*:443"
CLIENTADDR="`${INSTDIR}/bin/bin/ttahostname`:443"
a_SGDSecure="y"
REVERSEPROXYADDR="127.0.0.1:8081"

# detect any settings from previous installs and use them as the default
if [ -s $INSTDIR/etc/gatewayconfig.xml ]; then
    # binding address (--interface)
    previous_binding=`sed -n "s/.*<binding>\(.*\)<\/binding>.*/\1/p" $INSTDIR/etc/gatewayconfig.xml`
    [ -n "${previous_binding}" ] && BINDADDR=${previous_binding}

    # client address (--entry-point)
    previous_client_addr=`sed -n "s/.*<clientaddr>\(.*\)<\/clientaddr>.*/\1/p" $INSTDIR/etc/gatewayconfig.xml`
    [ -n "${previous_client_addr}" ] && CLIENTADDR=${previous_client_addr}

    # GW<->SGD security (--out)
    previous_sgd_client=`sed -n "s/.*<sgdclient>\(.*\)<\/sgdclient>.*/\1/p" $INSTDIR/etc/gatewayconfig.xml`
    [ "${previous_sgd_client}" = "tcpclient" ] && a_SGDSecure="n" || a_SGDSecure="y"

    # Reverse proxy address
    previous_address=`sed -n "s/.*<reverseproxyaddr>\(.*\)<\/reverseproxyaddr>.*/\1/p" $INSTDIR/etc/gatewayconfig.xml`
    [ -n "${previous_address}" ] && REVERSEPROXYADDR=${previous_address}
fi

#
# Create keystore password file
#
# Args: $1 - filename
#       $2 - permissions
#
create_passwordfile()
{
    # create a keystore password
    new_password=`${INSTDIR}/bin/bin/ttarandom --keysize 20 --printable`
    echo "${new_password}" > "$1"
    # Set permissions
    chmod $2 "$1"
    chown ${privusr}:${privgrp} "$1"
}

# Make it available to the post-installation scripts
export BINDADDR
export CLIENTADDR
export a_SGDSecure

SGDCLIENT="tcpclient"; [ "${a_SGDSecure}" = "y" ] && SGDCLIENT="sgd-ssl-client"
SGDWEBSOCKETCLIENT="websocket-client"; [ "${a_SGDSecure}" = "y" ] && SGDWEBSOCKETCLIENT="sgd-ssl-client"

[ -s "${INSTDIR}/etc/version" ] && . ${INSTDIR}/etc/version

mkdir -p ${INSTDIR}/httpd/httpd-${VERSION_APACHE}/conf/extra/gateway/servers 2>/dev/null
cp /dev/null ${INSTDIR}/httpd/httpd-${VERSION_APACHE}/conf/extra/gateway/servers/empty.conf
chown -R ${privusr}:${privgrp} "${INSTDIR}/httpd/httpd-${VERSION_APACHE}/conf/extra/gateway/servers" 2>/dev/null
chmod -R ${mode} "${INSTDIR}/httpd/httpd-${VERSION_APACHE}/conf/extra/gateway/servers" 2>/dev/null

    # Set security context on dynamically loadable Apache modules, if applicable (SELinux).
    # First try to find a security context that we can copy:
    sec_con_reference=""
    for sec_con_preferred in textrel_shlib_t texrel_shlib_t shlib_t; do
        sec_con_reference=`find /usr/lib -name '*.so' -print | xargs ls -dZ 2>/dev/null | grep ":${sec_con_preferred}" | sed 1q`
        [ -n "${sec_con_reference}" ] && {
            reference_file=`expr "${sec_con_reference}" : '.* \(/usr/lib/.*\)'`
            [ -n "${reference_file}" ] && (
                cd "${INSTDIR}/httpd/httpd-${VERSION_APACHE}/modules"
                chcon --reference="${reference_file}" *.so 2>/dev/null
            )
            break
        }
    done

# configure the web server
/bin/sh ${INSTDIR}/bin/scripts/config_install \
    --apachelocation="${INSTDIR}/httpd/httpd-${VERSION_APACHE}" \
    --apacheport="${REVERSEPROXYADDR}" \
    --machinename="`${INSTDIR}/bin/bin/ttahostname`" \
    --ttauser="${privusr}" \
    --ttagroup="${privgrp}" \
    --instdir="${INSTDIR}"

TidyScript=""

if ! ${UPGRADE}
then
    # clean install

    if ! [ -s "${INSTDIR}/etc/password" ]
    then
        # create SGD keystore password
        create_passwordfile "${INSTDIR}/etc/password" 600
    fi
    PASSWORD=`cat ${INSTDIR}/etc/password`

    if ! [ -s "${INSTDIR}/etc/password.reflection" ]
    then
        # create a reflection keystore password
        # Relax permission to allow group members read access
        create_passwordfile "${INSTDIR}/etc/password.reflection" 640
    fi
    PASSWORD_REFLECTION=`cat ${INSTDIR}/etc/password.reflection`
else
    # upgrade
    PASSWORD=`cat ${INSTDIR}/etc/password`

    if [ -f "${INSTDIR}/etc/password.reflection" ]; then
        PASSWORD_REFLECTION=`cat ${INSTDIR}/etc/password.reflection`
    else
        # Upgrading from an old Gateway version that has no separate reflection
        # password file. So create one and set the flag indicating that the
        # reflection keystore needs the password changing.

        # create a reflection keystore password
        # Relax permission to allow group members read access
        create_passwordfile "${INSTDIR}/etc/password.reflection" 640
        PASSWORD_REFLECTION=`cat ${INSTDIR}/etc/password.reflection`

        # The old keystore.reflection needs the password changing
        UPGRADE_PASSWORD_REFLECTION="t"
    fi
fi

###########################################################################
# Calculate tuning parameters
TUNING_DATA="${INSTDIR}/proxy/etc/tuning_data" TUNING_PARAMETERS="${INSTDIR}/proxy/etc/tuning_parameters"
vmem=''
case "${SCOARCH}" in
i3li* )
    vmem=`awk '/SwapTotal/{print int($2)}' /proc/meminfo | tail -1 | tr -cd "0123456789"` ;;
i3so* | spso* )
    vmem=`swap -s | sed -g 's/k//' | awk '{print int($9 + $11)}' | tail -1 | tr -cd "0123456789"` ;;
esac
# set a usable default if the calculation went wrong
[ -z "${vmem}" ] && vmem="1000000"
[ "${vmem}" -lt "1000000" ] && vmem="1000000"

# Do some arcane calculations as per CR:6747787
UM=`expr ${vmem} / 2`
echo "\
UM=${UM}
AIPMAXC=
WSMAXC=
HTTPC=" >${TUNING_DATA}
chmod ${mode} ${TUNING_DATA}
chown ${privusr}:${privgrp} ${TUNING_DATA}
HTTPC="100"
HTTPM=`expr 300 \* ${HTTPC}`
TMS="1400"
MAXS=`expr ${UM} - ${HTTPM}`
MAXS=`expr ${MAXS} / ${TMS}`
CS="4"
AIPMAXC="512"
WSMAXC="512"

heap="" heapbig="" heaphuge="" 
AIPMC="300"
AIPTOTAL=`expr ${AIPMAXC} + ${WSMAXC}`
Xms=`expr ${HTTPM} + ${AIPTOTAL} \* ${AIPMC} + 1023`
Xms=`expr ${Xms} / 1024`
Xms=`echo ${Xms} | awk '{print (int($0/64) + 1) * 64}'`	# round up to 64MB
Xmx="${Xms}"
heap="${Xms}"

# cap the ms/mx figures at 0.25 of the physical memory total
_pmem=''
case ${SCOARCH} in
i3li*)
    _pmem=`grep -i '^memtotal' /proc/meminfo | LANG=C LC_ALL=C tr -cd '[0-9]'`
    _units=`grep -i '^memtotal' /proc/meminfo | awk '{print $NF}' | LANG=C LC_ALL=C tr '[A-Z]' '[a-z]'`
    [ -n "${_pmem}" ] && {
	case "${_units}" in
	gb|gigabytes) _pmem=`expr ${_pmem} \* 1024`;;
	mb|megabytes) ;;
	*)  _pmem=`expr ${_pmem} / 1024`
	esac
    }
    ;;
*)  _prtconf=''
    for _dir in `echo "/usr/sbin:${PATH}" | tr : ' '`; do
	case "${_dir}" in
	/*) [ -x "${_dir}/prtconf" ] && { _prtconf="${_dir}/prtconf"; break; }
	esac
    done
    [ -x "${_prtconf}" ] && {
	_pmem=`LANG=C LC_ALL=C ${_prtconf} 2>/dev/null | grep -i '^memory' | LANG=C LC_ALL=C tr -cd '[0-9]'`
	_units=`LANG=C LC_ALL=C ${_prtconf} 2>/dev/null | grep -i '^memory' | awk '{print $NF}' | LANG=C LC_ALL=C tr '[A-Z]' '[a-z]'`
    }
    [ -n "${_pmem}" ] && {
	case "${_units}" in
	gb|gigabytes) _pmem=`expr ${_pmem} \* 1024`;;
	kb|kilobytes) _pmem=`expr ${_pmem} / 1024`;;
	esac
    }
esac
[ "${Xms:-0}" -gt 3584 ] && heaphuge="${Xms}" 	# 3584MB is 3.5GB (hard JVM limit)
[ -n "${_pmem}" ] && {
    _qmem=`expr ${_pmem} / 4`
    [ "${Xms:-0}" -gt "${_qmem:-0}" ] && heapbig="${Xms}"
    Xmx="${Xms}"
}

cp -p ${TUNING_DATA} ${TUNING_DATA}.$$ &&\
sed "s|AIPMAXC=.*|AIPMAXC=${AIPMAXC}|;s|HTTPC=.*|HTTPC=${HTTPC}|;s|WSMAXC=.*|WSMAXC=${WSMAXC}|" ${TUNING_DATA}.$$ >${TUNING_DATA}
rm -f ${TUNING_DATA}.$$ 2>/dev/null

cp -p ${TUNING_PARAMETERS} ${TUNING_PARAMETERS}.$$ &&\
( egrep -v '^(-Xms|-Xmx)' ${TUNING_PARAMETERS}.$$; echo "Xms${Xms}M"; echo "Xmx${Xmx}M" ) |
    sed 's/^Xm/-&/' >${TUNING_PARAMETERS}
rm -f ${TUNING_PARAMETERS}.$$ 2>/dev/null

[ -n "${heapbig}" ] && {
    echo
    printf "${i18n_heapwarn01_gw}" "${heapbig}"
    echo "${i18n_heapbig_gw}"
    echo "${i18n_referdoc_gw}"
}

# Generate the gatewayconfig xml
${INSTDIR}/bin/scripts/generate-gatewayconfig-xml.sh

# If the Include line for the REST config is not there
# add it in replacing the existing ProxyPass line which is
# now included in the REST configuration
includeStr="Include conf/extra/gateway/httpd-gateway-rest.conf"
apacheConf="${INSTDIR}/httpd/httpd-${VERSION_APACHE}/conf/extra/gateway/httpd-gateway.conf"
includePresent="$(grep "${includeStr}" "${apacheConf}")"
if [ -z "${includePresent}" ]
then
    awk -v includestr="${includeStr}" '
    {
        if ($0 ~ /ProxyPass \/ balancer:\/\/mysgdservers\/ lbmethod=byrequests stickysession=balanceid/ )
        {
            print "    "includestr
        }
        else
        {
            print $0
        }
    }' ${apacheConf} > ${apacheConf}.sgdg.tmp

    mv -f ${apacheConf}.sgdg.tmp ${apacheConf}
    chown ${privusr}:${privgrp} ${apacheConf}
fi

##########################################################################
# set up the java environment
#
JINST="$INSTDIR/java"
JHOME="${JINST}/default"
if [ -f "${JHOME}/lib/classes.zip" ]; then
    CLASSPATH="${JHOME}/lib/classes.zip:${JINST}"
    CLASSPATH_EXP='${JHOME}/lib/classes.zip:${JINST}'
elif [ -f "${JHOME}/lib/rt.jar" ]; then
    CLASSPATH="${JHOME}/lib/rt.jar:${JINST}"
    CLASSPATH_EXP='${JHOME}/lib/rt.jar:${JINST}'
else
    CLASSPATH=${JINST}
    CLASSPATH_EXP=${JINST}
fi
for jar in `ls ${JINST}/*.jar ${JINST}/*.zip 2>/dev/null`; do
    CLASSPATH="${CLASSPATH}:${JINST}/`basename ${jar}`"
    CLASSPATH_EXP="${CLASSPATH_EXP}:\${JINST}/`basename ${jar}`"
done
for jar in `ls ${JINST}/ext/*.jar ${JINST}/ext/*.zip 2>/dev/null`; do
    CLASSPATH="${CLASSPATH}:${JINST}/ext/`basename ${jar}`"
    CLASSPATH_EXP="${CLASSPATH_EXP}:\${JINST}/ext/`basename ${jar}`"
done
CLASSPATH="${CLASSPATH}:${JINST}/ext/jnet.jar"
CLASSPATH_EXP="${CLASSPATH_EXP}:\${JINST}/ext/jnet.jar"

isnumeric() {
   stripped=`echo "$1" | tr -cd '[0-9]'`
   [ -n "$1" -a "$1" = "${stripped}" ] && return 0 || return 1
}

default_clientaddr="`${INSTDIR}/bin/bin/ttahostname`:443"
default_gatewaymachinename=`expr "${default_clientaddr}" : '\(.*\):.*'`

client_cert_cn=`expr "${CLIENTADDR}" : '\(.*\):.*'`

GetValidity() {
    grep -i '^valid from' | tail -1
}
GetIssuer() {
    grep -i '^issuer' | sed 's/.*[cC][nN]=//;s/[, 	].*//' | LANG=C LC_ALL=C tr '[A-Z]' '[a-z]' | tail -1
}
ParseCertValidity() {
    # This is a bit fiddly, and relies on being able to get English language info
    # on cert validity, such as the following string (which is passed into this
    # function as $1):
    #
    # Valid from: Mon Jul 05 09:07:32 BST 2010 until: Sun Oct 03 09:07:32 BST 2010
    #
    # In the calculations the variables have the following meanings:
    # yearStart	Year of "Valid from" date (2010 in the above example)
    # yearEnd	Year of "Valid until" date (2010 ditto)
    # dayStart	Days from year start in "Valid from" date (186 ditto)
    # dayEnd	Days from year start in "Valid until" date (276 ditto)
    # We are deliberately ignoring leap years to simplify computation (it's bad enough already).
    yearStart="" yearEnd="" dayStart="" dayEnd=""
    Validity="$1 __END__"
    daysToMonthStart=""
    while [ -n "${Validity}" -a "${Validity}" != "__END__" ]; do
	tok=`echo "${Validity}" | sed 's/ .*//'`
	# figures below below are total number of days up to start of corresponding month
	# ignoring leap years
	case "${tok}" in
	Jan) daysToMonthStart=0   ;;
	Feb) daysToMonthStart=31  ;;
	Mar) daysToMonthStart=59  ;;
	Apr) daysToMonthStart=90  ;;
	May) daysToMonthStart=120 ;;
	Jun) daysToMonthStart=151 ;;
	Jul) daysToMonthStart=181 ;;
	Aug) daysToMonthStart=212 ;;
	Sep) daysToMonthStart=243 ;;
	Oct) daysToMonthStart=273 ;;
	Nov) daysToMonthStart=304 ;;
	Dec) daysToMonthStart=334 ;;
	[0-3][0-9])	# looks like a day number
	    case "${tok}" in
	    0[1-9]) tok=`expr "${tok}" : '.\(.\)'`	# remove leading zero from 2-digit number
	    esac
	    [ -z "${dayStart}" ] && \
		dayStart=`expr ${daysToMonthStart:-0} + ${tok}` || \
		dayEnd=`expr ${daysToMonthStart:-0} + ${tok}`
	    ;;
	2[0-9][0-9][0-9])	# looks like a year (needs fixing in year 3000 :-) )
	    [ -z "${yearStart}" ] && yearStart=${tok} || yearEnd=${tok}
	    ;;
	esac
	Validity=`echo "${Validity}" | sed 's/^[^ ]*  *//'`
    done
_valid=false
_pp="`echo ${dayStart}|sed 's/[0-9]//g'`"
if [ -z "$_pp" ]
then
    _valid=true
fi
_valds=$_valid

_valid=false
_pp="`echo ${dayEnd}|sed 's/[0-9]//g'`"
if [ -z "$_pp" ]
then
    _valid=true
fi
_valde=$_valid

_valid=false
_pp="`echo ${yearStart}|sed 's/[0-9]//g'`"
if [ -z "$_pp" ]
then
    _valid=true
fi
_valys=$_valid

_valid=false
_pp="`echo ${yearEnd}|sed 's/[0-9]//g'`"
if [ -z "$_pp" ]
then
    _valid=true
fi
_valye=$_valid

    [ "${_valds}" = true -a "${_valde}" = true -a "${_valys}" = true -a "${_valye}" = true ] && {
	echo "dayStart=${dayStart} dayEnd=${dayEnd} yearStart=${yearStart} yearEnd=${yearEnd}"
	return 0
    }
    return 1
}


# If there are no keystores then create them
# If there are keystores then upgrade them to use pkcs12 format
# (There's no simple way to test if they are pkcs12 already as far as I can tell)

if [ ! -s "${INSTDIR}/proxy/etc/keystore" ]
then
    ${GW_JAVA_DIR}/keytool \
        -genkeypair\
       	-alias "${OSGD_GW_ALIAS}" \
       	-dname "cn=${default_gatewaymachinename},O=Oracle Corporation Inc,ST=CA,C=US" \
       	-keyalg "RSA" \
       	-keypass "${PASSWORD}" \
       	-keystore "${INSTDIR}/proxy/etc/keystore" \
       	-storepass "${PASSWORD}" \
       	-validity 3600 \
        -storetype "${FORMAT_PKCS12}"

     chown ${privusr}:${privgrp} "${INSTDIR}/proxy/etc/keystore"
     chmod ${mode} "${INSTDIR}/proxy/etc/keystore"
else
     # Convert keystore to pkcs12
     ${GW_JAVA_DIR}/keytool \
     -importkeystore \
     -srckeystore "${KEYSTORE}" \
     -srcstorepass "${KeystorePassword}" \
     -deststoretype "${FORMAT_PKCS12}" \
     -destkeystore "${KEYSTORE}" \
     -deststorepass "${KeystorePassword}" >/dev/null 2>&1
fi

if [ ! -s "${INSTDIR}/proxy/etc/keystore.reflection" ]
then
    ${GW_JAVA_DIR}/keytool \
    -genkeypair\
    -alias "${OSGD_GW_ALIAS}" \
    -dname "cn=${default_gatewaymachinename},O=Oracle Corporation Inc,ST=CA,C=US" \
    -keyalg "RSA" \
    -keypass "${PASSWORD_REFLECTION}" \
    -keystore "${INSTDIR}/proxy/etc/keystore.reflection" \
    -storepass "${PASSWORD_REFLECTION}" \
    -validity 3600 \
    -storetype "${FORMAT_PKCS12}"

    chown ${privusr}:${privgrp} "${INSTDIR}/proxy/etc/keystore.reflection"
    chmod ${mode} "${INSTDIR}/proxy/etc/keystore.reflection"
else
    if [ -n "${UPGRADE_PASSWORD_REFLECTION}" ]
    then
        # Flag indicating that the reflection keystore
        # needs the password changing to use password.reflection
        # not the SGD keystore password.
        # Set password as part of the conversion to pkcs12.
        ${GW_JAVA_DIR}/keytool \
            -importkeystore \
            -srckeystore "${KEYSTORE}" \
            -srcstorepass "${PASSWORD}" \
            -deststoretype "${FORMAT_PKCS12}" \
            -destkeystore "${KEYSTORE}" \
            -deststorepass "${KeystorePassword}" \
            -destkeypass "${KeystorePassword}" >/dev/null 2>&1
    else
        # Convert keystore to pkcs12
        ${GW_JAVA_DIR}/keytool \
            -importkeystore \
            -srckeystore "${KEYSTORE}" \
            -srcstorepass "${KeystorePassword}" \
            -deststoretype "${FORMAT_PKCS12}" \
            -destkeystore "${KEYSTORE}" \
            -deststorepass "${KeystorePassword}" >/dev/null 2>&1
    fi
fi

# Create "keystore.client" cert if it doesn't exist
PVI="${INSTDIR}/proxy/var/info"
mkdir -p "${PVI}" 2>/dev/null
chown ${privusr} "${PVI}" 2>/dev/null
chgrp ${privgrp} "${PVI}" 2>/dev/null
chmod ${mode} "${PVI}" 2>/dev/null
if ! [ -s "${INSTDIR}/proxy/etc/keystore.client" ]
then
    # Create a keystore.client with a new self-signed cert in it
    OPENSSL=openssl
    OPENSSL_STORE=${PVI}/server.p12

    # Generate the self-signed cert for this gateway host
    TMP_DIR="${INSTDIR}/var/tmp" \
    OPENSSL_CONF="${INSTDIR}/etc/data/openssl.cnf" \
        ${INSTDIR}/bin/scripts/generate-self-signed-cert.sh \
            "${INSTDIR}/etc/password" \
            "${OPENSSL_STORE}" 1>>${INSTALL_LOG} 2>>${INSTALL_LOG}

    # keytool import new self-signed client cert.
    ${GW_JAVA_DIR}/keytool \
        -importkeystore \
        -srckeystore ${OPENSSL_STORE} \
        -srcstorepass ${PASSWORD} \
        -srcstoretype PKCS12 \
        -alias 1 \
        -destalias "${OSGD_GW_ALIAS}" \
        -destkeystore "${INSTDIR}/proxy/etc/keystore.client" \
        -deststorepass "${PASSWORD}" 1>>${INSTALL_LOG} 2>>${INSTALL_LOG}

    # Convert the keystore to pkcs12
    ${GW_JAVA_DIR}/keytool \
         -importkeystore \
         -srckeystore "${INSTDIR}/proxy/etc/keystore.client" \
         -srcstorepass "${PASSWORD}" \
         -destkeystore "${INSTDIR}/proxy/etc/keystore.client" \
         -deststorepass "${PASSWORD}" \
         -deststoretype "${FORMAT_PKCS12}" 1>>${INSTALL_LOG} 2>>${INSTALL_LOG}

    chown ${privusr}:${privgrp} \
        "${INSTDIR}/proxy/etc/keystore.client" \
        "${OPENSSL_STORE}"
    chmod ${mode} \
        "${INSTDIR}/proxy/etc/keystore.client" \
        "${OPENSSL_STORE}"
    cp -p "${INSTDIR}/proxy/etc/keystore.client" "${PVI}/."
fi

chmod ${mode} ${INSTDIR}/proxy/etc/keystore ${INSTDIR}/proxy/etc/keystore.reflection 2>/dev/null

# add to the rc after removing existing setup
mkdir -p $INSTDIR/var/tmp 2>/dev/null

if ${UPGRADE}
then
(
    # Migrate old configuration on upgrade
    cd ${INSTDIR}
    . etc/version.prev
    VERSION_APACHE_OLD="${VERSION_APACHE}"
    VERSION_JRE_OLD="${VERSION_JRE}"
    VERSION_SUNWsgdg_OLD="${VERSION_SUNWsgdg}"
    VERSION_SUNWsgdg_OLD_NUMERIC=`echo "${VERSION_SUNWsgdg_OLD}" | tr -d .`
    case "${VERSION_SUNWsgdg_OLD_NUMERIC}" in
    [0-9][0-9][0-9][0-9][0-9][0-9]) ;;
    *) VERSION_SUNWsgdg_OLD_NUMERIC=0
    esac
    . etc/version
    [ "${VERSION_SUNWsgdg_OLD_NUMERIC}" -gt 0 ] && {
	upgradelog="proxy/var/log/upgrade_${VERSION_SUNWsgdg_OLD}_${VERSION_SUNWsgdg}.log"
	:>${upgradelog}

	exec 2>${upgradelog}.dbg;set -x	#::TODO::BW - DEBUG ONLY, NOT FOR SHIPPING

	# "Preserved" means that the pre-upgrade version of the file has been brought forward
	# into the post-upgrade configuration.  If a file of the same name already existed
	# in the post-upgrade configuration, it has been saved as "<filename>.<newversion#>"
	Preserved="var/tmp/SUNWsgdg1.$$"; :>${Preserved}
	# "Available" means that the pre-upgrade version of the file has been brought forward
	# into the post-upgrade configuration under the name "<filename>.<oldversion#>".
	# It is not active; any useful configuration that it contains will have to be merged
	# manually into "<filename>".
	Available="var/tmp/SUNWsgdg2.$$"; :>${Available}

	find . -type f -print | egrep "/.*\.${VERSION_SUNWsgdg_OLD}/" | while read of
    do
        of=`expr "${of}" : '\./\(.*\)'`
        
        case "${of}" in
            httpd/httpd-*)
                nf=`echo "${of}" | sed "s|\.${VERSION_SUNWsgdg_OLD}/|/|;s|^\(httpd/httpd-\)[^/]*|\1${VERSION_APACHE}|"`
                ;;
            *)
                nf=`echo "${of}" | sed "s|\.${VERSION_SUNWsgdg_OLD}/|/|"`
        esac

	    if cmp -s "${of}" "${nf}"
        then
            # old and new versions identical
            rm -f "${of}"
	    elif [ ! -s "${nf}" ]
        then
            # file exists only in old version
            mv "${of}" "${nf}"
            echo "${nf}" >>${Preserved}
	    else
            # old and new versions differ
            case "${nf}" in
                httpd/httpd-*/conf/extra/gateway/*)
                    mv "${of}" "${nf}.${VERSION_SUNWsgdg_OLD}"
                    echo "${nf}.${VERSION_SUNWsgdg_OLD}" >>${Available}
                    ;;
                httpd/httpd-*)
                    # for Apache conf files, find out if the difference is *only* in the embedded version numbers and user/group
                    sed "s/${VERSION_APACHE_OLD}/@@VERSION_APACHE@@/g;s/^User .*$/@@USER@@/g;s/^Group .*$/@@GROUP@@/g" "${of}" >"${of}.noversion"
                    sed "s/${VERSION_APACHE}/@@VERSION_APACHE@@/g;s/^User .*$/@@USER@@/g;s/^Group .*$/@@GROUP@@/g"     "${nf}" >"${nf}.noversion"
                    
                    if cmp -s "${of}.noversion" "${nf}.noversion"
                    then
                        # old and new versions identical
                        rm -f "${of}"
                    else
                        # old and new versions differ - and not just by version number
                        mv "${of}" "${nf}.${VERSION_SUNWsgdg_OLD}"
                        echo "${nf}.${VERSION_SUNWsgdg_OLD}" >>${Available}
                    fi
                    rm -f "${of}.noversion" "${nf}.noversion"
                    ;;
                proxy/etc/keystore | proxy/etc/keystore.reflection | proxy/etc/keystore.client)
                    mv "${of}" "${nf}.${VERSION_SUNWsgdg_OLD}"
                    echo "${nf}.${VERSION_SUNWsgdg_OLD}" >>${Available}
                    ;;
                etc/version*)
                    rm "${of}"
                    ;;
                etc/ciphersuites.xml)
                    mv "${of}" "${nf}.${VERSION_SUNWsgdg_OLD}"
                    echo "${nf}.${VERSION_SUNWsgdg_OLD}" >>${Available}
                    ;;
                etc/gateway-*.xml)
                    mv "${of}" "${nf}.${VERSION_SUNWsgdg_OLD}"
                    # migrate pre-upgrade gateway.xml settings to new gateway.xml file
                    mv "${nf}" "${nf}.${PRODUCT_VERSION_FULL}"
                            ERR_LOG=${INSTDIR}/var/tmp/err.log
                    echo "GatewayUpgrade ${nf}" >>${upgradelog}
                    ${GW_JAVA_DIR}/java -classpath proxy/jarp.jar:lib/* config.GatewayUpgrade \
                    "${VERSION_SUNWsgdg_OLD}" "${nf}.${VERSION_SUNWsgdg_OLD}" \
                    "${PRODUCT_VERSION_FULL}" "${nf}.${PRODUCT_VERSION_FULL}" \
                    "${nf}" 2> "${ERR_LOG}"
                    if [ -s "${ERR_LOG}" ]; then
                        cat ${ERR_LOG} | tee -a ${upgradelog}
                        rm "${ERR_LOG}"
                    fi
                    echo "${nf}" >>${Preserved}
                    ;;
                *)  mv "${of}" "${nf}.${VERSION_SUNWsgdg_OLD}"
                    echo "${nf}.${VERSION_SUNWsgdg_OLD}" >>${Available}
            esac
	    fi
	done

	[ -s "${Preserved}" ] && (
	    printf "${i18n_upgpreserved01_gw}" "${VERSION_SUNWsgdg_OLD}"; echo
	    cat ${Preserved}
	) >>${upgradelog}
	[ -s "${Available}" ] && (
	    printf "${i18n_upgavailable01_gw}" "${VERSION_SUNWsgdg_OLD}"; echo
	    cat ${Available}
	) >>${upgradelog}
	rmdir `find . -depth -type d -name "*.${VERSION_SUNWsgdg_OLD}" -print` 2>/dev/null
	rm -f ${Preserved} ${Available} 2>/dev/null
    }
)
fi

### 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 var/info if needed
if [ ! -d ${INSTDIR}/var/info ] ; then
  mkdir -p ${INSTDIR}/var/info  2>/dev/null
  chown ${privusr}:${privgrp} ${INSTDIR}/var/info 2>/dev/null
  chmod ${mode} ${INSTDIR}/var/info 2>/dev/null
fi
# Create a new patch cfg with the correct version
echo "${PATCH_VERSION} : ${VERSION_SUNWsgdg}" > ${PATCH_CFG}
chown ${privusr}:${privgrp} "${PATCH_CFG}" 2>/dev/null
chmod ${mode} "${PATCH_CFG}"

# Empty the file so the server is now configured.
# Keep the file to avoid rpm warnings on OL7
echo "" > "${configure}"

[ -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


# Make sure all files have correct ownership
chown -R ${privusr}:${privgrp} ${INSTDIR}

exit 0
