#  $Id: gateway_patch_update.sh 145455 2017-06-15 14:40:42Z mike.mcewen@oracle.com $
#  Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
#  This software code contains proprietary information 
#  and should be treated as confidential

# Need to be root in order to update patch commands
u="`LANG=C LC_ALL=C id | sed 's/.*uid=\([0-9][0-9]*\).*/\1/'`"
if [ "$u" = "0" ]
then
  : # all is okay
else
  echo "You must be root to run this program"
  exit 15
fi


TTAINSTDIR=${INSTDIR}
HELP_DIR=${INSTDIR}/bin/scripts

msgfile="${INSTDIR}/bin/scripts/en-us_patch"
[ -s "${msgfile}" ] && . ${msgfile}

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`


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

privusr="sgdgsys"
privgrp="sgdgserv"


[ -s "${INSTDIR}/etc/version" ] && . ${INSTDIR}/etc/version
SGD_VERSION=${VERSION_SUNWsgdg}
VERSION_AS_NUMBER=`echo "${SGD_VERSION}" | tr -d .`
if [ "${VERSION_AS_NUMBER}" -lt 520000 ]; then
  privusr=daemon
  privgrp=daemon
fi

# If there are arguments missing show the usage for the patch commands
if [ "$#" -lt 6 ]; then
  ${TTAINSTDIR}/bin/gateway patch --help 
  exit 1
fi

TMPDIR=$1
FILELIST=$2
LOG_MESSAGE=$3
PATCH_LOG=$4
PATCH_NAME=$5
PATCH_CFG=$6
PATCH_ADD_CALLBACK=$7

# Move to the directory where the tar file was unpacked
cd ${TMPDIR}

ARCH=`machinearch -c`

# Copy across new versions of all the files listed
echo ${FILELIST} | tr ' ' '\012' |
while read data; do
  case "${data}" in
    en-us_patch)
      # Update help file
      mv ${data} ${HELP_DIR}
      chown ${privusr}:${privgrp} ${HELP_DIR}/en-us_patch
      chmod 440 ${HELP_DIR}/en-us_patch
      ;;
    *)
      # For an OS other than linux reset the permission to make the
      # file writable
      case "${ARCH}" in
        i3li)
          \cp ${data} "${TTAINSTDIR}/bin/scripts"
          ;;
        *)
          chmod 750 "${TTAINSTDIR}/bin/scripts/${data}"
          \cp ${data} "${TTAINSTDIR}/bin/scripts"
          chmod 550 "${TTAINSTDIR}/bin/scripts/${data}"
          ;;
      esac
      chown ${privusr}:${privgrp} "${TTAINSTDIR}/bin/scripts/${data}"
      ;;
  esac

  #chown ${privusr}:${privgrp} "${TTAINSTDIR}/bin/scripts/${data}"
  #UpdateRef ${data} ${PATCH_NAME} ${PATCH_CFG}
done
# Update version in patch config
UpdateRef "patch_mechanism_version" ${PATCH_NAME} ${PATCH_CFG}
chown ${privusr}:${privgrp} ${PATCH_CFG} 2>/dev/null

# Tidy up the tmp directory
cd ${TTAINSTDIR}/bin
rm -rf ${TMPDIR} 2> /dev/null

# Log the update of the commands
echo "${LOG_MESSAGE}" >> ${PATCH_LOG}

# Do we need to recall patch_add with the updated command? 
if [ "${PATCH_ADD_CALLBACK}" = "true" ]
then
    exec "${TTAINSTDIR}/bin/gateway" patch add --cont
fi
