#! /bin/sh
#
# ident	"@(#)setup.sh	1.94	05/03/03 SMI"
#
# Copyright (c) 2002-2003 by Sun Microsystems, Inc.
# All rights reserved.
#

# Script to install/uninstall unbundled Web Console.



##############################################################
#
# Usage function
#
##############################################################
#
Usage() {
    cat - << EOF

Usage $PROG [-h] | [-n] [-f] | [-u [-f]]

-h = print this usage statement

-n = do not start the server at the end of installation.
     By default, the server is automatically started.

-u = uninstall the packages.

-f = When used with the -u option, force the uninstall of Tomcat, JDK, and 
     JavaHelp but only if this setup script originally installed them.  By 
     default the user is prompted to confirm removal of each of these packages.

     When used without the -u option, do a silent install.  There will be no 
     prompt to confirm upgrade from an earlier version.  There will be no 
     prompt to confirm upgrade of the JDK if it does not satisfy the minimum 
     requirements.  By default, the user is prompted to confirm all package 
     upgrades.

EOF

    exit ${EXIT_USAGE}

} # Usage



############################################
#
# Global variables
#
############################################
#
TMPDIR=/tmp
TOMCAT_PKG=SUNWtcatu
BZIP_PKG=SUNWbzip
TOMCAT_INSTALLDIR=/opt/${TOMCAT_PKG}
ADMIN=${TMPDIR}/admin.$$
ADMIN_BZIP=${TMPDIR}/bzip-admin.$$
ADMIN_TOMCAT=${TMPDIR}/tomcat-admin.$$
ADMIN_J2SDK=${TMPDIR}/j2sdk-admin.$$
ADMIN_JHSDK=${TMPDIR}/javahelp-admin.$$
WEBCONSOLE=/usr/share/webconsole
UNINSTALLRC=.uninstallrc
PKGRC=.pkgrc
MIN_OS_SUPPORTED="5.8"
CONSOLE_SEARCH_TOKEN=webconsole/console/WEB-INF/app.xml
UNINSTALL_SCRIPTS=""

# Set this to empty to see list of objects installed by pkgadd
# as it installs them.
VERBOSE="-n"

# The minimum Java and JavaHelp versions we require.
# If changed here, also change it in smcwebserver!
MIN_JAVA_VERSION="1.4.2"
MIN_JAVAHELP_VERSION="2.0"

# Default locations for a java runtime.
DEFAULT_JAVA=""
if [ -d /usr/jdk ]; then
    DEFAULT_JAVA="/usr/jdk/`ls -A /usr/jdk | fgrep jdk1.5 | sort | tail -1`/bin/java"
fi
if [ -d /usr/j2se ]; then
    DEFAULT_JAVA="$DEFAULT_JAVA /usr/j2se/bin/java"
fi

# `which` is csh and can create problems under certain conditions
WHICH="/bin/ksh whence"

# Must have full path to media in light of intermittent cd's
SAVECWD=`pwd`
cd `dirname $0`
IMAGEDIR=`pwd`
PROG=${IMAGEDIR}/`basename $0`
cd ${SAVECWD}

EXIT_SUCCESS=0
EXIT_ACCESS_DENIED=1
EXIT_BAD_OS=2
EXIT_USAGE=3
EXIT_NO_UNINSTALL_LOG=4
EXIT_UPGRADE=6
EXIT_DOWNGRADE=7
EXIT_WRONG_PLATFORM=8

## Temporary placeholder for properties that are needed by this program,
## but which cannot be made available as an environment variable or
## as a configuration property in $CONSOLE_CONFIG_DIR/webconsole.
## This is ONLY used when ALL the following conditions are true:
##    - installation is being performed via unbundled setup only.
##    - use of environment variables is precluded.
##    - programs that need the properties are invoked from a pkg script
##    - $CONSOLE_CONFIG_DIR/webconsole does not exist
## 
## The reasons for these conditions are:
##    - $CONSOLE_CONFIG_DIR/webconsole might not exist because the smreg
##      script may not have been installed yet by the time the setup program
##      wants to set a property for smreg to use.  During OS install, 
##      smreg processing takes place during stage 2 of the 2-stage 
##      registration/deployment, at which time the proper runtime environment 
##      and properties file does exist.
##   -  During pkgadd on Solaris, we cannot simply export environment
##      variables to pkg scripts.  pkgadd completely sets the runtime 
##      environment for pkg scripts based on the pkginfo.
## If you change this file, you MUST also change it in the setup scripts
## for each platform, as well as smreg!
PREREG=/var/tmp/_prereg.properties

BAD_OS_VERSION=\
"Sorry, this software only runs on Solaris ${MIN_OS_SUPPORTED} or later"

PARTIAL_JAVA_MSG1=\
"In order to properly manage installation of Java, setup requires \
that Java packages be installed as a single unit.  However setup \
has detected that you have a partial installation because only \
these packages are installed: "

PARTIAL_JAVA_MSG2=\
"Setup would like to remove these packages and then install Java"

PARTIAL_JAVA_MSG3=\
"Answering no will cause setup to exit and no changes will be made to your \
system.\n\nCan setup remove these packages [n]?"

BAD_JAVA_MSG1=\
"Setup has detected a partial installation of Java.\n
The following files are missing:"

MISMATCHED_JAVA_MSG1=\
"Setup has detected a mismatched version installation of Java.\n"

# Determine if this script is running on a platform that can support it
OS=`uname -s`
if [ "$OS" != "SunOS" ]; then
    echo "This installer is intended to run only on Solaris."
    echo "Your system is running $OS."
    exit $EXIT_WRONG_PLATFORM
fi


############################################
#
# Parse options
#
############################################
fflag=0
uflag=0
nflag=0

# Because of the way we parse some of the args by mukking with
# the shell's IFS, we will need to rebuild the arguments during the parsing
# in case we need to recursively launch the script after authentication as root.
# Note that we can't just save $*, as this creates problems with quoting
# during the relaunch.

while getopts "hnuf" c
do
    savedArgs="${savedArgs} -$c"

    case $c in
	"h") Usage;;
	"n") nflag=1;;
	"f") fflag=1;;
	"u") uflag=1;;
	\?)  Usage;;
    esac
done

# -n and -u are mutually exclusive
if [ $nflag -eq 1 ] && [ $uflag -eq 1 ]; then
    Usage
fi



############################################
#
# Check running OS, exit if we can't run on it, or
# if we don't have the right bits to install on
# it.
#
############################################

# Determine if media bits were built for this platform.  We assume
# that the 1st successful match of any pkg's ARCH parameter to the
# platform's processor type is sufficient to continue.
# None of this applies during uninstall.
#
if [ $uflag -eq 0 ]; then
    archOnMedia=""
    if [ -f ${IMAGEDIR}/${PKGRC} ]; then
	. ${IMAGEDIR}/${PKGRC}
	PKGS="${PKGS} ${CORE_PKGS} ${OPTIONAL_PKGS}"
	for pkg in $PKGS
	do
	    if [ -f ${IMAGEDIR}/${pkg}.pkg ]; then
		tmpArch=`pkgparam -d ${IMAGEDIR}/${pkg}.pkg ${pkg} ARCH`
		if [ "${tmpArch}" != "all" ]; then
		    archOnMedia=${tmpArch}
		    break
		fi
	    fi
	done
    fi
    if [ `uname -p` != "$archOnMedia" ]; then
	echo "The software located on ${IMAGEDIR}"
	echo "is intended to be installed on $archOnMedia systems running"
	echo "Solaris.  Your system's processor type is `uname -p`."
	exit $EXIT_WRONG_PLATFORM
    fi
fi


# Determine if we run on the current OS.
major=`uname -r | awk -F. '{print $1}'`
minor=`uname -r | awk -F. '{print $2}'`
if [ $major -lt `echo ${MIN_OS_SUPPORTED} | awk -F. '{print $1}'` ]; then
    echo ${BAD_OS_VERSION}
    exit ${EXIT_BAD_OS}
fi
if [ $major -eq `echo ${MIN_OS_SUPPORTED} | awk -F. '{print $1}'` -a \
     $minor -lt `echo ${MIN_OS_SUPPORTED} | awk -F. '{print $2}'` ]; then
    echo ${BAD_OS_VERSION}
    exit ${EXIT_BAD_OS}
fi


# Make sure all appropriate patches are applied before installing.
if [ $uflag -eq 0 ]; then

    requiredPatches=""

    # PKG parameters can be > 9 characters on Solaris 8-update 5 or
    # later, or on Solaris 8 -> update 4 if the appropriate patch
    # is applied.
    if [ $minor -eq 8 ]; then

	# No API to determine specific release of Solaris 8, so
	# we try a pkginfo on any pkg name > 9 characters.  If it
	# fails then we can assume the machine needs to be patched.
	for pkg in $PKGS
	do
	    nameLength=`echo $pkg | awk '{print length($1)}'`
	    if [ $nameLength -le 9 ]; then
		continue
	    fi

	    # Ignore if pkg not on install media.  Should never happen.
	    if [ ! -f ${IMAGEDIR}/${pkg}.pkg ]; then
		continue
	    fi

	    # If we can safely run a pkginfo, machine is update 5
	    # or later, or the machine has been patched.
	    pkginfo ${IMAGEDIR}/${pkg}.pkg >/dev/null 2>&1
	    if [ $? -eq 0 ]; then
		break
	    fi

	    # We have pkgs > 9 characters, patch required.
	    if [ `uname -p` = "sparc" ]; then
		requiredPatches="$requiredPatches 110934"
	    fi
	    if [ `uname -p` = "i386" ]; then
		requiredPatches="$requiredPatches 110935"
	    fi
	    break

	done
    fi

    # If patches required, make sure they're installed.
    if [ -n "$requiredPatches" ]; then
	missingPatches=""
	for p in $requiredPatches; do
	    showrev -p | grep $p >/dev/null 2>&1
	    if [ $? -ne 0 ]; then
		missingPatches="$missingPatches $p"
	    fi
	done

	if [ -n "$missingPatches" ]; then
	    echo ""
	    echo "Before installing this software, you must install the"
	    echo "following patches, available http://sunsolve.sun.com:"
	    echo "    $missingPatches"
	    echo ""
	    exit ${EXIT_BAD_OS}
	fi
    fi
fi

# We can run on it.  Now check if we have any bits to install.
# Ideally we have exact bits for this machine.  If not, we
# try the bits for the previous OS release, and so on until
# we got one.  If we run out, clear PLATFORM but continue - in
# case we assume we have no platform dependent bits; this
# would typically be the case during development when only a 
# specific platform's bits are built and included in the
# (unmerged) tarball.
#
PLATFORM="`uname -s`-`uname -r`-`uname -p`"
osVersion=${major}.${minor}
while [ 1 ]; do
    if [ -d ${IMAGEDIR}/$PLATFORM ]; then
	break
    else
	major=`echo $osVersion | awk -F. '{print $1}'`
	minor=`echo $osVersion | awk -F. '{print $2}'`
	minor=`(expr $minor - 1)`
	osVersion=${major}.${minor}
	if [ $minor -lt 8 ]; then
	    PLATFORM=""
	    break
	fi
	PLATFORM="`uname -s`-${osVersion}-`uname -p`"
    fi
done


############################################
#
# Force user to authenticate as superuser.
#
############################################
id=`/bin/id | awk '{print $1}'`
if [ "${id}" != "uid=0(root)" ]; then

    echo ""
    echo "To use this installer you will need to be the system's root user. \n"
    echo ""

    # Login the user as a root user.  Use the "su" command to 
    # ask for password and recursively run the installer.
    # We allow a certain number of attempts before quitting.
    #
    s=${EXIT_ACCESS_DENIED};
    t=3;
    while [ $s != 0 -a ! $t = 0 -a $fflag = 0 ]; do 
	echo "Please enter this system's root user password.\n"
	su - root -c "sh `dirname $PROG`/`basename $0` $savedArgs"
	s=$?
	t=`(expr $t - 1)`
        echo " "
    done
    if [ $t = 0 ]; then
	echo "Access denied\n"
    fi
    exit $s
fi




########################################################
#
# Function to resolve a link to it's target.
#
########################################################
resolve_link() {

    prg=$1

    if [ -h "${prg}" ]; then

	# Must cd to where the symbolic link is located as a starting point
	# to follow the link.
	cd `dirname ${prg}`

	# Resolve link to conclusion
	while [ -h "${prg}" ]
	do
	    prg=`ls -al ${prg} | awk '{print $NF}'`
	    cd `dirname ${prg}`
	done

	# Resolve to full path, in case it's relative.
	prg=`pwd`/`basename ${prg}`
    fi

    echo $prg

} # resolve_link


########################################################
#
# Version to convert a version string in X.Y.Z-* or
# X.Y.X_NN format to XYZNN format so can be treated as a
# number.
#
# $1 = version string
# Returns numerical version
#
########################################################
versionString2Num () {

    # Minor and micro default to 0 if not specified.
    major=`echo $1 | awk -F. '{print $1}'`
    minor=`echo $1 | awk -F. '{print $2}'`
    if [ ! -n "$minor" ]; then
        minor="0"
    fi
    micro=`echo $1 | awk -F. '{print $3}'`
    if [ ! -n "$micro" ]; then
        micro="0"
    fi

    # The micro version may further be extended to include a patch number.
    # This is typically of the form <micro>_NN, where NN is the 2-digit
    # patch number.  However it can also be of the form <micro>-XX, where
    # XX is some arbitrary non-digit sequence (eg., "rc").  This latter
    # form is typically used for internal-only release candidates or
    # development builds.
    #
    # For these internal builds, we drop the -XX and assume a patch number 
    # of "00".  Otherwise, we extract that patch number.
    #
    patch="00"
    dash=`echo $micro | grep "-"`
    if [ $? -eq 0 ]; then
	# Must be internal build, so drop the trailing variant.
	micro=`echo $micro | awk -F- '{print $1}'`
    fi

    underscore=`echo $micro | grep "_"`
    if [ $? -eq 0 ]; then
	# Extract the seperate micro and patch numbers, ignoring anything
	# after the 2-digit patch.
	patch=`echo $micro | awk -F_ '{print substr($2, 1, 2)}'`
	micro=`echo $micro | awk -F_ '{print $1}'`
    fi

    echo "${major}${minor}${micro}${patch}"

} # versionString2Num



##############################################################
#
# Install SUNWbzip
#
##############################################################
#
InstallBzip() {

    UNINSTALL_BZIP_SH=${TMPDIR}/${UNINSTALLRC}-bzip.$$
    pkginfo ${BZIP_PKG} >/dev/null 2>&1

    if [ $? -ne 0 ]; then

        rm -f ${ADMIN_BZIP} >/dev/null 2>&1
	cat ${ADMIN} > ${ADMIN_BZIP}

        # Install the SUNWbzip pkg.
	if [ -f ${IMAGEDIR}/${PLATFORM}/${BZIP_PKG}.pkg ]; then
	    path2pkg=${IMAGEDIR}/${PLATFORM}/${BZIP_PKG}.pkg
	else
	    path2pkg=${IMAGEDIR}/${BZIP_PKG}.pkg
	fi
        pkgadd ${VERBOSE} -a ${ADMIN_BZIP} -d ${path2pkg} ${BZIP_PKG}

        # Output to uninstall script how this pkg should be uninstalled.
        #
        rm -f ${UNINSTALL_BZIP_SH}
        cat << \DOINSTALL_EOF3 | sed -e "s/BZIP_PKG/${BZIP_PKG}/" > ${UNINSTALL_BZIP_SH}
echo ""
echo "Removing BZIP_PKG ..."
pkgrm -n -a ${ADMIN} BZIP_PKG
DOINSTALL_EOF3

        UNINSTALL_SCRIPTS="${UNINSTALL_BZIP_SH} ${UNINSTALL_SCRIPTS}"
        rm -f ${ADMIN_BZIP}
    fi
}


########################################################
#
# Function to try to find a suitable Java2 runtime.
# Suitable means java and javac must be available for
# required JDK version.
#
########################################################
findJava() {

    # Map to a number we can do a numerical comparison on.
    weWant=`versionString2Num $MIN_JAVA_VERSION`

    # JAVA_HOME environment variable overrides everything
    JAVA_LOC="${JAVA_HOME:+${JAVA_HOME}/bin/java}"

    # java.home property is where we think it should be.
    javahome_prop=""
    if [ -f /usr/sbin/smreg ]; then
	javahome_prop=`/usr/sbin/smreg list -p | grep "java.home="`
	if [ $? -eq 0 ]; then
	    JAVA_LOC="$JAVA_LOC `echo $javahome_prop | cut -d"=" -f2`/bin/java"
	fi
    fi

    # Followed by along PATH and the standard location.
    javaOnPath=`${WHICH} java 2>&1`
    if [ $? -eq 0 ]; then
	JAVA_LOC="$JAVA_LOC ${javaOnPath} ${DEFAULT_JAVA}"
    else
	JAVA_LOC="$JAVA_LOC ${DEFAULT_JAVA}"
    fi

    JAVA_HOME=""
    for i in ${JAVA_LOC}
    do
	prog=`resolve_link ${i}`
	progC=`dirname $prog`/javac
	if [ -x ${prog} -a -x $progC ]; then
	    # Get version, and map to a number we can do a 
	    # numerical comparison on.
	    version=`${i} -version 2>&1 | head -1`
	    version=`echo $version | awk '{print $3}' | sed -e "s/\"//g"`
	    weHave=`versionString2Num $version`

	    if [ ${weHave} -ge ${weWant} ]; then
		JAVA_HOME=`dirname \`dirname ${prog}\``
		break
	    fi

	fi
    done

} # findJava


########################################################
#
# Function to try to find a suitable JavaHelp runtime
#
########################################################
findJavaHelp() {

    # JAVAHELP_HOME environment variable overrides everything
    # as long as it points to a valid JavaHelp install.
    if [ -n "$JAVAHELP_HOME" ]; then
	if [ -f "${JAVAHELP_HOME}/lib/jhall.jar" ]; then
	    return
	fi
	JAVAHELP_HOME=""
    fi

    # javahelp.home property is where we think it should be.
    # Again, as long as it points to a valid JavaHelp install.
    javahelphome_prop=""
    if [ -f /usr/sbin/smreg ]; then
	javahelphome_prop=`/usr/sbin/smreg list -p | grep "javahelp.home="`
	if [ $? -eq 0 ]; then
	    javahelphome_prop=`echo $javahelphome_prop | cut -d"=" -f2`
	    if [ -n "$javahelphome_prop" ]; then
		JAVAHELP_HOME=$javahelphome_prop
		if [ -f "${JAVAHELP_HOME}/lib/jhall.jar" ]; then
		    return
		fi
		JAVAHELP_HOME=""
	    fi
	fi
    fi

} # findJavaHelp


##############################################################
#
# Install JavaHelp
#
# $1 = relocatable install directory.  If not specified,
#      default of "/" is assumed.
# $2 = base directory
#
##############################################################
#
InstallJavaHelp() {

    # We need 2.0 or better and upgrades do not behave so
    # remove the existing packages before we install jh 2.0

    # Map min version we require to a number we can do a
    # numerical comparison on.
    weWant=`versionString2Num $MIN_JAVAHELP_VERSION`

    JAVAHELP_PKGS="SUNWjhrt SUNWjhdev SUNWjhdoc SUNWjhdem"

    # remove in reverse order of installation
    for helpPkg  in `echo $JAVAHELP_PKGS | \
	awk '{ for (i = NF; i > 0; --i) print $i }'`
    do
	# see how many instances of each javahelp pkg are on the system
	pkginsts=`pkginfo "${helpPkg}*" 2>/dev/null | awk '{print $2}'`
	for pkginst in ${pkginsts}
	do
	    # Get installed version, and map to a number we can do a
	    # numerical comparison on.
	    version=`env LANG=C LC_ALL=C pkgparam ${Rarg} $pkginst VERSION \
		| awk -F',' '{print $1}'`
	    weHave=`versionString2Num $version`
	    # if the pkg instance we have is less than 2.0
	    # remove the package
	    if [ ${weHave} -lt ${weWant} ]; then
		pkgrm -n -a ${ADMIN} ${pkginst}
	    fi
	done
    done

    # Find a suitable JavaHelp runtime.  If find one, use it
    findJavaHelp
    if [ -n "$JAVAHELP_HOME" ]; then
	return
    fi

    relocDir=$1
    baseDir=$2

    # Relocation directory of "/" same as no relocation.
    if [ "${relocDir}" = "/" ]; then
	relocDir=""
	baseDir=""
    fi

    # If relocatable, compose argument for pkg commands.
    Rarg=""
    if [ -n "${relocDir}" ]; then
	Rarg="-R ${relocDir}"
    fi

    # Name for uninstall script
    #
    UNINSTALL_JAVAHELP_SH=${TMPDIR}/${UNINSTALLRC}-javahelp.$$

    # Detect if minimum version is installed.
    #
    pkginsts=`pkginfo ${Rarg} "SUNWjhrt*" 2>/dev/null | awk '{print $2}'`
    for pkginst in $pkginsts
    do
	# Get installed version, and map to a number we can do a
	# numerical comparison on.
	version=`env LANG=C LC_ALL=C pkgparam ${Rarg} $pkginst VERSION \
	    | awk -F',' '{print $1}'`
	weHave=`versionString2Num $version`

	# If JavaHelp version is at least the minimum required version
	# installed here, stop.  We will not install it.
	#
	if [ ${weHave} -ge ${weWant} ]; then
	    # JavaHelp is installed, find where jhall.jar is located.
	    jh_jar=`env LANG=C LC_ALL=C pkgchk ${Rarg} -l $pkginst | grep -i pathname | \
		grep "jhall" | awk '{print $2}' | sort | head -1`
	    jh_jar=`resolve_link $jh_jar`

	    # JAVAHELP_HOME is the parent of the lib directory.
	    libdir=`dirname $jh_jar`
	    JAVAHELP_HOME=`dirname $libdir`

	    return

	fi
    done

    # If we get here, install the pkgs.  Note that we have to keep track
    # of the pkg instance names actually installed, as these may be
    # different than the names used to install in the case of multiple pkg
    # instances on the system.  We need the actual instance names so
    # we can save'em to the uninstall script, so we can delete the right
    # pkgs later on.

    rm -f ${ADMIN_JHSDK}
    sed -e "/instance/s@overwrite@unique@" ${ADMIN} > ${ADMIN_JHSDK}

    PKGINSTS=""
    for i in ${JAVAHELP_PKGS}
    do

	# Install pkg.
	if [ -f ${IMAGEDIR}/${PLATFORM}/${i}.pkg ]; then
	    path2pkg=${IMAGEDIR}/${PLATFORM}/${i}.pkg
	else
	    path2pkg=${IMAGEDIR}/${i}.pkg
	fi
	pkgadd ${VERBOSE} -a ${ADMIN_JHSDK} ${Rarg} -d ${path2pkg} ${i}

	# Determine the pkg instance and output to
	# to running list of pkg instances.  We do this
	# by generating a reverse-sorted list of all pkg instances 
	# of this pkg and taking the 1st value.  Note that this
	# only work for no more than 10 pkg instances because it's
	# string sort, but it is not likely any system will ever
	# have more than 10 versions of JavaHelp installed on it.
	#
	pkginst=`pkginfo ${i}.\* | awk '{print $2}' | sort -r | head -1`
	PKGINSTS="${pkginst} ${PKGINSTS}"

	# Set JAVAHELP_HOME
	if [ ! -n "$JAVAHELP_HOME" ]; then

	    # Find where jhall.jar is located.
	    jh_jar=`env LANG=C LC_ALL=C pkgchk -l $pkginst | \
                fgrep "jhall" | awk '{print $2}' | sort | head -1`
	    if [ ! -n "$jh_jar" ]; then
		continue
	    fi
	    jh_jar=`resolve_link $jh_jar`

	    # JAVAHELP_HOME is the parent of the lib directory.
	    libdir=`dirname $jh_jar`
	    JAVAHELP_HOME=`dirname $libdir`
	fi

    done

    # Output to uninstall script how these pkgs should be uninstalled.
    #
    rm -f ${UNINSTALL_JAVAHELP_SH}
    cat << \DOINSTALL_JH1 \
	| sed -e "s@PKGINSTS@${PKGINSTS}@" \
	| sed -e "s@RARG@${Rarg}@" \
	| sed -e "s@PRODUCT@JavaHelp@g" \
	| sed -e "s@VERSION@${MIN_JAVAHELP_VERSION}@g" \
	> ${UNINSTALL_JAVAHELP_SH}
ans="yes"
if [ $fflag -eq 0 ]; then
    P="Do you want to uninstall the PRODUCT VERSION software? If you have other work that requires the use of PRODUCT VERSION, you may not wish to delete it from your machine.\n\nDo you want to delete it? [n]"

    ans=`/bin/ckyorn -Q -d "no" -p "${P}?"`
fi

if [ "${ans}" = "y" -o "${ans}" = "yes" -o "${ans}" = "Y" -o "${ans}" = "YES" ];
 then
    echo ""
    echo "Removing JavaHelp VERSION ..."
    pkgrm -n RARG -a ${ADMIN} PKGINSTS
fi
DOINSTALL_JH1

    UNINSTALL_SCRIPTS="${UNINSTALL_JAVAHELP_SH} ${UNINSTALL_SCRIPTS}"
    rm -f ${ADMIN_JHSDK}

} # InstallJavaHelp


##############################################################
#
# Install Java
#
# $1 = relocatable install directory.  If not specified,
#      default of "/" is assumed.
# $2 = base directory
#
##############################################################
#
InstallJava() {

    # Find a suitable Java 2 runtime.  If find one, use it.
    findJava
    if [ -n "$JAVA_HOME" ]; then
	return
    fi

    # In order to properly manage new and upgrade installs of Java 2,
    # we require managing all Java pkgs as a single unit.  Otherwise,
    # managing sparse pkgs becomes too complicated.  So we detect the
    # case of sparse pkgs and ask the user if we can delete them first
    # before installing all Java pkgs.

    JAVA_PKGS_REQUIRED="SUNWj3rt SUNWj3dev"
    JAVA_PKGS_OPTIONAL="SUNWj3dmo SUNWj3man SUNWj3cfg"
    JAVA_PKGS="$JAVA_PKGS_REQUIRED $JAVA_PKGS_OPTIONAL"
    numInstalled=0
    installedPkgs=""
    numUninstalled=0

    # First track counts of installed vs uninstalled pkgs, and the names
    # of the installed ones.
    for pkg in ${JAVA_PKGS_REQUIRED}
    do
	pkginfo ${pkg} >/dev/null 2>&1
	if [ $? -eq 0 ]; then
	    numInstalled=`(expr $numInstalled + 1)`
	    installedPkgs="${installedPkgs} ${pkg}"
	else
	    numUninstalled=`(expr $numUninstalled + 1)`
	fi
    done

    installedOptPkgs=""

    # First track counts of optional installed vs uninstalled pkgs, 
    # and the names of the installed ones.
    for pkg in ${JAVA_PKGS_OPTIONAL}
    do
        pkginfo ${pkg} >/dev/null 2>&1
        if [ $? -eq 0 ]; then
            installedOptPkgs="${installedOptPkgs} ${pkg}"
        fi
    done

    # If not all required pkgs are installed, prompt user.
    if [ $numInstalled -ne 0 -a $numUninstalled -ne 0 ]; then
	P="${PARTIAL_JAVA_MSG1}\n\t${installedPkgs} ${installedOptPkgs}\n${PARTIAL_JAVA_MSG2}"
	P="${P} ${MIN_JAVA_VERSION}.  ${PARTIAL_JAVA_MSG3}"
	if [ $fflag -eq 1 ]; then
	    ans="yes"
	else
	    ans=`/bin/ckyorn -Q -d "no" -p "${P}"`
	fi
	if [ "${ans}" = "y" -o "${ans}" = "yes" -o \
	     "${ans}" = "Y" -o "${ans}" = "YES" ]; then
	    pkgrm -n -a ${ADMIN} ${installedPkgs} ${installedOptPkgs}
	    numInstalled=0
	else
	    echo "Setup exiting - no changes have been made to your system."
	    exit ${EXIT_SUCCESS}
	fi
    fi


    # At this point, we have required JDK pkgs on the system.  Now verify
    # their integrity for at least the bits we must have.
    if [ $numInstalled -ge 2 ]; then

	# If pkg versions don't match, ask user to blow away existing pkgs
	# so we can install new ones.
        rtVersion=`env LANG=C LC_ALL=C \
                pkgparam SUNWj3rt VERSION | awk -F',' '{print $1}'`
        devVersion=`env LANG=C LC_ALL=C \
                pkgparam SUNWj3dev VERSION | awk -F',' '{print $1}'`
	if [ "$rtVersion" != "$devVersion" ]; then
	    P="${MISMATCHED_JAVA_MSG1}"
	    P="${P}SUNWj3rt is version $rtVersion\n"
	    P="${P}SUNWj3dev is version $devVersion\n"
	    P="${P}\n${PARTIAL_JAVA_MSG2}:\n"
	    P="${P}\t${installedPkgs} ${installedOptPkgs}\n"
	    P="${P}\n${PARTIAL_JAVA_MSG3}"
	    if [ $fflag -eq 1 ]; then
		ans="yes"
	    else
		ans=`/bin/ckyorn -Q -d "no" -p "${P}"`
	    fi
	    if [ "${ans}" = "y" -o "${ans}" = "yes" -o \
		"${ans}" = "Y" -o "${ans}" = "YES" ]; then
		pkgrm -n -a ${ADMIN} ${installedPkgs} ${installedOptPkgs}
	    else
		echo "Setup exiting - no changes have been made to your system."
		exit ${EXIT_SUCCESS}
	    fi
	fi


	# If bits we need don't exist, ask user to blow away existing pkgs
	# so we can install new ones.

	base=`env LANG=C LC_ALL=C pkgparam SUNWj3rt BASEDIR`

	# java
	java=${base}/j2se/bin/java
	missing=""
	pkgchk -q -c -p $java SUNWj3rt
	if [ $? -ne 0 ]; then
	    missing="$missing $java"
	fi

	# javac
	javac=${base}/j2se/bin/javac
	pkgchk -q -c -p $javac SUNWj3dev
	if [ $? -ne 0 ]; then
	    missing="$missing $javac"
	fi

	if [ -n "$missing" ]; then
	    P="${BAD_JAVA_MSG1}\n\t${missing}\n\n${PARTIAL_JAVA_MSG2}:\n"
	    P="${P}\t${installedPkgs} ${installedOptPkgs}\n"
	    P="${P}\n${PARTIAL_JAVA_MSG3}"
	    if [ $fflag -eq 1 ]; then
		ans="yes"
	    else
		ans=`/bin/ckyorn -Q -d "no" -p "${P}"`
	    fi
	    if [ "${ans}" = "y" -o "${ans}" = "yes" -o \
		"${ans}" = "Y" -o "${ans}" = "YES" ]; then
		pkgrm -n -a ${ADMIN} ${installedPkgs} ${installedOptPkgs}
	    else
		echo "Setup exiting - no changes have been made to your system."
		exit ${EXIT_SUCCESS}
	    fi
	fi
    fi


    relocDir=$1
    baseDir=$2

    # Relocation directory of "/" same as no relocation.
    if [ "${relocDir}" = "/" ]; then
	relocDir=""
	baseDir=""
    fi

    # If relocatable, compose argument for pkg commands.
    Rarg=""
    if [ -n "${relocDir}" ]; then
	Rarg="-R ${relocDir}"
    fi

    # Map min version we require to a number we can do a
    # numerical comparison on.
    weWant=`versionString2Num $MIN_JAVA_VERSION`

    # Name for uninstall script
    #
    UNINSTALL_JAVA2_SH=${TMPDIR}/${UNINSTALLRC}-java2.$$

    # Need location to install.  Either upgrade existing installation,
    # or install in new location.  Whereever we detect Java is located,
    # regardless of whether we install it or not, track the location
    # in JAVA_HOME.
    #
    j2basedir=""
    j2upgrade=0
    JAVA_HOME=""
    pkginfo ${Rarg} SUNWj3rt >/dev/null 2>&1
    if [ $? -eq 0 ]; then

	# Java 2 SDK is installed, find where it's installed.
	j2basedir=`env LANG=C LC_ALL=C pkgparam ${Rarg} SUNWj3rt BASEDIR`

	# Loop forever until we have place to install to.
	#
	while [ 1 ]
	do

	    # If pkg does not exist at specified relocatable area,
	    # then assume we can relocate it there using
	    # a base directory of $j2basedir.
	    pkginfo ${Rarg} SUNWj3rt >/dev/null 2>&1
	    if [ $? -ne 0 ]; then
		break
	    fi

	    # Get version, and map to a number we can do a
	    # numerical comparison on.
	    java=${j2basedir}/j2se/bin/java
	    version=`${java} -version 2>&1 | head -1`
	    version=`echo $version | awk '{print $3}' | sed -e "s/\"//g"`
	    weHave=`versionString2Num $version`

	    # If Java version is at least the minimum required version installed
	    # here, stop.  We will not install it.
	    #
	    if [ ${weHave} -gt ${weWant} ]; then
		j2basedir=""
		JAVA_HOME=${relocDir}${j2basedir}/j2se
		break
	    fi

	    relocDir=`echo ${relocDir} | sed -e 's@/*$@@' -e 's@//*@/@g'`

	    # We don't have the minimum.  Ask user to upgrade it.  If yes, stop.
	    #
	    P="Java version $MIN_JAVA_VERSION or greater is required."
	    P="${P}  You currently have Java ${version} installed in ${relocDir}${j2basedir}/j2se."
	    P="${P}  Do you wish to upgrade it to Java version $MIN_JAVA_VERSION or greater? [n]"
	    if [ $fflag -eq 1 ]; then
		ans="yes"
	    else
		ans=`/bin/ckyorn -Q -d "no" -p "${P}"`
	    fi
	    if [ "${ans}" = "y" -o "${ans}" = "yes" -o \
	 	 "${ans}" = "Y" -o "${ans}" = "YES" ]; then
		j2upgrade=1
		break
	    fi

	    # Upgrade denied, so ask user for an install directory
	    #
	    P="Enter the directory path in which to install Java version $MIN_JAVA_VERSION or greater"
	    relocDir=`/bin/ckpath -ayQ -p "${P}"`
	    Rarg="-R ${relocDir}"
	done

    else

	# Java 2 SDK is not installed, so we will install into /usr
	j2basedir="/usr"

    fi

    # If have location to install, then do so now.
    #
    if [ -n "${j2basedir}" ]; then

	# For Java 2, we change the default basedir.  But only allow
	# multiple pkg instances if not upgrading, since the current pkg
	# database information must persist.  When upgrading, we can
	# blow away the existing pkgs first.
	#
	rm -f ${ADMIN_J2SDK}
	if [ $j2upgrade -eq 1 ]; then
	    # Upgrade, so remove in reverse order of installation
	    cp ${ADMIN} ${ADMIN_J2SDK}
	    for i in `echo $JAVA_PKGS | \
		    awk '{ for (i = NF; i > 0; --i) print $i }'`
	    do
		pkginfo ${Rarg} $i >/dev/null 2>&1
		if [ $? -eq 0 ]; then
		    pkgrm -n -a $ADMIN_J2SDK $Rarg $i
		fi
	    done
	else
	    if [ -n "${baseDir}" ]; then
		sed -e "/basedir/s@default@${baseDir}@" \
		    -e "/instance/s@overwrite@unique@" ${ADMIN} > ${ADMIN_J2SDK}
	    else
		sed -e "/basedir/s@default@${baseDir}${j2basedir}@" \
		    -e "/instance/s@overwrite@unique@" ${ADMIN} > ${ADMIN_J2SDK}
	    fi
	fi


	# Create basedir and install the pkgs.  Note that we have to keep track
	# of the pkg instance names actually installed, as these may be
	# different than the names used to install in the case of multiple pkg
	# instances on the system.  We need the actual instance names so
	# we can save'em to the uninstall script, so we can delete the right
	# pkgs later on.
	#
	mkdir -p ${relocDir}${j2basedir}
	JAVA_HOME=${relocDir}${j2basedir}/j2se
	PKGINSTS=""
	for i in ${JAVA_PKGS}
	do

	    # Install pkg.
	    if [ -f ${IMAGEDIR}/${PLATFORM}/${i}.pkg ]; then
		path2pkg=${IMAGEDIR}/${PLATFORM}/${i}.pkg
	    else
		path2pkg=${IMAGEDIR}/${i}.pkg
	    fi
	    pkgadd ${VERBOSE} -a ${ADMIN_J2SDK} ${Rarg} -d ${path2pkg} ${i}

	    # Determine the pkg instance and output to
	    # to running list of pkg instances.  We do this
	    # by generating a reverse-sorted list of all pkg instances 
	    # of this pkg and taking the 1st value.  Note that this
	    # only work for no more than 10 pkg instances because it's
	    # string sort, but it is not likely any system will ever
	    # have more than 10 versions of Java installed on it.
	    #
	    pkginst=`pkginfo ${i}.\* | awk '{print $2}' | sort -r | head -1`
	    PKGINSTS="${pkginst} ${PKGINSTS}"

	done


	# Output to uninstall script how these pkgs should be uninstalled.
	#
	version=`$JAVA_HOME/bin/java -version 2>&1 | head -1`
	version=`echo $version | awk '{print $3}' | sed -e "s/\"//g"`
	rm -f ${UNINSTALL_JAVA2_SH}
	cat << \DOINSTALL_EOF1 \
		| sed -e "s@PKGINSTS@${PKGINSTS}@" \
		| sed -e "s@RARG@${Rarg}@" \
		| sed -e "s@PRODUCT@Java@g" \
		| sed -e "s@VERSION@${version}@g" \
		> ${UNINSTALL_JAVA2_SH}
ans="yes"
if [ $fflag -eq 0 ]; then
    P="Do you want to uninstall the PRODUCT VERSION software? If you have other work that requires the use of PRODUCT VERSION, you may not wish to delete it from your machine.\n\nDo you want to delete it? [n]"

    ans=`/bin/ckyorn -Q -d "no" -p "${P}?"`
fi

if [ "${ans}" = "y" -o "${ans}" = "yes" -o "${ans}" = "Y" -o "${ans}" = "YES" ];
 then
    echo ""
    echo "Removing Java VERSION ..."
    pkgrm -n RARG -a ${ADMIN} PKGINSTS
fi
DOINSTALL_EOF1

	UNINSTALL_SCRIPTS="${UNINSTALL_JAVA2_SH} ${UNINSTALL_SCRIPTS}"
	rm -f ${ADMIN_J2SDK}
    fi

} # InstallJava


##############################################################
#
# Install man pages
#
# $1 = relocatable install directory.  If not specified,
#      default of "/" is assumed.
# $2 = base directory
#
##############################################################
#
InstallManPages() {

    relocDir=$1
    baseDir=$2

    # Relocation directory of "/" same as no relocation.
    if [ "${relocDir}" = "/" ]; then
	relocDir=""
	baseDir="/usr"
    fi

    # If relocatable, compose argument for pkg commands.
    Rarg=""
    if [ -n "${relocDir}" ]; then
	Rarg="-R ${relocDir}"
    fi

    # Install the man pages, possibly on top of an older version.
    # The older version may have been installed when the OS was installed,
    # in which case we unregister it from the pkg DB before installing
    # the new page and re-registering.
    #
    # We have to install the man pages directly here, rather than out of a
    # pkg because all our pkgs are also part of Solaris install, but the
    # man pages are already installed by the SUNWman pkg.
    #
    MANPKG=SUNWman
    pkginfo ${Rarg} ${MANPKG} >/dev/null 2>&1
    if [ $? -eq 0 ]; then
	echo "\nInstalling man pages ..."
	for i in smreg smcwebserver
	do
	    # First determine where an existing page is installed.
	    manpage=`env LANG=C LC_ALL=C pkgchk ${Rarg} -l $MANPKG | \
		grep -i Pathname | awk '{print $2}' | grep ${i}.1m`
	    if [ $? -eq 0 ]; then
		# Found existing page - unregister it from pkg DB.
		removef ${Rarg} $MANPKG $manpage >/dev/null
		removef ${Rarg} -f $MANPKG
	    else
		# Not found, so determine where the "sman1m" pages are located.
		# By sorting and pulling off the 1st one, we get the 
		# directory path.
		manpage=`env LANG=C LC_ALL=C pkgchk ${Rarg} -l $MANPKG \
		    | grep -i Pathname \
		    | awk '{print $2}' | grep sman1m | sort | head -1`

		# Should have it by now, but if not use a default.
		if [ ! -n "${manpage}" ]; then
		    manpage=${relocDir}${basedir}/share/man/sman1m
		fi

		manpage=${manpage}/$i.1m
	    fi

	    # Install the man page and register it with the pkg DB.
	    cp ${IMAGEDIR}/${i}.1m $manpage
	    chmod 444 $manpage
	    installf ${Rarg} $MANPKG $manpage f 0444 root bin
	    installf ${Rarg} -f $MANPKG
	done
    fi

} # InstallManPages



##############################################################
#
# Do everything required to prepare for this script being used
# later for uninstall.
#
# $1 = name of pkg to which we can attach additional files
#      so that they'll be removed when the pkg is removed.
# $2 = relocatable directory for pkg specified in $1
#
##############################################################
#
SetupUninstall() {

    primaryPkg=$1
    relocDir=$2

    # Relocation directory of "/" same as no relocation.
    if [ "${relocDir}" = "/" ]; then
	relocDir=""
    fi

    # If relocatable, compose argument for pkg commands.
    Rarg=""
    if [ -n "${relocDir}" ]; then
	Rarg="-R ${relocDir}"
    fi

    # Because this setup script doubles as an uninstaller, we have to install
    # ourselves someplace where it's accessible, as user might not
    # keep the install media around.  So copy this setup script to an
    # appropriate location, and register it with the pkg database.  And for 
    # the same reasons, we do the same with the uninstall script.

    if [ -n "${primaryPkg}" ]; then

	# First find the base directory for the pkg
	PKG=${primaryPkg}
	basedir=`env LANG=C LC_ALL=C pkgparam ${Rarg} ${PKG} BASEDIR`

	# 2ndly copy the setup script and register it, dynamically substituting
	# the primary pkg name so we can use it during uninstall.
	dest="${basedir}/usr/lib/webconsole/`basename $PROG`"
	sed -e "/__THE_PRIMARY_PKG__/s/THIS_WILL_BE_DYNAMICALLY_DETERMINED/${PKG}/" $PROG > ${relocDir}${dest}
	installf -c none ${Rarg} ${PKG} ${dest} f 555 root bin

	# 3rdly, concatenate all uninstall scripts into a single script and
	# register it.
	dest="${basedir}/usr/lib/webconsole/${UNINSTALLRC}"
	echo "# THIS FILE IS AUTOMATICALLY GENERATED.  DO NOT EDIT!" \
		> ${relocDir}${dest}
	cat ${UNINSTALL_SCRIPTS} >> ${relocDir}${dest}

	chmod 444 ${relocDir}${dest}
	installf -c none ${Rarg} ${PKG} ${dest} f 444 root bin

	# Notify the pkg database we're done.
	installf -f ${Rarg} ${PKG}

    else
	# Can't find pkg to register uninstall information

	echo "${PROG} is unable to determine what the primary web console package"
	echo "is, and thus cannot create an install log.  This means that"
	echo "\"${PROG} -u\" cannot be used to uninstall the packages."
	if [ $nflag -eq 0 ]; then
	    echo "It also means that the server will not automatically be"
	    echo "started because the server startup script cannot be located."
	    echo "However, if you know where the script is located, you can"
	    echo "run it manually to start the server."
	fi

	nflag=1  # to disable server startup, below
    fi

} # SetupUninstall



##############################################################
#
# Locate the uninstall script and execute it.
#
# $2 = relocatable directory of pkgs to search for script
#
##############################################################
#
RunUninstallrc() {

    relocDir=$1

    # Relocation directory of "/" same as no relocation.
    if [ "${relocDir}" = "/" ]; then
	relocDir=""
    fi

    # If relocatable, compose argument for pkg commands.
    Rarg=""
    if [ -n "${relocDir}" ]; then
	Rarg="-R ${relocDir}"
    fi

    # In order to find the uninstall script, we need to first find the pkg
    # the script is registered with.  If setup was invoked from the install
    # media, we can determine the pkg by scanning the core pkgs listed in
    # the .pkgrc file.
    #
    PKG=""
    if [ -f `dirname $PROG`/${PKGRC} ]; then
	. `dirname $PROG`/${PKGRC}

	for i in ${CORE_PKGS}; do
	    out=`env LANG=C LC_ALL=C pkgchk -l ${Rarg} $i 2>&1 | \
		grep -i Pathname | grep "${CONSOLE_SEARCH_TOKEN}" | \
		sort | head -1`
	    if [ -n "${out}" ]; then
		PKG=$i
		break
	    fi
	done
    else
	# Otherwise setup was invoked from install location, in which
	# case setup modified itself during that install to set the
	# pkg name here in place of the special string below.
	# DO NOT EDIT ANYTHING ON THIS LINE!!!!
	# THE VALUE AND THE COMMENT ARE USED FOR FIND & REPLACE!!
	#
	PKG="THIS_WILL_BE_DYNAMICALLY_DETERMINED"  # __THE_PRIMARY_PKG__
    fi

    if [ "${PKG}" = "" -o "${PKG}" = "THIS_WILL_BE_DYNAMICALLY_DETERMINED" ]; then
	echo "Unable to determine package containing uninstall script."
	echo "You will have to uninstall the packages manually using the"
	echo "pkgrm command."
	if [ -f `dirname $PROG`/${PKGRC} ]; then
	    echo "Look in `dirname $PROG`/${PKGRC} for the list of packages."
	fi
	exit ${EXIT_NO_UNINSTALL_LOG}
    fi

    # Find the base directory for the web console pkg
    basedir=""
    pkginfo ${Rarg} ${PKG} >/dev/null 2>&1
    if [ $? -eq 0 ]; then
	basedir=`env LANG=C LC_ALL=C pkgparam ${Rarg} ${PKG} BASEDIR`
    fi

    # Copy the uninstall script to a temp area so we get out of
    # the way of the pkg software.
    UNINSTALL_SH=${TMPDIR}/${UNINSTALLRC}.$$
    rm -f ${UNINSTALL_SH}
    if [ ! -f "${relocDir}${basedir}/usr/lib/webconsole/${UNINSTALLRC}" ]; then
	echo "Unable to find uninstall script."
	echo "You will have to uninstall the packages manually using the"
	echo "pkgrm command."
	if [ -f `dirname $PROG`/${PKGRC} ]; then
	    echo "Look in `dirname $PROG`/${PKGRC} for the list of packages."
	fi
	exit ${EXIT_NO_UNINSTALL_LOG}
    fi
    cp ${relocDir}${basedir}/usr/lib/webconsole/${UNINSTALLRC} ${UNINSTALL_SH}

    # Execute it
    . ${UNINSTALL_SH}
    rm -f ${UNINSTALL_SH}

} # RunUninstallrc



##############################################################
#
# Install the pkgs.  For each pkg installed, log to a script
# how the pkg is to be uninstalled.  This script will be
# executed when the pkgs are to be removed.
#
##############################################################
#
DoInstall() {

    # Test for previously installed console packages.
    PKGS=""
    if [ -f ${IMAGEDIR}/${PKGRC} ]; then
	. ${IMAGEDIR}/${PKGRC}
	PKGS="${PKGS} ${CORE_PKGS} ${OPTIONAL_PKGS}"
    fi
    testConsolePackages "${PKGS}"

    # Ensure server is stopped, in the case of upgrading.
    shutdown

    REG_DIR=/usr/share/webconsole/lib/.reg
    if [ -d "${REG_DIR}" ]; then
	SMREG=/usr/sbin/smreg
	if [ -x $SMREG ]; then
	    for i in `ls -A ${REG_DIR} | sort`
	    do
		sh $REG_DIR/$i
	    done
	fi
	rm -rf ${REG_DIR}
	rm -rf /var/opt/webconsole/.reg >/dev/null 2>&1
    fi

    # We must blow away Tomcat's work directory because there may be
    # compiled JSP's which are not compatibile with the new bits we are
    # about to install.  One would think that installing new JSP's would
    # trigger an automatic re-compile, but it doesn't appear so.
    WORK_DIR=/var/opt/webconsole/work
    if [ -d $WORK_DIR ]; then
	rm -rf $WORK_DIR
    fi


    ###############     BZIP     ###############

    InstallBzip

    ###############     END BZIP     ###############


    ###############     JAVA     ###############

    InstallJava
    InstallJavaHelp

    echo "java.home=$JAVA_HOME" > $PREREG

    ###############     END JAVA     ###############


    ###############     TOMCAT       ###############

    # Name for uninstall script
    #
    UNINSTALL_TOMCAT_SH=${TMPDIR}/${UNINSTALLRC}-tomcat.$$

    # Install Tomcat Servlet/JSP Container pkg, if not already installed.
    #
    pkginfo ${TOMCAT_PKG} >/dev/null 2>&1
    if [ $? -ne 0 ]; then

	# For Tomcat, we change the default basedir
	rm -f ${ADMIN_TOMCAT}
	sed -e "/basedir/s@default@${TOMCAT_INSTALLDIR}@" ${ADMIN} > ${ADMIN_TOMCAT}

	# Create basedir and install the pkg.
	mkdir -p ${TOMCAT_INSTALLDIR}
	if [ -f ${IMAGEDIR}/${PLATFORM}/${TOMCAT_PKG}.pkg ]; then
	    path2pkg=${IMAGEDIR}/${PLATFORM}/${TOMCAT_PKG}.pkg
	else
	    path2pkg=${IMAGEDIR}/${TOMCAT_PKG}.pkg
	fi
	pkgadd ${VERBOSE} -a ${ADMIN_TOMCAT} -d ${path2pkg} ${TOMCAT_PKG}

	# Create pkg registration entry for basedir.
	#
	installf -c none ${TOMCAT_PKG} ${TOMCAT_INSTALLDIR} d 755 root sys
	installf -f ${TOMCAT_PKG}

	# Output to uninstall script how this pkg should be uninstalled.
	#
	rm -f ${UNINSTALL_TOMCAT_SH}
	cat << \DOINSTALL_EOF2 | sed -e "s/TOMCAT_PKG/${TOMCAT_PKG}/" > ${UNINSTALL_TOMCAT_SH}
ans="yes"
if [ $fflag -eq 0 ]; then
    P="Do you want to uninstall the Tomcat Servlet/JSP Container software? If you have other work that requires the use of Tomcat Servlet/JSP Container, you may not wish to delete it from your machine.\n\nDo you want to delete it? [n]"
    ans=`/bin/ckyorn -Q -d "no" -p "${P}?"`
fi

if [ "${ans}" = "y" -o "${ans}" = "yes" -o "${ans}" = "Y" -o "${ans}" = "YES" ];
 then
    echo ""
    echo "Removing TOMCAT_PKG ..."
    pkgrm -n -a ${ADMIN} TOMCAT_PKG
fi
DOINSTALL_EOF2

	UNINSTALL_SCRIPTS="${UNINSTALL_TOMCAT_SH} ${UNINSTALL_SCRIPTS}"
	rm -f ${ADMIN_TOMCAT}

    fi

    ###############     END TOMCAT       ###############



    ###############     WEB CONSOLE       ###############


    # Name for uninstall script
    #
    UNINSTALL_CONSOLE_SH=${TMPDIR}/${UNINSTALLRC}-console.$$

    # Install Web Console pkgs (core and optional)
    #
    PKGS=""
    if [ -f ${IMAGEDIR}/${PKGRC} ]; then
	. ${IMAGEDIR}/${PKGRC}
	PKGS="${PKGS} ${CORE_PKGS} ${OPTIONAL_PKGS}"
    fi

    PRIMARYPKG=""
    RMPKGS=""
    for pkg in ${PKGS}
    do
	# Never downgrade the installed pkg!
	if [ -n "$DOWNGRADES" ]; then
	    echo "${DOWNGRADES}" | grep ${pkg} > /dev/null
	    if [ $? -eq 0 ]; then
		continue
	    fi
	fi

	if [ -f ${IMAGEDIR}/${PLATFORM}/${pkg}.pkg ]; then
	    path2pkg=${IMAGEDIR}/${PLATFORM}/${pkg}.pkg
	else
	    path2pkg=${IMAGEDIR}/${pkg}.pkg
	fi
	pkgadd ${VERBOSE} -a ${ADMIN} -d ${path2pkg} ${pkg}
	RMPKGS="${pkg} ${RMPKGS}"

	# See if this is the primary web console pkg.  We need to determine
	# this so that we have a pkg to register some additional entries, below.
	#
	out=`env LANG=C LC_ALL=C pkgchk -l $pkg 2>&1 | \
		grep -i Pathname | grep "${CONSOLE_SEARCH_TOKEN}" | \
		sort | head -1`
	if [ -n "${out}" ] && [ ! -n "${PRIMARYPKG}" ]; then
	    PRIMARYPKG=$pkg
	fi

    done

    rm -f ${UNINSTALL_CONSOLE_SH}
    for pkg in ${RMPKGS}
    do
	echo "echo \"Removing ${pkg} ...\"" >> ${UNINSTALL_CONSOLE_SH}
	echo "pkgrm -n -a \${ADMIN} ${pkg}" >> ${UNINSTALL_CONSOLE_SH}
    done

    UNINSTALL_SCRIPTS="${UNINSTALL_CONSOLE_SH} ${UNINSTALL_SCRIPTS}"


    InstallManPages


    ###############     END WEB CONSOLE       ###############


    # Everything is in place, so we can remove $PREREG
    rm -f $PREREG

    # Setup for later uninstall.
    SetupUninstall ${PRIMARYPKG}

    # Remove all the temporary uninstall scripts for each component
    rm ${UNINSTALL_SCRIPTS}

    echo ""
    echo "Installation complete."
    echo ""

    # Save JAVA_HOME and JAVAHELP_HOME as properties for export to other 
    # programs that implement Java abd JavaHelp search algorithms
    # (eg., smcwebserver).
    /usr/sbin/smreg add -p -c java.home=$JAVA_HOME
    /usr/sbin/smreg add -p -c javahelp.home=$JAVAHELP_HOME

    # Start the webserver, unless automatic start is disabled
    if [ $nflag -eq 0 ]; then

	# If already running, restart it.  Otherwise, just start.
	SMCWEBSERVER="${basedir}/usr/sbin/smcwebserver"
	cmd=start
	ans=`$SMCWEBSERVER status -p | grep running | cut -d"=" -f2`
	if [ "$ans" = "yes" ]; then
	    cmd=restart
	fi
	env JAVA_HOME=${JAVA_HOME} ${SMCWEBSERVER} $cmd
    fi

} # DoInstall



##############################################################
#
# Uninstall the pkgs.  During install, a script was automatically
# generated defining how each pkg needs to be uninstalled.  So
# we simply "source" it.
#
##############################################################
#
DoUninstall() {

    shutdown
    RunUninstallrc

    echo ""
    echo "Uninstallation complete."
    echo ""

} # DoUninstall


##############################################################
#
# Shut down server if it is running.
#
##############################################################
#
shutdown() {

    # If server running, must be upgrading.  So shut it down before
    # installing new bits.  Note that "status" command did not exist
    # in 1.0, so we have no choice but to test for the existence of the
    # server's pid file to tell if a 1.0 server is running.
    #
    SMCWEBSERVER=/usr/sbin/smcwebserver
    if [ ! -x $SMCWEBSERVER ]; then
	SMCWEBSERVER=/usr/sadm/bin/smcwebserver
    fi
    if [ -x $SMCWEBSERVER ]; then
	version=`$SMCWEBSERVER --version | awk '{print $NF}'`
	major=`echo $version | cut -d"." -f1`
	minor=`echo $version | cut -d"." -f2`
	if [ $major -eq 1 -a $minor -eq 0 ]; then
	    if [ -f /var/run/smcwebserver.pid ]; then
		$SMCWEBSERVER stop
	    fi
	else
	    ans=`$SMCWEBSERVER status -p | grep running | cut -d"=" -f2`
	    if [ "$ans" = "yes" ]; then
		$SMCWEBSERVER stop
	    fi
	fi
    fi

} # shutdown


##############################################################
#
# Test for previously installed console packages.
#
# $1 = packages to test.
#
# $2 = relocatable install directory.  If not specified,
#      default of "/" is assumed.
#
##############################################################
#
testConsolePackages() {
    pkgs=$1
    relocDir=$2

    # Relocation directory of "/" same as no relocation.
    if [ "${relocDir}" = "/" ]; then
	relocDir=""
    fi

    # If relocatable, compose argument for pkg commands.
    Rarg=""
    if [ -n "${relocDir}" ]; then
	Rarg="-R ${relocDir}"
    fi

    # Test each package to be installed.
    for pkg in ${1}
    do
	if [ -f ${IMAGEDIR}/${PLATFORM}/${pkg}.pkg ]; then
	    path2pkg=${IMAGEDIR}/${PLATFORM}/${pkg}.pkg
	else
	    path2pkg=${IMAGEDIR}/${pkg}.pkg
	fi

	# Test if package exists.
	pkginfo ${Rarg} ${pkg} >/dev/null 2>&1
	if [ $? -eq 0 ]; then
	    # Get version of package to be installed, convert to a version num
	    INSTALLING_VERSION=`env LANG=C LC_ALL=C \
		pkgparam -d ${path2pkg} ${pkg} VERSION | awk -F',' '{print $1}'`
	    INSTALLING_VERSION_NUM=`versionString2Num $INSTALLING_VERSION`

	    # Get version of installed package, convert to a version num
	    CURRENT_VERSION=`env LANG=C LC_ALL=C \
		pkgparam ${Rarg} ${pkg} VERSION | awk -F',' '{print $1}'`
	    CURRENT_VERSION_NUM=`versionString2Num $CURRENT_VERSION`

	    # If the version number of the package to be installed is greater
	    # than the version number of the installed package, then we have an 
	    # upgrade scenario and we must prompt the user. If the version 
	    # number of the upgrade package to be installed is less than the
	    # version number of the installed package, then we have a downgrade
	    # scenario and we should exit.

	    # Determine if the pkg to be installed is a Web Console pkg.
	    NAME=`env LANG=C LC_ALL=C pkgparam -d ${path2pkg} ${pkg} NAME`
	    echo $NAME | grep "Web Console" >/dev/null
	    isWebConsole=`(expr 1 - $?)`

	    if [ $INSTALLING_VERSION_NUM -lt $CURRENT_VERSION_NUM ]; then

		# Non-console dependent pkgs that would be downgraded are
		# flagged so that they won't be installed.
		if [ $isWebConsole -eq 0 ]; then
		    DOWNGRADES="$DOWNGRADES $pkg"
		    continue
		fi

		echo "The Sun Java(TM) Web Console software already installed (version $CURRENT_VERSION)"
		echo "is newer than the version ($INSTALLING_VERSION) you are attempting to install."
		echo "Downgrading is not supported.  If you wish to run the older version,"
		echo "you can install it after unintalling the currently installed version."
		exit $EXIT_DOWNGRADE
	    else

		# No prompting for upgrade of non-console dependent pkgs.
		# Just upgrade them automatically.
		if [ $isWebConsole -eq 0 ]; then
		    continue
		fi

		ans="no"
		P="The Sun Java(TM) Web Console software is about to be upgraded."
		P="${P} \n\nDo you want to continue? [n]"
		if [ $fflag -eq 1 ]; then
		    ans="yes"
		else
		    ans=`/bin/ckyorn -Q -d "no" -p "${P}?"`
		fi

		if [ "${ans}" = "y" -o "${ans}" = "yes" -o "${ans}" = "Y" -o "${ans}" = "YES" ]; then
		    break
		else
		    echo ""
		    echo "Exiting ..."
		    exit $EXIT_UPGRADE
		fi
	    fi
	fi
    done

} # testConsolePackages



#
# User is now root, proceed with installation.
#

# Before installing or uninstalling, we must check for any outstanding
# registration requests that may have been posted during an OS install,
# but which have not been processed because the server was never started.
# In order to properly manage this, we must process those requests now
# by executing any deferred registration scripts.  These could be scripts
# that were generated as a result of an OS upgrade as well as scripts
# generated as per normal registration during a fresh install.  To avoid
# exposing these deferred registrations that might otherwise confuse the
# user, we process them silently.  After processing, delete them and
# their counterparts in /var, since we'll never need them again.
# See the smreg script for details on these self-timestamped scripts.
#
FLUSH_MSG="Synchronizing registration databases.  Please wait ..."
wasMsgOutput=0
SMREG=/usr/sbin/smreg
UPGRADERC=/usr/share/webconsole/lib/.upgraderc
if [ -f "${UPGRADERC}" ]; then
    if [ -x $SMREG ]; then
	echo $FLUSH_MSG
	wasMsgOutput=1
	echo ".\c"
	sh ${UPGRADERC} >/dev/null
    fi
fi
rm -f $UPGRADERC >/dev/null 2>&1
rm -f /var/opt/webconsole/.upgradeDate >/dev/null 2>&1

REG_DIR=/usr/share/webconsole/lib/.reg
if [ -d "${REG_DIR}" ]; then
    if [ -x $SMREG ]; then
	if [ $wasMsgOutput -eq 0 ]; then
	    echo $FLUSH_MSG
	fi
	for i in `ls -A ${REG_DIR} | sort`
	do
	    echo ".\c"
	    sh $REG_DIR/$i >/dev/null
	done
    fi
fi
rm -rf ${REG_DIR} >/dev/null 2>&1
rm -rf /var/opt/webconsole/.reg >/dev/null 2>&1
echo ""



# Create admin files
#
rm -f ${ADMIN}
echo "mail=" >> ${ADMIN}
echo "instance=overwrite" >> ${ADMIN}
echo "partial=nocheck" >> ${ADMIN}
echo "runlevel=nocheck" >> ${ADMIN}
echo "idepend=nocheck" >> ${ADMIN}
echo "rdepend=nocheck" >> ${ADMIN}
echo "space=nocheck" >> ${ADMIN}
echo "setuid=nocheck" >> ${ADMIN}
echo "conflict=nocheck" >> ${ADMIN}
echo "action=nocheck" >> ${ADMIN}
echo "basedir=default" >> ${ADMIN}

# Each of the components will yield an uninstall script that 
# uninstalls the pkgs for the component in the correct order.  To
# ensure that the components themselves are uninstalled in the correct
# order, each component must **prepend** its uninstall script to
# this variable.  This means that it is a requirement that components
# must be installed in the correct order.

UNINSTALL_SCRIPTS=""

if [ $uflag -eq 1 ]; then
    DoUninstall
else
    DoInstall
fi

rm -f ${ADMIN}
exit ${EXIT_SUCCESS}
