#!/bin/sh
#
# Copyright 2006 Sun Microsystems, Inc. All rights reserved.
# Use is subject to license terms.
#
# pragma ident "@(#)postcommon	1.17 06/04/25 Sun Microsystems"
#
# This file contains shell routines common to both the postinstall and
# preremove scripts for the core j2se package (rt).  The postinstall and
# preremove scripts are built by concatenating the the specific portion
# to this common portion.
#
# The following commands are defined as shell variables so that they can
# be redefined (as below) to place this script in a mode such that it
# will tell you what it would do, without actually modifying the system.
# Only commands which modify the system should be so aliased.
#
# Be particularly careful with sed.  Its only on this list because at
# one point its output creates a file as part of the delivery.  $SED
# is applied there, but not at most uses of sed.
#
INSTALLF="installf"
RM="rm"
LN="ln"
CP="cp"
MKDIR="mkdir"
CHMOD="chmod"
CHOWN="chown"
CHGRP="chgrp"
TOUCH="touch"
SED="sed"

#
# The following are Gnome commands required to update the desktop databases.
# They are currently (04/06) not as stable as we would like, but we have
# little choice but to use them.  Usage should allow for graceful and
# mostly successful continuation of the installation should the commands
# fail (or not be present).
#
# Since these are both tested for existance and to be executed, separate
# names are provided so that only some uses may be "echoed" for testing.
#
GNOME_UTILS_DIRS="/usr/bin /usr/gnome/bin"
UPDATE_MIME_DATABASE="/usr/bin/update-mime-database"
UPDATE_DESKTOP_DATABASE="/usr/bin/update-desktop-database"
GTK_UPDATE_ICON_CACHE="/usr/bin/gtk-update-icon-cache"
UPDATE_MIME_DATABASE_EXEC="${UPDATE_MIME_DATABASE}"
UPDATE_DESKTOP_DATABASE_EXEC="${UPDATE_DESKTOP_DATABASE}"
GTK_UPDATE_ICON_CACHE_EXEC="${GTK_UPDATE_ICON_CACHE}"

#
# For development purposes, one might consider uncommenting the following
# lines.  The result is a script which will tell you what it would do
# without actually doing anything.
#
# INSTALLF="echo installf"
# RM="echo rm"
# LN="echo ln"
# CP="echo cp"
# MKDIR="echo mkdir"
# CHMOD="echo chmod"
# CHOWN="echo chown"
# CHGRP="echo chgrp"
# TOUCH="echo touch"
# SED="echo sed"
# UPDATE_MIME_DATABASE_EXEC="echo ${UPDATE_MIME_DATABASE}"
# UPDATE_DESKTOP_DATABASE_EXEC="echo ${UPDATE_DESKTOP_DATABASE}"
# GTK_UPDATE_ICON_CACHE_EXEC="echo ${GTK_UPDATE_ICON_CACHE}"
#

if [ "$PKG_INSTALL_ROOT" != "" ]; then
    INSTALLF="$INSTALLF -R ${PKG_INSTALL_ROOT}"
fi

PRODVERS=`echo ${SUNW_PRODVERS} | sed -e "s/\/.*//"`
PRODVERS_NP=`echo ${PRODVERS} | sed -e "s/_.*//"`
PREFIX="jdk"

REGISTRY_DIR="jdk"
REGISTRY_PATH="${BASEDIR}/${REGISTRY_DIR}"
REGISTRY_ENTRY="${PREFIX}${PRODVERS}"
REGISTRY_NAME="${REGISTRY_PATH}/${REGISTRY_ENTRY}"

INSTALL_DIR="instances"
INSTALL_PATH="${REGISTRY_PATH}/${INSTALL_DIR}"
INSTALL_ENTRY="${PREFIX}${PRODVERS_NP}"
INSTALL_NAME="${INSTALL_PATH}/${INSTALL_ENTRY}"

J2SE_PATH="${BASEDIR}/j2se"
JAVA_PATH="${BASEDIR}/java"
LATEST_PATH="${REGISTRY_PATH}/latest"
BIN_PATH="${BASEDIR}/bin"
BIN_JAVA="${BIN_PATH}/java"
BIN_JAVAWS="${BIN_PATH}/javaws"

JAVA_LINK_VALUE="${REGISTRY_DIR}/${REGISTRY_ENTRY}"
LATEST_LINK_VALUE="${REGISTRY_ENTRY}"

#
# Desktop integration source locations below.
#
JDK_DESKTOP="${INSTALL_NAME}/jre/lib/desktop"
JDK_ICONS="${JDK_DESKTOP}/icons"
JDK_APPS="${JDK_DESKTOP}/applications"
JDK_MIME="${JDK_DESKTOP}/mime"

#
# Desktop registration locations below.
# freedesktop.org conventions.
#
SHARE_PATH="${BASEDIR}/share"
SHARE_ICONS="${SHARE_PATH}/icons"
SHARE_MIME="${SHARE_PATH}/mime"
SHARE_APPS="${SHARE_PATH}/applications"

#
# Themes.
#
HICOLOR="hicolor"
HIGHCONTRAST="HighContrast"
HIGHCONTRASTINVERSE="HighContrastInverse"
LOWCONTRAST="LowContrast"
THEMES="${HICOLOR} ${HIGHCONTRAST} ${HIGHCONTRASTINVERSE} ${LOWCONTRAST}"

#
# Icons.
#
RESOLUTIONS="16x16 48x48"
TEXT_ICON="gnome-mime-text-x-java.png"
JAR_ICON="gnome-mime-application-x-java-archive.png"
JNLP_ICON="gnome-mime-application-x-java-jnlp-file.png"
JAVA_ICON="sun-java.png"
JAVAWS_ICON="sun-javaws.png"
JCONTROL_ICON="sun-jcontrol.png"
APPS_ICONS="${JAVA_ICON} ${JAVAWS_ICON} ${JCONTROL_ICON}"
MIME_ICONS="${TEXT_ICON} ${JAR_ICON} ${JNLP_ICON}"
ICONS="${APPS_ICONS} ${MIME_ICONS}"

#
# Support for both Gnome 2.0, JDS 3 (Gnome 2.6) and JDS 4 (Gnome 2.14 or
# later) is provided (and hopefully later versions).  Gnome 2.6 and earlier,
# do not not support the freedesktop conventions.
# Legacy locations follow.
#
SHARE_CONTROL_CENTER="${SHARE_PATH}/control-center-2.0"
SHARE_CAPPLETS="${SHARE_CONTROL_CENTER}/capplets"
SHARE_MIME_INFO="${SHARE_PATH}/mime-info"
SHARE_APP_REGISTRY="${SHARE_PATH}/application-registry"
SHARE_PIXMAPS="${SHARE_PATH}/pixmaps"

#
# Other legacy versions of Gnome on Solaris relocate some of the directories
# that Gnome expects to find in /usr/share to /usr/share/gnome.
#
SHARE_GNOME="${SHARE_PATH}/gnome"
GNOME_CONTROL_CENTER="${SHARE_GNOME}/control-center-2.0"
GNOME_CAPPLETS="${GNOME_CONTROL_CENTER}/capplets"
GNOME_MIME_INFO="${SHARE_GNOME}/mime-info"
GNOME_APP_REGISTRY="${SHARE_GNOME}/application-registry"
GNOME_PIXMAPS="${SHARE_GNOME}/pixmaps"

#
# This is as it should be:
#
REL_JAVAWS="bin/javaws"

#
# As a transition, we also have this, which can completely go away when
# 4954937 is fixed and fully disappears (only in internal 1.5 builds):
#
REL_JAVAWS_GOOFY="jre/bin/javaws"

#
# See PSARC/2003/091: 1.4.2 shipped with this "official" location for
# javaws.  Until 1.4.2 is deader than a doornail, we need this extra
# location.
#
REL_JAVAWS_OLD="jre/javaws/javaws"

#
# "Global variables" which (if set) reflect the minimum and maximum j2se
# releases expected to be the default on the underlying host release of
# Solaris.  These are fully expanded tuples.
DEFAULT_MIN=
DEFAULT_MAX=

#
# FollowLink ( link )
#
# Given a symbolic link, follow that link until it doesn't point a symbolic
# link.  Sequences such as "/foo/../" and "/./" are simplified.
#
# Parameters:
#  $1	link		Link name
#
FollowLink() {
    link=$1
    while [ -h $link ]; do
        ls=`ls -l $link`
        link=`dirname $link`/`echo $ls | cut -f 11 -d " "`
        echo $link | grep "\/\.\/" 2>/dev/null >/dev/null
        while [ $? = 0 ]; do
            link=`echo $link | sed -e s"/\/\.\//\//g"`
            echo $link | grep "\/\.\/" 2>/dev/null >/dev/null
        done
        echo $link | grep "[^\/]*\/\.\.\/" 2>/dev/null >/dev/null
        while [ $? = 0 ]; do
            link=`echo $link | sed -e s"/[^\/]*\/\.\.\///g"`
            echo $link | grep "[^\/]*\/\.\." 2>/dev/null >/dev/null
        done
        link=`echo $link | sed -e "s/^\.\///g"`
    done
    echo "$link"
    return 0
}

#
# GetHostRelease ()
#
# The use of /var/sadm/system/admin/INST_RELEASE is allowed by PSARC/2001/472.
# We fallback to the use of uname should this file not exist, but that may
# give the wrong answer for diskless server installations.  Fortunately, the
# absence of the INST_RELEASE file is a "should never happen" situation,
# except for internal development where it happens all the time, but then
# uname does yield the right answer.
#
# Unfortunately, the format of the VERSION identifier has changed over time
# as "Solaris 2.X" became marketed as simply "Solaris X".  Hence we need
# to allow for both the "2.X" and simply "X" forms. uname is consistent in
# providing a "Major.Minor[.Micro]" format.
#
# This returns the simple "X" that is the Minor release by the taxonomy.
#
GetHostRelease() {
    if [ -f $PKG_INSTALL_ROOT/var/sadm/system/admin/INST_RELEASE ]; then
	ver=`grep '^VERSION=' \
	  $PKG_INSTALL_ROOT/var/sadm/system/admin/INST_RELEASE`
	ver=`echo $ver | sed -e "s/[^0-9]*//" -e "s/^2\.//" -e "s/\..*//"`
    else
	ver=`uname -r | sed -e "s/[0-9]*\.//" -e "s/\..*//"`
    fi
    echo $ver
}

#
# ExpandPrefix ( release )
# ExpandPrefixInfinity ( release )
#
# These two shell routines expand JVM release identifier prefixes to the
# full, four element tuple.  ExpandPrefix zero extends as per JSR 56.
# ExpandPrefixInfinity extends with essentially infinite values.
#
# Parameters:
#   $1	release		Partial or complete release name tuple.
#
ExpandPrefix() {
    echo $1 | sed -e "s/_/\./g" | \
      awk '{FS="."; printf "%d.%d.%d_%.2d\n", $1, $2, $3, $4}'
}

ExpandPrefixInfinity() {
    echo $1 | sed -e "s/_/\./g" | \
      awk '{FS="."; \
	if ($1 == "") major=9999; else major=$1; \
	if ($2 == "") minor=9999; else minor=$2; \
	if ($3 == "") micro=9999; else micro=$3; \
	if ($4 == "") patch=9999; else patch=$4; \
	printf "%d.%d.%d_%.2d\n", major, minor, micro, patch}'
}

#
# GetDefaultRange ()
#
# Determines the range of J2se releases acceptable as the default on the
# host version of Solaris.
#
GetDefaultRange() {
    if [ -f $PKG_INSTALL_ROOT/etc/default/default_java ]; then
	. $PKG_INSTALL_ROOT/etc/default/default_java
    elif [ -f $PKG_INSTALL_ROOT/var/sadm/system/admin/default_java ]; then
    	. $PKG_INSTALL_ROOT/var/sadm/system/admin/default_java
    fi
    if [ "$DEFAULT_MIN" = "" ]; then
	release=`GetHostRelease`
	case $release in
	    5 | 6 | 7 )
		DEFAULT_MIN=1.1
		;;
	    8 )
		DEFAULT_MIN=1.2
		;;
	    9 )
		DEFAULT_MIN=1.4
		;;
	    10 )
		DEFAULT_MIN=1.5
		;;
	    * )
		;;
	esac
    fi
    if [ "$DEFAULT_MAX" = "" ]; then
	DEFAULT_MAX=$DEFAULT_MIN
    fi
    DEFAULT_MIN=`ExpandPrefix $DEFAULT_MIN`
    DEFAULT_MAX=`ExpandPrefixInfinity $DEFAULT_MAX`
    return 0
}

#
# GetRel ( filename )
#
# A little utility routine to strip viable prefixes from release names.
# Note that this only works for release names by Sun convention, not the
# whole, generalized JSR 56 name set.
#
# The current and legacy prefixes are:
#	jdk (default for these packages)
#	jre
#	j2re
#	j2sdk
#
# Parameters:
#   $1	filename	Filesystem filename
#
# Returns:
#	Version portion of the file name.
#
GetRel() {
    if [ "`echo $1 | cut -c 1-3`" = "jdk" ]; then
	echo $1 | cut -c 4-
    elif [ "`echo $1 | cut -c 1-3`" = "jre" ]; then
	echo $1 | cut -c 4-
    elif [ "`echo $1 | cut -c 1-4`" = "j2re" ]; then
	echo $1 | cut -c 5-
    elif [ "`echo $1 | cut -c 1-5`" = "j2sdk" ]; then
	echo $1 | cut -c 6-
    else
	echo $1
    fi
}

#
# GetMicro ( release )
#
# Extracts the Micro (dot-dot) version identifier from a Solaris JRE
# release identifier.  This is the entire release identifier ('X.Y.Z',
# not just 'Z'). Prefix specifications are zero extended.
#
# Parameters:
#   $1	release		release identifier
#
# Returns:
#	The Micro release portion of the release identifier.
#
GetMicro() {
    echo `echo $1 | sed -e "s/[-_].*//" | \
      awk '{FS="."; printf "%s.%s.%s", $1, $2, $3}'`
}

#
# RelCmp ( rel1 rel2 )
#
# Styled as much as possible after strcmp, this routine returns one of the
# strings "lt", "eq", or "gt" based on the relationship of the two release
# version identifier strings passed as parameters. The sort is done only
# on the first four fields (Major, Minor, Micro, Patch).  Internal identifiers
# beyond that are ignored and releases differing only in the internal
# identifier will compare as equal.
#
# Parameters:
#   $1	rel1		Release identifier
#   $2	rel2		Release identifier
#
# Returns:
#	"lt", "eq", or "gt" based on the relationship of the two releases
#
RelCmp() {
    r1=`echo $1 | sed -e "s/-.*//" -e "s/_/\./g"`
    r2=`echo $2 | sed -e "s/-.*//" -e "s/_/\./g"`
    if [ "$r1" = "$r2" ]; then
	echo "eq"
    else
	lrel=`printf "%s\n%s\n" ${r1} ${r2} | \
	      sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n | \
	      head -1`

	if [ "$r1" = "$lrel" ]; then
	    echo "lt"
	else
	    echo "gt"
	fi
    fi
}

#
# Select ( "least"|"greatest" list )
#
# From the list of file system objects passed in, return the "greatest"
# or "least" depending upon the text flag passed in $1.  The ordering
# is determined by the rules documented in JSR 56 (Appendix A).
# However, this implementation is limited to identifiers which follow the
# Sun conventions for release and directory naming.
#
# Parameters:
#   $1	flag		"least"|"greatest" to control the selection.
#   $2	list		List of potential file system identifiers.
#
# Returns:
#	The selected file system identifier.
#
Select() {
    if [ "$2" = "" ]; then
	return
    fi

    tlist=
    for dir in $2; do
	rel=`GetRel $dir`
	rel=`ExpandPrefix $rel | sed -e "s/[\._-]/ /g"`
	tlist=`printf "%s %s\n%s" "${rel}" "${dir}" "${tlist}"`
    done
    if [ "$1" = "least" ]; then
	printf "%s\n" "${tlist}" | \
	    sort -k 1,1n -k 2,2n -k 3,3n -k 4,4n | \
	    head -1 | \
	    cut -d " " -f 5
    else
	printf "%s\n" "${tlist}" | \
	    sort -k 1,1n -k 2,2n -k 3,3n -k 4,4n | \
	    tail -1 | \
	    cut -d " " -f 5
    fi
}

#
# InRange ( low_bound release high_bound )
#
# Determines if the release identifier ($2) lies between the low bound ($1)
# and the high bound ($3) inclusive.  The release identifiers must be full
# expanded tuples.
#
# Parameters:
#   $1	low_bound	Low bound of the release range (inclusive).
#   $2	release		Release to be checked.
#   $3	high_bound	High bound of the release range (inclusive).
#
# Returns:
#   0	(success) is the release identifier is in range.
#   1	(failure) is the release identifier is out of range.
#
InRange() {
    if [ "$2" = "" ]; then
	return 1
    fi

    low=`echo "$1" | sed -e "s/[\._-]/ /g"`
    rel=`echo "$2" | sed -e "s/[\._-]/ /g"`
    hi=`echo "$3" | sed -e "s/[\._-]/ /g"`
    mid=`echo "${low}\n${rel}\n${hi}" | \
        sort -k 1,1n -k 2,2n -k 3,3n -k 4,4n | \
        head -2 | \
        tail -1`
    mid=`echo $mid | awk '{FS=" "; printf "%d.%d.%d_%.2d\n", $1, $2, $3, $4}'`
    if [ "$2" = "$mid" ]; then
	return 0
    else
	return 1
    fi
}

#
# UpdateIconCache(icon_theme_root)
#
# Update the icon cache for the theme located at icon_root_theme.  The
# icon cache is optional but if it is present it needs to be updated
# for the new icons to be found.
#
# On older systems, the cache update utility may not exist.
#
# In addition, the following little tidbit is found in the "Implementation
# Notes" section of the "Icon Theme Specification (0.11)":
#
#       (http://freedesktop.org/wiki/Standards_2ficon_2dtheme_2dspec)
#
#       This caching can make it impossible for users to add icons without
#       having to restart applications. In order to handle this, any
#       implementation that does caching is required to look at the mtime
#       of the toplevel icon directories when doing a cache lookup, unless
#       it already did so less than 5 seconds ago. This means that any icon
#       editor or theme installation program need only to change the mtime
#       of the the toplevel directory where it changed the theme to make sure
#       that the new icons will eventually get used.
#
# Its not clear to me if "toplevel directory" means the "theme" directory or
# an immediate child.  To be sure, touch both.
#
UpdateIconCache() {
    _icon_theme_root=$1

    if [ -f ${_icon_theme_root}/icon-theme.cache ]; then
	for _dir in ${GNOME_UTILS_DIRS}; do
	    if [ -x ${_dir}/${GTK_UPDATE_ICON_CACHE} ]; then
		( ${_dir}/${GTK_UPDATE_ICON_CACHE_EXEC} ${_icon_theme_root} ) \
		    > /dev/null 2>&1
		break
	    fi
	done
	${TOUCH} ${_icon_theme_root}
	for _dir in ${RESOLUTIONS}; do
	    if [ -d ${_icon_theme_root}/${_dir} ]; then
		${TOUCH} ${_icon_theme_root}/${_dir}
	    fi
	done
    fi

}

#
# UpdateDesktopDatabase(desktop_root)
#
# Update the desktop file database for the directory desktop_root.  The
# desktop database (cache) is optional but if it is present it needs to
# be updated for the new desktop files to be found.  (Interesting name for
# the database/cache file, no?)
#
# On older systems, the update utility may not exist.
#
# In order for the new .desktop files to be recognized, host based update
# utilities need to be run.  As we all know, this isn't always possible,
# so be careful to run them only when appropriate and be gracious about
# accepting failures.
#
UpdateDesktopDatabase() {
    _desktop_root=$1

    if [ -f ${_desktop_root}/mimeinfo.cache ]; then
	for _dir in ${GNOME_UTILS_DIRS}; do
	    if [ -x ${_dir}/${UPDATE_DESKTOP_DATABASE} ]; then
		( ${_dir}/${UPDATE_DESKTOP_DATABASE_EXEC} ${_desktop_root} ) \
		   > /dev/null 2>&1
		break
	    fi
	done
    fi

}

#
# UpdateMimeDatabase(mime_root)
#
# Update the mime definitions database located at mime_root.  This is not
# optional.
#
# On older systems, the update utility may not exist (but in that case,
# this mime database isn't being used).
#
UpdateMimeDatabase() {
    _mime_root=$1

    if [ -d ${mime_root}/packages ]; then
	for _dir in ${GNOME_UTILS_DIRS}; do
            if [ -x ${_dir}/${UPDATE_MIME_DATABASE} ]; then
		( ${_dir}/${UPDATE_MIME_DATABASE_EXEC} ${_mime_root} ) \
		    > /dev/null 2>&1
		break
	    fi
	done
    fi

}

#
# Copyright 2006 Sun Microsystems, Inc. All rights reserved.
# Use is subject to license terms.
#
# pragma ident "@(#)preremove	1.35 07/11/29 Sun Microsystems"
#
# The function of this script is to attempt to restore a system default
# jvm should is be that it is the former system default which is being
# removed. Also delete the service tag if created.
#
# See "NewDefault()" for the exact algorithm.
#

#
# CheckLegacy ( dir )
#
# Check the legacy directory (ie: j2se, java1.2, java1.1) as a valid answer
# for the default release based on the assumed contents of that directory.
# If valid, the /usr/java symbolic link is set to point there and "success"
# is returned; else return "failure".
#
# Parameters:
#   $1	dir		Directory (in /usr) assumed to contain a legacy release.
#
# Returns:
#   0	(success) is the release identifier is in range.
#   1	(failure) is the release identifier is out of range.
#
CheckLegacy() {
    if [ ! -h ${BASEDIR}/$1 -a \
	-d ${BASEDIR}/$1 -a \
	-x ${BASEDIR}/$1/bin/java ]; then
	case $1 in
	    "j2se" )
		rel=1.4
		;;
	    "java1.2" )
		rel=1.2
		;;
	    "java1.1" )
		rel=1.1
		;;
	    * )
		return 1
		;;
	esac
	min=`ExpandPrefix "$rel"`
	max=`ExpandPrefixInfinity "$rel"`
	if [ "`RelCmp $min $DEFAULT_MAX`" != "gt" -a \
	     "`RelCmp $max $DEFAULT_MIN`" != "lt" ]; then
	    ${RM} -f ${JAVA_PATH}
	    ${LN} -s $1 ${JAVA_PATH}
	    return 0
	fi
    fi
    return 1
}

#
# NewDefault ()
#
# Try to establish a new default. Note that only JREs installed in well
# known system locations are considered.
#
NewDefault() {

    #
    # Begin by generating the list of possible JREs from the system
    # repository (/usr/jdk).
    #
    list=""
    for path in `ls -d ${REGISTRY_PATH}/jdk* ${REGISTRY_PATH}/jre* \
      ${REGISTRY_PATH}/j2sdk* ${REGISTRY_PATH}/j2re*  2>/dev/null`; do
	if [ ! -d $path -a ! -h $path ]; then
	    continue
	fi
	if [ ! -x ${path}/bin/java ]; then
	    continue
	fi
	entry=`basename $path`
	if [ "$entry" = "${REGISTRY_ENTRY}" ]; then
	    continue
	fi
	list="$list $entry"
    done
  
    #
    # Step 1:	Try to make a different patch level of the same Micro release
    #		the default. If multiple candidates exist, choose the most
    #		advanced.
    #
    if [ "$list" != "" ]; then
	mymicro=`GetMicro ${REGISTRY_ENTRY}`
	minimum=`ExpandPrefix $mymicro`
	maximum=`ExpandPrefixInfinity $mymicro`
	short_list=""
	for jre in $list; do
	    jre_rel=`GetRel $jre`
	    jre_rel=`ExpandPrefix $jre_rel`
	    if `InRange $minimum $jre_rel $maximum`; then
		short_list="$short_list $jre"
	    fi
	done
	if [ "$short_list" != "" ]; then
	    entry=`Select "greatest" "$short_list"`
	    ${RM} -f ${JAVA_PATH}
	    ${LN} -s jdk/$entry ${JAVA_PATH}
	    return
	fi
    fi

    #
    # Step 2:	Try to find a JRE within the preferred default range
    #		for this host platform. If multiple candidates exist,
    #		choose the most	advanced.
    #
    GetDefaultRange
    if [ "$list" != "" ]; then
	short_list=""
	for jre in $list; do
	    jre_rel=`GetRel $jre`
	    jre_rel=`ExpandPrefix $jre_rel`
	    if `InRange $DEFAULT_MIN $jre_rel $DEFAULT_MAX`; then
		short_list="$short_list $jre"
	    fi
	done
	if [ "$short_list" != "" ]; then
	    entry=`Select "greatest" "$short_list"`
	    ${RM} -f ${JAVA_PATH}
	    ${LN} -s jdk/$entry ${JAVA_PATH}
	    return
	fi
    fi

    #
    # Step 2':	Special case for when the default range includes 1.4.
    #		We don't know exactly what release exists in /usr/j2se,
    #		but the odds are high enough that we should try to use
    #		it now. By this point we know that there are no other
    #		1.4 candidates, so anything that's in j2se is better
    #		than anything else we will find.
    #
    if CheckLegacy "j2se" ; then
	return
    fi

    #		Ditto for 1.2 and java1.2.
    if CheckLegacy "java1.2" ; then
	return
    fi

    #		Ditto for 1.1 and java1.1.
    if CheckLegacy "java1.1" ; then
	return
    fi

    #
    # Step 3:	(Desperation sets in) Look for any JRE.
    #
    if [ "$list" != "" ]; then
	entry=`Select "greatest" "$list"`
	${RM} -f ${JAVA_PATH}
	${LN} -s jdk/$entry ${JAVA_PATH}
	return
    fi
    for dir in j2se java1.2 java1.1 ; do
	if [ ! -h ${BASEDIR}/${dir} ] && [ -d ${BASEDIR}/${dir} ] && \
	   [ -x ${BASEDIR}/${dir}/bin/java ]; then
	    ${RM} -f ${JAVA_PATH}
	    ${LN} -s ${dir} ${JAVA_PATH}
	    return
	fi
    done

    #
    # Finally, if there is no default, there should be no link.
    #
    if [ -h ${JAVA_PATH} ]; then
        ${RM} -f ${JAVA_PATH}
    fi

}

#
# NewLatest
#
# Determining the correct algorithm to apply for setting the "latest"
# link isn't as obvious as it might seem. The complication is due to
# package removal.  If the "latest" is being removed, you want to set
# the "latest" link to something else.  The trouble is, if that something
# else wasn't put there via pkgadd (a tar ball for example) or simply
# predates the creation of this interface, absolutely nothing will
# happen on that removal and the link will be left dangling.
#
# There is no complete solution for this, but following algorithm
# limits the problem area to systems where some installs happened
# via packages and other installs by tar archives - in other words,
# an edge condition in a rare scenario.
#
# On installation:
#
#	if <"latest" doesn't exist, or points to something older> then
#		set latest to point at the instance being installed
#
# On removal:
#
#	scan the registry for the most recent of the remaining JVMs
#	if <the most recent remaining is >= 1.5.0_01> then
#		set the link to point to the most recent remaining
#	else
#		remove the link
#	fi
#
# 1.5.0_01 is significant, because that is the first jvm which will
# manipulate this link, and hence, won't leave it dangling should it
# be removed.  The algorithm could be modified to carry back as far
# as 1.4.2_05, with the only downside being the potential for dangling
# links.  Carrying it back beyond this would be a nightmare, because
# a not-so-obvious part of the semantic of "latest", is that it is
# Multiple JRE enabled.
#
NewLatest() {

    #
    # We know the old link will be removed.  Let's do that first.
    #
    ${RM} -f ${LATEST_PATH}

    #
    # Begin by generating the list of possible JREs from the system
    # repository (/usr/jdk).
    #
    list=""
    for path in `ls -d ${REGISTRY_PATH}/jdk* ${REGISTRY_PATH}/jre* \
      ${REGISTRY_PATH}/j2sdk* ${REGISTRY_PATH}/j2re*  2>/dev/null`; do
	if [ ! -d $path -a ! -h $path ]; then
	    continue
	fi
	if [ ! -x ${path}/bin/java ]; then
	    continue
	fi
	entry=`basename $path`
	if [ "$entry" = "${REGISTRY_ENTRY}" ]; then
	    continue
	fi
	list="$list $entry"
    done

    #
    # If there are alternatives, find the most advanced (dare I say
    # "latest"?) JVM from among the possibilities.  As per the algorithm
    # description above, set the "latest" link to point the the JVM
    # selected above, iff that JVM is 1.5.0_01 or later.
    #
    if [ "$list" != "" ]; then
	latest=`Select "greatest" "$list"`
	latest_tuple=`GetRel $latest`
	latest_tuple=`ExpandPrefix $latest_tuple`
	if [ "`RelCmp $latest_tuple 1.5.0_01`" != "lt" ]; then
	    ${LN} -s $latest ${LATEST_PATH}
        fi
    fi
    return 0
}

#
# FixDangle ( rel_path )
#
FixDangle() {
    list=""
    for path in `ls -d ${REGISTRY_PATH}/jdk* ${REGISTRY_PATH}/jre* \
      ${REGISTRY_PATH}/j2sdk* ${REGISTRY_PATH}/j2re*  2>/dev/null`; do
	    if [ ! -d $path -a ! -h $path ]; then
		continue
	    fi
	    if [ ! -x ${path}/$1 ]; then
		continue
	    fi
	    entry=`basename $path`
	    if [ "$entry" = "${REGISTRY_ENTRY}" ]; then
		continue
	    fi
	    list="$list $entry"
	done
	if [ "$list" != "" ]; then
	    entry=`Select "least" "$list"`
	    ${RM} -f ${BIN_JAVAWS}
	    ${LN} -s ../${REGISTRY_DIR}/${entry}/$1 ${BIN_JAVAWS}
	    return 0
	elif [ -x ${J2SE_PATH}/$1 ]; then
	    ${RM} -f ${BIN_JAVAWS}
	    ${LN} -s ../j2se/$1 ${BIN_JAVAWS}
	    return 0
	fi	
	return 1
}

#
# Main Processing
#

# Delete the service tag if created
#
# If a different package install root is specified via pkgadd -R option,
# the installer cannot delete a service tag since the service tag registry
# client (see /usr/bin/stclient) only supports local system use.
# A RFE# 6576434 is created for stclient to support the remote installation
# support.
#
if [ "${PKG_INSTALL_ROOT}" = "" ]; then
    ${INSTALL_NAME}/bin/java com.sun.servicetag.Installer -delete > /dev/null 2>&1 
fi

#
# Remove all links from the Registry directory which point to this instance
# being removed.
#
for path in `ls -d ${REGISTRY_PATH}/jdk* ${REGISTRY_PATH}/jre* \
  ${REGISTRY_PATH}/j2sdk* ${REGISTRY_PATH}/j2re* 2>/dev/null`; do
    if [ -h $path ]; then
	target=`FollowLink $path`
	if [ "$target" = "${INSTALL_NAME}" ]; then
	    ${RM} $path
	fi
    fi
done

#
# The only processing need is if this package is either the current default,
# the current "latest" or the target of the /usr/bin/javaws symbolic link
# (See PSARC/2003/091).
#
# Generate the paths to examine before starting to adjust these links.
#
if [ -h ${JAVA_PATH} ]; then
    path=`FollowLink ${JAVA_PATH}`
fi
if [ -h ${LATEST_PATH} ]; then
    latest_path=`FollowLink ${LATEST_PATH}`
fi
if [ -h ${BIN_JAVAWS} ]; then
    ls=`ls -l ${BIN_JAVAWS}`
    link=`echo $ls | cut -f 11 -d " "`
    javaws_path=`echo ${BIN_PATH}/$link | \
      sed -e "s:/${REL_JAVAWS_GOOFY}$::" \
	  -e "s:/${REL_JAVAWS}$::" \
	  -e "s:/${REL_JAVAWS_OLD}$::" \
	  -e "s:/\./:/:g" \
	  -e "s:[^/]*/\.\./::g"`
    javaws_path=`FollowLink $javaws_path`
fi

#
# Test to see if /usr/java is a symlink and points to the instance being
# removed.  If so, then search for a new default.
#
if [ -h ${JAVA_PATH} ]; then
    if [ "$path" = "${REGISTRY_NAME}" ] || \
       [ "$path" = "${INSTALL_NAME}" ]; then

	NewDefault

	#
	# Due to the name change of ControlPanel to jcontrol, make sure the
	# desktop file points to something that exists.
	#
	# The sed script is because early implementations edited the file on
	# installation (as thus) and we need to duplicate that action.
	# Building this type of knowledge of other versions into the package
	# scripts is generally a bad idea, but in this case the risk is quite
	# contained: We just need to make sure these two strings never reappear.
	# One might note that older versions also removed "X-Sun_Supported;" and
	# X-Red_Hat_Base;".  Since these could reappear, it is safer to leave
	# them harmlessly in place.
	#
	if [ -h ${JAVA_PATH} ] && \
	  [ -f ${SHARE_PATH}/control-center-2.0/capplets/sun_java.desktop ] && \
	  [ -f ${JAVA_PATH}/jre/plugin/desktop/sun_java.desktop ]; then
	    $SED -e "s!INSTALL_DIR!${CLIENT_JAVA_PATH}!g" \
	      -e "s!JRE_NAME_VERSION!jre!g" \
	      ${JAVA_PATH}/jre/plugin/desktop/sun_java.desktop \
	      > ${SHARE_PATH}/control-center-2.0/capplets/sun_java.desktop
	fi

    fi
fi

#
# Test to see if /usr/jdk/latest is a symlink and points to the instance
# being removed.  If so, then search for a new (older) latest version.
#
if [ -h ${LATEST_PATH} ]; then
    if [ "$latest_path" = "${REGISTRY_NAME}" ] || \
       [ "$latest_path" = "${INSTALL_NAME}" ]; then

	NewLatest

    fi
fi

#
# Due to PSARC/2003/091, it is possible that the /usr/bin/javaws now
# needs to be adjusted. Only perform these adjustments if they are
# the result of this package removal.
#
if [ -h ${BIN_JAVAWS} ]; then
    if [ "$javaws_path" = "${REGISTRY_NAME}" ] || \
       [ "$javaws_path" = "${INSTALL_NAME}" ]; then

	#
	# 1. If the default now contains a valid javaws, point the link back to
	#    the default (through /usr/java).
	#
	# Due to psarc/2003/091 and 4954923, there are multiple places to search
	# for javaws.
	#
	if [ -x ${JAVA_PATH}/${REL_JAVAWS} ]; then
	    ${RM} -f ${BIN_JAVAWS}
	    ${LN} -s ../java/${REL_JAVAWS} ${BIN_JAVAWS}
	elif [ -x ${JAVA_PATH}/${REL_JAVAWS_GOOFY} ]; then
	    ${RM} -f ${BIN_JAVAWS}
	    ${LN} -s ../java/${REL_JAVAWS_GOOFY} ${BIN_JAVAWS}
	elif [ -x ${JAVA_PATH}/${REL_JAVAWS_OLD} ]; then
	    ${RM} -f ${BIN_JAVAWS}
	    ${LN} -s ../java/${REL_JAVAWS_OLD} ${BIN_JAVAWS}

	#
	# 2. Failing the above, if the link is now dangling removal of this
	#    package, then scan all the available JREs for one with an
	#    appropriate javaws.  Try to choose the one with the most
	#    correct name, and from among those, try to choose the oldest.
	#    Note that the oldest must be newer than the default, so this
	#    is "closest approximation").
	#
	else
	    if FixDangle ${REL_JAVAWS}; then
		exit 0
	    fi
	    if FixDangle ${REL_JAVAWS_GOOFY}; then
		exit 0
	    fi
	    if FixDangle ${REL_JAVAWS_OLD}; then
		exit 0
	    fi

	    #
	    # Nothng to point at.  Nuke it!
	    #
	    ${RM} -f ${BIN_JAVAWS}
	fi
    fi
fi

exit 0
