#!/bin/bash
# Copyright (c) 2009, 2020, Oracle and/or its affiliates.
#
#  Component: Secure Global Desktop Gateway
#  Author: Bill Weir

machinearch ()
{
#!/bin/sh
#  $Id: ixiarch.sh 23561 2012-05-15 08:22:43Z ww161634 $
#  Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved.
#  This software code contains proprietary information
#  and should be treated as confidential.
#
#  Print canonical syscode for platform

# There are three valid types of command line:
#
# 1.     visionarch
# 2.     visionarch <available codes>...
# 3.	 visionarch [-c|-o]
#
# 1. The architecture is echoed
# 2. The best architecture from the list is returned
# 3. The -c and -o options return just the system Code or the OS type.

# 0) INITIALIZE VARIABLES

# Some of these are historical, but dont cause any harm
PATH=/bin:/usr/bin:/sbin:/usr/sbin:$XDTHOME/bin:$PMWMHOME/bin:$IXIHOME/bin:$PATH


# 1) Arguments
numcodes=0
for i
do
  case $i in
    -c )
      codeonly=1
    ;;
  
    -o )
      osonly=1
    ;;

    -n )
      if [ -z "$codeonly" -a -z "$osonly" ]
      then
	  displayname=1	
      fi
    ;;
 
    * )
      checkcodes="$checkcodes $i"
      numcodes=`expr $numcodes + 1`
    ;;

   esac
done

# fast exit
if [ $numcodes = 1 ]
then
  echo $checkcodes
  exit 0
fi


# 2) MESSAGES
myname=`basename $0`

#  First define some messages.
#  They get overwritten by sourcing from a file, scripts.ll_TT,
#  so there's no need to translate them here.  

#  Messages for the visionarch script.
#  These follow text like "visionarch: !4! ", and may extend to several lines.
msg_xdtarch_no_uname=\
'No uname command found.'
msg_xdtarch_os_cpu=\
'Cannot recognize the Operating System or processor type.'
msg_xdtarch_ver_rel=\
'Cannot calculate version or release.'
msg_xdtarch_no_match=\
'Cannot find matching installed system.'

#  End of messages
# Try to find a language script
posslangfiles=""
for lang in C $IXILANG $PANLANG $LANG
do
  for pathname in $XDTHOME/bin/scripts. $PMWMHOME/bin/scripts. $IXIHOME/bin/scripts. ./scripts.
  do
    posslangfiles="$posslangfiles $pathname.$lang"
  done
done

# see if we can find one of those language files
for f in $posslangfiles
do
  if [ -f $f ]
  then
    . $scriptslangfile			# source it
    break
  fi						
done
  
# 3) TRY UNAME AND SET UP VARIABLES

unamev=`uname -v 2>/dev/null`
if [ $? -ne 0 ]
then
  # This isn't really a UNIX system is it?
  echo >&2  "$myname: !2! $msg_xdtarch_no_uname"
  exit 2
fi

U_SYSTEM=`uname -s 2>/dev/null`  || U_SYSTEM=UNKNOWN
U_RELEASE=`uname -r 2>/dev/null` || U_RELEASE=UNKNOWN
U_VERSION=`uname -v 2>/dev/null` || U_VERSION=UNKNOWN

# Some machines use -m arg to return 'model' rather
# than architecture.  For example, NCR SVR4 returns
# 3433,3434.  On such machines need to use -p which
# returns processor.

for MACHARG in m p
do
    U_MACHINE=`uname -"$MACHARG" 2>/dev/null` || U_MACHINE=UNKNOWN

    # 4)  FIND THE MACHINE
    # Note that we only look for cpu/os combinations our products currently
    # support - if you want better matching, most GNU software comes with
    # a script called 'config.guess' which does a more thorough job (and
    # has totally different output!)

    CPU= 			# Characters 1-2 of syscode
    OS= 			# Characters 3-4 of syscode
    VER=			# Digits 5-6 of syscode
    REL= 			# Digits 7-8 of syscode


    case ${U_MACHINE}::${U_SYSTEM}::${U_RELEASE}::${U_VERSION} in
      # Intel FreeBSD
      i*::FreeBSD::*:* )
        CPU=i3
        OS=fb
        NAME="FreeBSD (Intel)"
        VER=`expr $U_RELEASE : '[^0-9]*\([0-9][0-9]*\)[^0-9]'`
        REL=`expr $U_RELEASE : '[^0-9]*[0-9][0-9]*[^0-9]\([0-9][0-9]*\)'`
       ;;
      # MacOS X
      powerpc::Darwin::*::*)
        CPU=pp
        OS=dw
        NAME="Darwin (PowerPC)"
        VER=`expr $U_RELEASE : '[^0-9]*\([0-9][0-9]*\)[^0-9]'`
        REL=`expr $U_RELEASE : '[^0-9]*[0-9][0-9]*[^0-9]\([0-9][0-9]*\)'`
       ;;
      # MacOS X (Intel)
      i386::Darwin::*::*)
        CPU=i3
        OS=dw
        NAME="Darwin (Intel)"
        VER=`expr $U_RELEASE : '[^0-9]*\([0-9][0-9]*\)[^0-9]'`
        REL=`expr $U_RELEASE : '[^0-9]*[0-9][0-9]*[^0-9]\([0-9][0-9]*\)'`
       ;;
      # PowerPC Linux
      ppc*::Linux::*::*)
        CPU=pp
        OS=li
        NAME="Linux (PowerPC)"
        VER=`expr $U_RELEASE : '[^0-9]*\([0-9][0-9]*\)[^0-9]'`
        REL=`expr $U_RELEASE : '[^0-9]*[0-9][0-9]*[^0-9]\([0-9][0-9]*\)'`
       ;;
      # Intel Linux
      i*::Linux::*::* )
	CPU=i3
	OS=li
	NAME="Linux (Intel)"
	VER=`expr $U_RELEASE : '[^0-9]*\([0-9][0-9]*\)[^0-9]'`
	REL=`expr $U_RELEASE : '[^0-9]*[0-9][0-9]*[^0-9]\([0-9][0-9]*\)'`
      ;;
      # Athlon 64 Linux
      x86_64::Linux::*::* )
	CPU=i3
	OS=li
	NAME="Linux (AMD 64)"
	VER=`expr $U_RELEASE : '[^0-9]*\([0-9][0-9]*\)[^0-9]'`
	REL=`expr $U_RELEASE : '[^0-9]*[0-9][0-9]*[^0-9]\([0-9][0-9]*\)'`
      ;;
      # PowerPC Linux
      ppc*::Linux::*::* )
        CPU=pp
        OS=li
        NAME="Linux (PowerPC)"
        VER=`expr $U_RELEASE : '[^0-9]*\([0-9][0-9]*\)[^0-9]'`
        REL=`expr $U_RELEASE : '[^0-9]*[0-9][0-9]*[^0-9]\([0-9][0-9]*\)'`
       ;;
      # Sequent (Intel)
      i*::DYNIX*::*::* )
	CPU=i3
	OS=dy
	NAME="Sequent DYNIX/ptx (Intel)"
	VER=`expr $U_VERSION : 'V\([0-9]\).*'`
	REL=`expr $U_VERSION : 'V[0-9].\([0-9].[0-9]\)' | sed 's/\.//g'`
      ;;

      # The Sun family
      *::SunOS::4.*::* )
	CPU=sp
	OS=su
	VER=4
	NAME="Sun SunOS (Sparc)"
	REL=`expr $U_RELEASE : '4.\([^_]*\)' | sed 's/[^0-9]//g'`
      ;;
      sun*::SunOS::5.*::* )
	CPU=sp
	OS=so
	VER=5
	NAME="Sun Solaris (Sparc)"
	REL=`expr $U_RELEASE : '5.\([0-9][0-9]*\).*' | sed 's/[^0-9]//g'`
      ;;
      *86*::SunOS::5.*::* )
	CPU=i3
	OS=so
	VER=5
	NAME="Sun Solaris (Intel)"
	REL=`expr $U_RELEASE : '5.\(.*\)' | sed 's/[^0-9]//g'`
      ;;
      *::SunOS::5.*::* )
	CPU=sp
	OS=so
	VER=5
	NAME="Sun Solaris (Sparc)"
	REL=`expr $U_RELEASE : '5.\([0-9][0-9]*\).*' | sed 's/[^0-9]//g'`
      ;;

      # HP
      *::HP-UX::*::* )
	CPU=pa
	OS=hp
	NAME="Hewlett-Packard HP-UX (PA-RISC)"
	VER=`expr $U_RELEASE : '[^.]*.\([0-9]*\).*'`
	REL=`expr $U_RELEASE : '[^.]*.[^.]*.\([0-9]*\)'`
      ;;

      # Data General
      *::dgux::5.4*::* )
	CPU=m8
	OS=dg
	VER=54
	NAME="Data General DG/UX (Motorola)"
	REL=`expr $U_RELEASE : '5.4\(.*\)' | sed 's/[^0-9]//g' | sed 's/\(.\).*\(.\)$/\1\2/'`
      ;;

      # Data General on Intel
      *::dgux::R4*::* )
	case `uname -p`  in
	  m* )
	    CPU=m8 ;;
	  * )
	    CPU=i3 ;;
	esac
	OS=dg
	VER=04
	NAME="Data General DG/UX (Intel)"
	REL=`expr $U_RELEASE : 'R4.\(.*\)' | sed 's/[^0-9]//g'`
        REL=`echo $REL | sed 's/\(..\).*/\1/'`
      ;;

      # OSF/1
      alpha::OSF1::*::* )
	CPU=ax
	OS=o1
	NAME="DEC OSF/1 (Alpha)"
	VER=`echo $U_RELEASE | sed 's/\([^.]*\).*/\1/' | sed 's/[^0-9]//g'`
	REL=`echo $U_RELEASE | sed 's/[^.]*.\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;

      # ULTRIX
      *::ULTRIX::*::* )
	CPU=mp
	OS=ul
	NAME="DEC Ultrix (MIPS)"
	VER=`echo $U_RELEASE | sed 's/\([^.]*\).*/\1/' | sed 's/[^0-9]//g'`
	REL=`echo $U_RELEASE | sed 's/[^.]*.\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;

      # IRIX
      *::IRIX::4.*::* )
	CPU=mp
	OS=ir
	VER=`echo $U_RELEASE | sed 's/\([^.]*\).*/\1/' | sed 's/[^0-9]//g'`
	REL=`echo $U_RELEASE | sed 's/[^.]*.\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;
      
      *::IRIX::5.1::* )
	CPU=mp
	OS=ir
	VER=`echo $U_RELEASE | sed 's/\([^.]*.[^.]*\).*/\1/' | sed 's/[^0-9]//g'`
	REL=`echo $U_RELEASE | sed 's/[^.]*.[^.]*.\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;

      # Note
      # If we ever get minor release numbers of 5.2 we'll have to do
      # something different
      *::IRIX::5.2::* )
	CPU=mp
	OS=ir
	VER=`echo $U_RELEASE | sed 's/\([^.]*\).*/\1/' | sed 's/[^0-9]//g'`
	REL=20
      ;;
      # Note
      # This system does not exist yet
      *::IRIX::5.2.*::* )
	CPU=mp
	OS=ir
	VER=`echo $U_RELEASE | sed 's/\([^.]*\).*/\1/' | sed 's/[^0-9]//g'`
	REL=`echo $U_RELEASE | sed 's/[^.]*.\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;

      # catchall for other irix versions
      # 6.4 and later change from IRIX to IRIX64
      *::IRIX*::*::* )
	CPU=mp
	OS=ir
	VER=`echo $U_RELEASE | sed 's/\([^.]*\).*/\1/' | sed 's/[^0-9]//g'`
	REL=`echo $U_RELEASE | sed 's/[^.]*.\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;

      # AIX
      # note that we can't figure out the patch level of a 3.2.x (x<4)
      # system (even IBM can't tell you immediately!)
      *::AIX::*::* )
	CPU=rs
	OS=ai
	NAME="IBM AIX (Risc)"
	VER=$U_VERSION
	REL=$U_RELEASE
      ;;

      # RISC OS (the mips variety, not acorn)
      # version 5 like output
      mips::*::*::RISCos )
	CPU=mp
	OS=ro
	VER=`echo $U_RELEASE | sed 's/\([^.]*\).*/\1/' | sed 's/[^0-9]//g'`
	REL=`echo $U_RELEASE | sed 's/[^.]*.\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;
      # version 4 like output
      mips::*::*::UMIPS )
	CPU=mp
	OS=ro
	VER=`echo $U_RELEASE | sed 's/\([0-9]*\).*/\1/'`
	REL=`echo $U_RELEASE | sed 's/[0-9]*\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;

      # Siemens Nixdorf mips R4000 (at least)
      R4000::*::*::* )
	CPU=mp
	OS=sx
	NAME="Siemens Nixdorf SINIX (MIPS)"
	VER=`echo $U_RELEASE | sed 's/\([0-9]*\).*/\1/'`
	REL=`echo $U_RELEASE | sed 's/[0-9]*\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;

      # Motorola SVR4
      *88*::*::4*::* )
	CPU=m8
	OS=mo
	VER=`expr $U_VERSION : '[^V]*.\([^.]*\).*' | sed 's/[^0-9]//g'`
	REL=`expr $U_VERSION : '[^V]*.[^.]*.\(.*\)' | sed 's/[^0-9]//g'`
      ;;

      # windows nt with nutcracker
      *::Windows_NT::*::* )
	CPU=i3
	OS=wi
	VER="$U_RELEASE"
	REL="$U_VERSION"
      ;;

      DRS*::*::*::* )
	  PROC=`uname -p 2>/dev/null` || PROC=UNKNOWN
	  case "$PROC" in
	    sparc | SPARC )
	      CPU=sp
	      OS=nx
	      NAME="ICL DRS/NX (Sparc)"
	      ;;
	    i386 )
	      CPU=i386
	      OS=nx
	      NAME="ICL DRS/NX (Intel)"
	      ;;
	  esac

	  VER=`expr $U_VERSION : '\([0-9]\).*'`
	  REL=`expr $U_VERSION : '[0-9]..*\([0-9].[0-9]\)' | sed 's/\.//g'`
      ;;

      
      *::UnixWare::*::* )
	CPU=i3
	OS=un
	NAME="SCO UnixWare (Intel)"
	VER=`expr $U_VERSION : '\([0-9]\)'`
	REL=`expr $U_VERSION : '[0-9].\(.*\)' | sed -e 's/\.//'`
	if [ -z "$REL" ]; then
		REL=00
        elif [ "x`expr $REL : '[0-9]\([0-9]\)'`" = "x" ] ; then
		REL="$REL"0
	fi
	;;

      *::OpenUNIX::*::* )
        CPU=i3
        OS=un
        NAME="SCO UnixWare (Intel)"
        VER=`expr $U_VERSION : '\([0-9]\)'`
        REL=`expr $U_VERSION : '[0-9].\(.*\)' | sed -e 's/\.//'`
        if [ -z "$REL" ]; then
                REL=00
        elif [ "x`expr $REL : '[0-9]\([0-9]\)'`" = "x" ] ; then
                REL="$REL"0
        fi
        ;;

      # Various Intel based Unixen.  These seem particularly reluctant
      # to divulge their OS name, so we have to grep through
      # various system files to find the OS string

      *86*::*::*::* )
	if grep -s -i UnixWare /stand/boot 2>/dev/null 1>&2 || strings /stand/1/unix_mp 2>/dev/null | grep -s -i Unixware 2>/dev/null 1>&2
	then
          # It's some version of Unixware obviously
	  CPU=i3
	  OS=un
	  NAME="SCO UnixWare (Intel)"
          if expr $U_VERSION : 'D\([0-9]*.*\)' 2>/dev/null 1>&2
	  then
            # It's a date stamped version ; we dont yet know how to figure out
            # which so just pretend that it is unixware 212
            VER=02
            REL=12
          else
	    VER=`expr $U_VERSION : '\([0-9]\)'`
	    REL=`expr $U_VERSION : '[0-9].\(.*\)' | sed -e 's/\.//'`
	    if [ "x`expr $REL : '[0-9]\([0-9]\)'`" = "x" ] 
	    then
		REL="$REL"0
	    fi
          fi
	else
	  if [ "$U_SYSTEM" = "SCO_SV" ]
	  then
	    CPU=i3
	    OS=sc
	    VER=`expr $U_RELEASE : '^\([0-9]*\)'`
	    NAME="SCO OpenServer (Intel)"
	    # just the release string ie: 3.2v5.0.0
	    relstr=`uname -X | grep Release | awk '{ print $3 }'`
	    # just the major SCO version after the SVR? (3.2v) bit
	    U_VERSION=`expr ${relstr} : '[0-9.]*v\([0-9]\)[0-9.]*'`
	    REL=`expr ${U_RELEASE}::${U_VERSION} : '[0-9]*\(.*\)' | sed 's/[^0-9]//g'`
	  else
	    if grep -s 'The Santa Cruz Operation' /etc/gettydefs 2>/dev/null 1>&2
	    then
	      CPU=i3
	      OS=sc
	      NAME="SCO Unix (Intel)"
	      VER=`expr $U_RELEASE : '^\([0-9]*\)'`
	      REL=`expr ${U_RELEASE}::${U_VERSION} : '[0-9]*\(.*\)' | sed 's/[^0-9]//g'`
	    else
	      # DYNIX/ptx V2 doesn't return 'DYNIX' or 'ptx' in uname.
	      # This kludge may work, may not, it's either this
	      # or flip a coin!   
	      if grep -s 'ptx' /etc/versionlog 2>/dev/null 1>&2
	      then
		CPU=i3
		OS=dy
		NAME="Sequent DYNIX/ptx (Intel)"
		VER=`expr $U_VERSION : 'V\([0-9]\).*'`
		REL=`expr $U_VERSION : 'V[0-9].\([0-9].[0-9]\)' | sed 's/\.//g'`
	      else
	        # Assume OS must be System V Release 4.
	        CPU=i3
	        OS=sv
		NAME="System V Release 4 (Intel)"
	        VER=`expr $U_RELEASE : '^\([0-9]*\)'`
	        REL=`expr ${U_RELEASE}::${U_VERSION} : '[0-9]*\(.*\)' | sed 's/[^0-9]//g'`
	      fi
	    fi
	  fi
	fi
	;;	
    esac

    if [ -n "$CPU" -a -n "$OS" -a -n "$VER" -a -n "$REL" ]
    then
	break
    fi
done

# 5) Do sanity checking and cleanup
VER=`echo $VER | sed 's/[^0-9]//g'`
REL=`echo $REL | sed 's/[^0-9]//g'`

if [ -z "$CPU" -o -z "$OS" ]
then
  echo "$myname: !10! $msg_xdtarch_os_cpu"
  exit 10
fi

if [ -z "$VER" -o -z "$REL" ]
then
  echo "$myname: !11! $msg_xdtarch_ver_rel"
  exit 11
fi

# Add leading zeroes
REL=`echo 0$REL | sed 's/.*\(..\)/\1/'`
VER=`echo 0$VER | sed 's/.*\(..\)/\1/'`

# 6) So we now know it all

syscode=$CPU$OS$VER$REL

if  test -n "$codeonly"
then
    echo $CPU$OS
    exit 0
fi

if  test -n "$osonly"
then
    echo $VER$REL
    exit 0
fi

# 7) Check for codes given on the command line

if [ ! -z "$checkcodes" ]
then
    for i in $checkcodes
    do
	# Filter the input $checkcodes by matching CPU and OS, and strip
	# them off leaving just the VER and REL.  The tr command replaces
	# spaces by line-feeds, so that the following sort can do its stuff.
	posscodes=`echo $checkcodes | tr ' ' '\012' \
				| sed -ne "s/$CPU$OS//p" | sort -n`
	if [ -z "$posscodes" ]
	then				# None supplied for correct CPU+OS
	    echo >&2 "$myname: !5! $msg_xdtarch_no_match"
	    exit 5
	fi 

	# Some of them are the right platform.
	# The following algorithm returns the greatest possible code which
	# is older than this syscode, or, failing that, the least possible
	# code which is more recent than this one.

	for ver_rel in $posscodes
	do
	    if [ $VER$REL -eq $ver_rel ]
	    then 			# bingo we have this exact release
		echo $syscode
		exit 0
	    elif [ $VER$REL -gt $ver_rel ]
	    then 			# store this previous version
		priorcode=$CPU$OS$ver_rel
	    else 			# $VER$REL is < $ver_rel
		if [ -n "$priorcode" ]
		then
		    echo $priorcode
		    exit 0
		else
		    # Oh dear, we have no previous version so we should use
		    # the oldest newer version which is this current one ...
		    echo $CPU$OS$ver_rel
		    exit 0
		fi
	    fi
	done
    done
    if [ -n "$priorcode" ]
    then
        echo $priorcode
        exit 0
    fi
else
    if [ -n "$displayname" ]
    then
	echo "$NAME"
    else
	echo $syscode
    fi
fi

}
MACHINEARCH=`machinearch`

SCOARCH=${MACHINEARCH} export SCOARCH
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="--------------------------------------------------------------------------"

privusr="sgdgsys"
privgrp="sgdgserv"

mode=750


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

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

TEMPLATES_PATH="${INSTDIR}/etc/templates"
GWCONF="${INSTDIR}/etc/gatewayconfig.xml"
TUNING_DATA="${INSTDIR}/proxy/etc/tuning_data"
TUNING_PARAMETERS="${INSTDIR}/proxy/etc/tuning_parameters"
IPV6_PARAMETERS="${INSTDIR}/proxy/etc/ipv6_parameters"

usage() {
    echo "${i18n_configusage10_gw}"
    exit 1
}

usage_create() {
    case "$1" in '' | --help) ;; *) printf "${i18n_badarg01_gw}" "$1" ;; esac
    echo "${i18n_configcreateusage40_gw}"
    exit 1
}

usage_list() {
    case "$1" in '' | --help) ;; *) printf "${i18n_badarg01_gw}" "$1" ;; esac
    echo "${i18n_configlistusage10_gw}"
    exit 1
}

usage_edit() {
    case "$1" in '' | --help) ;; *) printf "${i18n_badarg01_gw}" "$1" ;; esac
    echo "${i18n_configeditusage10_gw}"
    exit 1
}

usage_enable() {
    case "$1" in '' | --help) ;; *) printf "${i18n_badarg01_gw}" "$1" ;; esac
    echo "${i18n_configenableusage10_gw}"
    exit 1
}

usage_disable() {
    case "$1" in '' | --help) ;; *) printf "${i18n_badarg01_gw}" "$1" ;; esac
    echo "${i18n_configdisableusage10_gw}"
    exit 1
}

GetTag() {
    status=0
    cfg="${TMPDIR:-/tmp}/SUNWsgdg.$$"
    rm -rf ${cfg} 2>/dev/null
    # get the XML file on a single line to simplify parsing
    tr -d ' ' <$2 | tr -d '\012' >${cfg}
    echo >>${cfg}
    if [ -z "`egrep \"<$1>..*</$1>\" ${cfg}`" ]; then
	status=1  # tag-endtag pair missing
    elif [ -n "`egrep \"<$1>.*<$1>\" ${cfg}`" ]; then
	status=2  # duplicate tag
    else
	sed "s|.*<$1>||;s|</$1>.*||" ${cfg}	# extract value
    fi
    rm -f ${cfg} 2>/dev/null
    return ${status}
}

# Set a tags value in the gateway config
# Usage: SetTag <tag> <value>
# <tag> The name of the tag to set
# <value> the value to set the tag
#
# The tag will be set in the gateway config file and
# also in any tag specific config file (if there is one)
SetTag() {
    tag="$1"
    value="$2"
    if [ -n "$tag" ]
    then
        tagfile="${INSTDIR}/etc/${tag}.xml"
        if [ -f "${tagfile}" ]
        then
            placeholder=`sed 's/</ /g;s/>/ /' ${tagfile} | awk '{print $2}'`
            cp -p ${tagfile} ${tagfile}.$$ &&\
            sed "s|${placeholder}|${value}|" ${tagfile}.$$ >${tagfile}
            rm -f ${tagfile}.$$ 2> /dev/null
        fi
        cp -p ${GWCONF} ${GWCONF}.$$ &&\
        sed "s|<${tag}>.*</${tag}>|<${tag}>${value}</${tag}>|" ${GWCONF}.$$ >${GWCONF}
        rm -f ${GWCONF}.$$ 2>/dev/null
    fi
}

config_interactive() {
    BINDADDR=`GetTag binding ${GWCONF}`
    CLIENTADDR=`GetTag clientaddr ${GWCONF}`
    SGDCLIENT=`GetTag sgdclient ${GWCONF}`
    SGDWEBSOCKETCLIENT=`GetTag sgdwebsocketclient ${GWCONF}`
    a_SGDSecure="${i18n_s_no}"
    [ "${SGDCLIENT}" = "sgd-ssl-client" ] && a_SGDSecure="${i18n_s_yes}"
    while :; do
[ "NOPROMPT" != "NOPROMPT" ] && echo "NOPROMPT"
echo # blank line between prompt and question
_valid=false
while [ $_valid = false ]
do
  echo $N "$i18n_q_gatewayport_gw [$BINDADDR] $C"
  read _answer
  if [ -z "$_answer" ]
  then
    _answer="$BINDADDR"   # default
  fi
  _valid=true
done
BINDADDR="$_answer"

	case "${BINDADDR}" in
	*:*) BINDPORT=`expr "${BINDADDR}" : '.*:\(.*\)'`
	     probe="$INSTDIR/bin/bin/ttahostprobe `${INSTDIR}/bin/bin/ttahostname`:${BINDPORT}"
	     [ "`${probe}`" = "y" ] && { echo; printf "${i18n_portinuse01_gw}" "${BINDPORT}"; }
	     break
	esac
	echo
	echo "${i18n_interfaceandport_gw}"
    done
    case "${BINDADDR}" in
    [a-zA-Z]*:*) CLIENTADDR="${BINDADDR}"
    esac
    while :; do
[ "NOPROMPT" != "NOPROMPT" ] && echo "NOPROMPT"
echo # blank line between prompt and question
_valid=false
while [ $_valid = false ]
do
  echo $N "$i18n_q_clientaddr10_gw [$CLIENTADDR] $C"
  read _answer
  if [ -z "$_answer" ]
  then
    _answer="$CLIENTADDR"   # default
  fi
  _valid=true
done
CLIENTADDR="$_answer"

	case "${CLIENTADDR}" in
	*:*) CLIENTPORT=`expr "${CLIENTADDR}" : '.*:\(.*\)'`
	     probe="$INSTDIR/bin/bin/ttahostprobe `${INSTDIR}/bin/bin/ttahostname`:${CLIENTPORT}"
	     [ "`${probe}`" = "y" ] && { echo; printf "${i18n_portinuse01_gw}" "${CLIENTPORT}"; }
	     break
	esac
	echo
	echo "${i18n_interfaceandport_gw}"
    done
[ -z "${i18n_yes}" ] && i18n_yes="${a_yes}"
[ -z "${i18n_no}" ] && i18n_no="${a_no}"
[ -z "${i18n_case_yes}" ] && i18n_case_yes="${a_case_yes}"
[ -z "${i18n_case_no}" ] && i18n_case_no="${a_case_no}"
[ -z "${i18n_s_yes}" ] && i18n_s_yes="${s_yes}"
[ -z "${i18n_s_no}" ] && i18n_s_no="${s_no}"
[ "NOPROMPT" != "NOPROMPT" ] && echo "NOPROMPT"
echo # blank line between prompt and question
_valid=false
while [ $_valid = false ]
do
  echo $N "$i18n_q_sgdsecure_gw [$a_SGDSecure] $C"
  read _answer
  if [ -z "$_answer" ]
  then
    _answer="$a_SGDSecure"   # default
  fi
  case "$_answer" in
    [${i18n_case_yes}]* )
	    _answer=$i18n_s_yes
	    _valid=true
	    ;;
    [${i18n_case_no}]* )
	    _answer=$i18n_s_no
	    _valid=true
	    ;;
  esac
done
a_SGDSecure="$_answer"

    OUT="plaintext" SGDCLIENT="tcpclient" SGDWEBSOCKETCLIENT="websocket-client"
    [ "${a_SGDSecure}" = "${i18n_s_yes}" ] && OUT="ssl" SGDCLIENT="sgd-ssl-client" SGDWEBSOCKETCLIENT="sgd-ssl-client"
}

config_create() {
    BINDADDR="" CLIENTADDR="" CONFIGFILE="" REVERSEPROXYREDIRECTADDR=""
    REVERSEPROXYADDR="" SECURE_SGD="" CLIENT_CERTS_AUTH_MODE=""
    while [ -n "$1" ]; do
	case "$1" in
	--interface)
	    case "$2" in
	    "" | --*) printf "${i18n_invalidarg01_gw}" "$1"; usage_create
	    esac
	    BINDADDR="$2"
	    ;;
	--entry-point)
	    case "$2" in
	    "" | --*) printf "${i18n_invalidarg01_gw}" "$1"; usage_create
	    esac
	    CLIENTADDR="$2"
	    ;;
	--out)
	    case "$2" in
	    "" | --*) printf "${i18n_invalidarg01_gw}" "$1"; usage_create
	    esac
	    case "${2}" in
	       ssl|SSL)
	          SECURE_SGD="true"
	       ;;
	       plaintext|PLAINTEXT)
	          SECURE_SGD="false"
	       ;;
	       *)
	          printf "${i18n_invalidarg01_gw}" "$1"
	          usage_create
	       ;;
	    esac
	    ;;
	--file)
	    case "$2" in
	    "" | --*) printf "${i18n_invalidarg01_gw}" "$1"; usage_create
	    esac
	    CONFIGFILE="$2"
	    # deal with relative filename
	    case "${CONFIGFILE}" in /*) ;; *) CONFIGFILE="${ORIGDIR}/${CONFIGFILE}" ;; esac
	    [ ! -s "${CONFIGFILE}" ] && { printf "${i18n_invalidarg01_gw}" "$1"; usage_create; }
	    BINDADDR=`GetTag binding ${CONFIGFILE}`
	    CLIENTADDR=`GetTag clientaddr ${CONFIGFILE}`

	    SGDCLIENT=`GetTag sgdclient ${CONFIGFILE}`
        if [ "${SGDCLIENT}" == "tcpclient" ]
        then
            SECURE_SGD="false"
        else
            SECURE_SGD="true"
        fi

	    [ -z "${BINDADDR}" -o \
	      -z "${CLIENTADDR}" -o \
	      -z "${SECURE_SGD}" ] && { printf "${i18n_invalidarg01_gw}" "$1"; usage_create; }
	    ;;
	*)  usage_create "$1"
	esac
	shift; shift
    done

    # Get the config that cannot be changed from this command
    REVERSEPROXYREDIRECTADDR=`GetTag reverseproxyredirectaddr ${GWCONF}`
    REVERSEPROXYADDR=`GetTag reverseproxyaddr ${GWCONF}`
    CLIENT_CERTS_AUTH_MODE=`GetTag clientcerts ${GWCONF}`
    export REVERSEPROXYREDIRECTADDR
    export REVERSEPROXYADDR
    export CLIENT_CERTS_AUTH_MODE

    if [ -z "${BINDADDR}" -a -z "${CLIENTADDR}" -a -z "${SECURE_SGD}" ]
    then
        config_interactive
    fi

    # Attempt to populate variables from config if they haven't been provided.
    : ${BINDADDR:=`GetTag binding ${GWCONF}`}
    : ${CLIENTADDR:=`GetTag clientaddr ${GWCONF}`}
    : ${SGDCLIENT:=`GetTag sgdclient ${GWCONF}`}
    if [ "${SGDCLIENT}" == "tcpclient" ]
    then
        SECURE_SGD="false"
    else
        SECURE_SGD="true"
    fi

    if [ -z "${BINDADDR}" ]; then
        printf "${i18n_invalidarg01_gw}" "--interface"
        usage_create
    elif [ -z "${CLIENTADDR}" ]; then
        printf "${i18n_invalidarg01_gw}" "--entry-point"
        usage_create
    elif [ -z "${SECURE_SGD}" ]; then 
        printf "${i18n_invalidarg01_gw}" "--out"
        usage_create
    fi

    tag="binding"
    case "${BINDADDR}" in
    *:*) BINDPORT=`expr "${BINDADDR}" : '.*:\(.*\)'`
        probe="$INSTDIR/bin/bin/ttahostprobe `${INSTDIR}/bin/bin/ttahostname`:${BINDPORT}"
        [ "`${probe}`" = "y" ] && printf "${i18n_portinuse01_gw}" "${BINDPORT}"
        ;;
    *)  echo "${tag}: ${i18n_interfaceandport_gw}"; exit 1
    esac

    tag="clientaddr"
    case "${CLIENTADDR}" in
    *:*) CLIENTPORT=`expr "${CLIENTADDR}" : '.*:\(.*\)'`
        probe="$INSTDIR/bin/bin/ttahostprobe `${INSTDIR}/bin/bin/ttahostname`:${CLIENTPORT}"
        [ "`${probe}`" = "y" ] && printf "${i18n_portinuse01_gw}" "${CLIENTPORT}"
        ;;
    *)  echo "${tag}: ${i18n_interfaceandport_gw}"; exit 1
    esac

    export BINDADDR
    export CLIENTADDR
    export SECURE_SGD

    # Get the tuning data
    AIPMAXC=`sed '/^AIPMAXC=/!d;s/.*=//' ${TUNING_DATA} 2>/dev/null | tail -1 | tr -cd "0123456789"` 
    [ -n "${AIPMAXC}" ] && export AIPMAXC 

    WSMAXC=`sed '/^WSMAXC=/!d;s/.*=//' ${TUNING_DATA} 2>/dev/null | tail -1 | tr -cd "0123456789"`
    [ -n "${WSMAXC}" ] && export WSMAXC 
 
    HTTPC=`sed '/^HTTPC=/!d;s/.*=//' ${TUNING_DATA} 2>/dev/null | tail -1 | tr -cd "0123456789"` 
    [ -n "${HTTPC}" ] && export HTTPC

    # Set INSTALL_PATH to where the gateway is installed
    INSTALL_PATH="${INSTDIR}"
    export INSTALL_PATH

    # Generate new config files based on the newly created config
    ${INSTDIR}/bin/scripts/generate-gw-config-from-templates.sh
    ${INSTDIR}/bin/scripts/generate-gatewayconfig-xml.sh

    return 0
}

ALLTAGS="
binding:binding
routes-http-maxcon:http-maxcon
routes-aip-maxcon:aip-maxcon
routes-ws-maxcon:ws-maxcon
routes-reverseproxy-redirect:reverseproxy-redirect
services-reflection-binding:reflection-binding
services-reflection-auth-binding:reflection-auth-binding
services-clientcerts:clientcerts
"

gettag() {
    echo "${ALLTAGS}" | sed "/^$1:/!d;s/.*://"
}

config_list() {
    case "$1" in
    --help) usage_list
    esac
    tags=""
    while [ -n "$1" ]; do
	display=`expr "$1" : '..\(.*\)'`; tag=`gettag ${display}`
	if [ -n "${tag}" ]; then
	    tags="${tags} ${display}:${tag}"
	else
	    case "$1" in
	    --xml) cat ${GWCONF}; return 0;;
	    *)  printf "${i18n_badarg01_gw}" "$1"
	    esac
	fi
	shift
    done
    if [ -n "${tags}" ]; then
	for x in ${tags}; do
	    display=`expr ${x} : '\(.*\):.*'` tag=`expr ${x} : '.*:\(.*\)'`
	    sed "/<${tag}>/!d;s|.*<${tag}>||;s|</${tag}>||;s|^|${display}: |" ${GWCONF}
	done
    else
	for x in ${ALLTAGS}; do
	    display=`expr ${x} : '\(.*\):.*'` tag=`expr ${x} : '.*:\(.*\)'`
	    sed "/<${tag}>/!d;s|.*<${tag}>||;s|</${tag}>||;s|^|${display}: |" ${GWCONF}
	done
    fi
    return 0
}

config_edit() {
    case "$1" in
    --help) usage_edit
    esac
    howmany=0 recompute=""
    while [ -n "$1" ]; do
	display=`expr "$1" : '..\(.*\)'`; tag=`gettag ${display}`
	case "$2" in '' | --*) printf "${i18n_badarg01_gw}" "$1"; return 1;; esac
	if [ -n "${tag}" ]; then
	    howmany=`expr ${howmany} + 1`
	else
	    printf "${i18n_badarg01_gw}" "$1"
	fi
	[ -n "${tag}" ] && {
            REVERSEPROXYREDIRECTADDR=`GetTag reverseproxyredirectaddr "${GWCONF}"`
            SetTag "${tag}" "$2"
	    case "${tag}" in
	    *binding)
		# check whether the specified port is in use; if so, output warning
		port="$2"
		case "${port}" in
		*:*) port=`expr "${port}" : '.*:\(.*\)'`
		esac
		case "${port}" in
		[0-9]*)
		    probe="$INSTDIR/bin/bin/ttahostprobe `${INSTDIR}/bin/bin/ttahostname`:${port}"
		    [ "`${probe}`" = "y" ] && { echo; printf "${i18n_portinuse01_gw}" "${port}"; }
		esac
		;;
	    *maxcon)
		recompute="t"	# recompute JVM tuning parameters
		;;
            reverseproxy-redirect)
                NEW_REVERSEPROXYREDIRECTADDR="$2"
                SetTag "reverseproxyredirectaddr" "${NEW_REVERSEPROXYREDIRECTADDR}"
                if [ "${REVERSEPROXYREDIRECTADDR}" != "${NEW_REVERSEPROXYREDIRECTADDR}" ]
                then
                    # Set the new reverseproxyredirectaddr in the httpd config
                    sed "s|${REVERSEPROXYREDIRECTADDR}|${NEW_REVERSEPROXYREDIRECTADDR}|g" "${INSTDIR}/httpd/httpd-${VERSION_APACHE}/conf/extra/gateway/httpd-gateway.conf" > "${INSTDIR}/httpd/httpd-${VERSION_APACHE}/conf/extra/gateway/httpd-gateway.conf.tmp"
                    printf "${i18n_configchangeavail01_gw}" "${INSTDIR}/httpd/httpd-${VERSION_APACHE}/conf/extra/gateway/httpd-gateway.conf.saved"
                    mv "${INSTDIR}/httpd/httpd-${VERSION_APACHE}/conf/extra/gateway/httpd-gateway.conf" "${INSTDIR}/httpd/httpd-${VERSION_APACHE}/conf/extra/gateway/httpd-gateway.conf.saved"
                    mv "${INSTDIR}/httpd/httpd-${VERSION_APACHE}/conf/extra/gateway/httpd-gateway.conf.tmp" "${INSTDIR}/httpd/httpd-${VERSION_APACHE}/conf/extra/gateway/httpd-gateway.conf"
                fi
                ;;
	    esac
	}
	shift; shift
    done
    if [ "${howmany}" -eq 0 ]; then
	usage_edit
    else
	[ -n "${recompute}" ] && {
	    # recompute JVM tuning parameters
	    AIPMAXC=`GetTag aip-maxcon ${GWCONF}`
	    HTTPC=`GetTag http-maxcon ${GWCONF}`
	    WSMAXC=`GetTag ws-maxcon ${GWCONF}`
	    HTTPM=`expr 300 \* ${HTTPC}`
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

	    echo
	    if [ -n "${heaphuge}" ]; then
		printf "${i18n_newheapwarn01_gw}" "${heaphuge}"
		echo "${i18n_heaphuge_gw}"
	    elif [ -n "${heapbig}" ]; then
		printf "${i18n_newheapwarn01_gw}" "${heapbig}"
		echo "${i18n_heapbig_gw}"
	    else
		printf "${i18n_newheap01_gw}" "${heap}"
	    fi
	    echo "${i18n_referdoc_gw}"
	}
	echo; echo "${i18n_needrestart10_gw}"
    fi
    return 0
}

config_enable() {
    case "$1" in
    --help) usage_enable
    esac
    howmany=0
    while [ -n "$1" ]; do
	case "$1" in
	--services-reflection)
	    howmany=`expr ${howmany} + 1`
	    cp -p "${TEMPLATES_PATH}/etc/reflection.xml.template" \
              "${INSTDIR}/etc/reflection.xml"
	    ;;
	--services-reflection-auth)
	    howmany=`expr ${howmany} + 1`
	    ssl_xml_file="etc/reflection-ssl.xml"
	    sed "s|%INSTDIR%|${INSTDIR}|g
		     s|%CONFIGDIR%|${INSTDIR}/proxy/etc|g" \
            "${TEMPLATES_PATH}/${ssl_xml_file}.template" \
            > "${INSTDIR}/${ssl_xml_file}"
        cp -p "${TEMPLATES_PATH}/etc/reflection-auth.xml.template" \
              "${INSTDIR}/etc/reflection-auth.xml"
	    ;;
	--routes-http-redirect)
	    howmany=`expr ${howmany} + 1`
	    cp -p "${TEMPLATES_PATH}/etc/http-redirect.xml.template" \
              "${INSTDIR}/etc/http-redirect.xml"
	    ;;
    --ipv6)
        howmany=`expr ${howmany} + 1`
        echo "-Djava.net.preferIPv4Stack=false" > "$IPV6_PARAMETERS"
        chown ${privusr}:${privgrp} "$IPV6_PARAMETERS"
        chmod ${mode} "$IPV6_PARAMETERS"
        ;;
	*)  printf "${i18n_badarg01_gw}" "$1"
	esac
	shift
    done
    if [ "${howmany}" -eq 0 ]; then
	usage_enable
    else
	echo; echo "${i18n_needrestart10_gw}"
    fi
    return 0
}

config_disable() {
    case "$1" in
    --help) usage_disable
    esac
    howmany=0
    while [ -n "$1" ]; do
	case "$1" in
	--services-reflection)
	    howmany=`expr ${howmany} + 1`
	    echo "<empty />" > ${INSTDIR}/etc/reflection.xml; chmod ${mode} ${INSTDIR}/etc/reflection.xml; chown ${privusr}:${privgrp} ${INSTDIR}/etc/reflection.xml
	    ;;
	--services-reflection-auth)
	    howmany=`expr ${howmany} + 1`
	    for f in ${INSTDIR}/etc/reflection-ssl.xml ${INSTDIR}/etc/reflection-auth.xml; do
		echo "<empty />" >$f; chmod ${mode} $f; chown ${privusr}:${privgrp} $f
	    done
	    ;;
	--routes-http-redirect)
	    howmany=`expr ${howmany} + 1`
	    echo "<empty />" > ${INSTDIR}/etc/http-redirect.xml; chmod ${mode} ${INSTDIR}/etc/http-redirect.xml; chown ${privusr}:${privgrp} ${INSTDIR}/etc/http-redirect.xml
	    ;;
    --ipv6)
        howmany=`expr ${howmany} + 1`
        echo "-Djava.net.preferIPv4Stack=true" > "$IPV6_PARAMETERS"
        chown ${privusr}:${privgrp} "$IPV6_PARAMETERS"
        chmod ${mode} "$IPV6_PARAMETERS"
        ;;
	*)  printf "${i18n_badarg01_gw}" "$1"
	esac
	shift
    done
    if [ "${howmany}" -eq 0 ]; then
	usage_disable
    else
	echo; echo "${i18n_needrestart10_gw}"
    fi
    return 0
}

case "$1" in
create)
    shift
    config_create "$@"
    ;;
list)
    shift
    config_list "$@"
    ;;
edit)
    shift
    config_edit "$@"
    ;;
enable)
    shift
    config_enable "$@"
    ;;
disable)
    shift
    config_disable "$@"
    ;;
*)  usage
esac

exit 0
