#!/bin/ksh
#
#ident  "@(#)setup.sh 1.46 03/09/19 SMI"
#
# This utility installs the packages associated with PatchPro 2.2.
# While it installs, it creates an uninstall script that will undo everything
# this script does.
#
SETUPDIRECTORY=`dirname $0`
PATCHLIST=`cat ${SETUPDIRECTORY}/patchlist`
PRODDIR=${SETUPDIRECTORY}
PATCHPROPKG="SUNWppro"
BACKOUTSCRIPT=uninstallpatchpro
REMOVEPATH="/var/tmp/${BACKOUTSCRIPT}"
LOG="/var/tmp/ppro_install_log.$$"
J2SEPATH="/usr/j2se"
INSTALLPKG=false
REMOVETHIS=""
ALREADYINSTALLED="false"
REMOTEDIST="false"
MODADMINFILE="/var/tmp/admin"
MODADMINFILETMP="/var/tmp/admin.$$"
SMPPKG="SUNWpmgr"
JREPKGS="SUNWj3rt SUNWlj3rt SUNWj3dev"
JREJSPKGS="SUNWjsse"
JAXPPKGS="SUNWjaxp"
JAVAPKGLIST="${JREPKGS} ${JREJSPKGS}"
SUPRTPKGLIST="${JAVAPKGLIST} SUNWsdb SUNWapcy SUNWppmn ${SMPPKG}"
CFGPKGLIST="SUNWppcfg"
REQPKGLIST="SUNWmfrun SUNWlibC SUNWadmc SUNWadmfw"
REQS6PKGLIST="${REQPKGLIST} SUNWxcu4"
INCLUDESJAVA=0
BAK_CONFIGFILE="/var/tmp/old_patchpro.conf.$$"
SUNW_JSSE_BASE_DIR="/usr/j2se/opt"
SUNW_APCY_BASE_DIR="/opt/SUNWapcy"
SUNW_SDB_BASE_DIR="/opt/SUNWsdb"
SUNW_PPRO_BASE_DIR="/opt/SUNWppro"

CP="/usr/bin/cp"
GREP="/usr/bin/grep"
SED="/usr/bin/sed"
NAWK="/usr/bin/nawk"
MKDIR="/usr/bin/mkdir -p"
MV="/usr/bin/mv"
PKGADD="/usr/sbin/pkgadd -S -a ${MODADMINFILE}"
PKGRM="/usr/sbin/pkgrm -n -a ${MODADMINFILE}"
PATCHADD="/usr/sbin/patchadd"
PATCHRM="/usr/sbin/patchrm"
PKGPARAM="/usr/bin/pkgparam"
PKGINFO="/usr/bin/pkginfo"
PKGCHK="/usr/sbin/pkgchk"
PRINT="/usr/sadm/bin/puttext"
PRINTINDENT="/usr/sadm/bin/puttext -l 8"
PRINTONELINE="/usr/bin/echo"
SHOWREV="/usr/bin/showrev"
CKYORN="/usr/bin/ckyorn -p"
CKYORN_NOQUIT="/usr/bin/ckyorn -Q -p"

PKGCMDARGS=""

# Message pool
WRONGBUNDLEMSG="This utility needs to be run in the directory that \
contains the PatchPro packages. Please \
\"cd\" to that directory and try again."

WRONGOSMSG="The PatchPro product will only work on \
SunOS ${TARGETOS} and this system is running SunOS \
$ACTUALOS."

WRONGUSERMSG="You must be root on this system to install this product."

INTROMSG="This utility will install PatchPro and all required support \
software. It is a wrapper around pkgadd and patchadd. \
It will honor your SVR4 install policies \
and will backout all changes if anything goes \
wrong."

SINGLEUSERMSG="Patches may be applied in support of the installation. \
For that reason, this utility should be run on a quiet \
system with no active windowing, preferrably in \
single user mode. If reboot is required, you will \
see a message at the end of the installation."

INTERACTMSG="This installation will preserve critical data files by \
executing a shell script with root permission."

CONTINUEQRY="Would you like to continue with the installation? "

PPROALREADYINSTALLED1="\nThe PatchPro product is already installed. You \
must uninstall the PatchPro product before running this \
setup script. To remove the PatchPro product, run the "

PPROALREADYINSTALLED2="script. Next, rerun this \
setup script to reinstall the PatchPro product.\n"

BEGINNING="Beginning installation ..."
SUSPENDING="Suspending installation. The filesystem has not been \
modified."

UPGRADESTMT="The currently installed version of pkg is older than \
the version now being installed."
UPGRADEQRY="Would you like to upgrade your current installation? "

INSTALLINGPATCHES="Installing required patches..."
INSTALLINGPKGS="Installing supporting packages..."
INSTALLINGPPPKGS="Installing PatchPro package..."
INSTALLINGCFGPKGS="Installing configuration package..."
INSTALLINGSDB="Installing database module..."
INSTALLINGAPCY="Installing policy module..."
REMOVEJAVA="Java2 was installed along with Patchpro. Do you want \
to remove Java2? "

BOGUSJAVAMSG="No Java packages were discovered but your /usr/j2se directory \
is populated. Please delete or move the contents of /usr/j2se \
and try again."

NOTREQUIRED="== not required"

PATCHPROALREADYINSTALLEDMSG="PatchPro already installed."

ALREADYINSTALLEDMSG="== already installed"

UPGRADINGMSG="== upgrading older version"
NEWERINSTALLEDMSG="== installed version is newer"

ALREADYAPPLIEDMSG="== already applied"

OBSOLETEDMSG="== obsoleted by another patch"

PATCHSUCCESS="== applied successfully"

PKGSUCCESS="== installed successfully"

REMOTEDISTMSG="While the PatchPro package is not installed, the \
PatchPPro files appear to be present. These could \
be distributed \
from a remote server. Check with your system administrator \
to determine if this really is the PatchPro package."

BACKOUTMSG="An error was detected. The installation has been \
uninstalled. Your filesystem is restored to its original \
state. See ${LOG} for details."

NOTIFYLOGLOCATIONMSG="NOTE: For error and warning messages, see the log file at ${LOG}."

JAVAVERSIONMSG="The version for the Java 2 packages installed at /usr/j2se \
is: "

VALIDJAVAVERSIONMSG="Java packages installed at /usr/j2se should be 1.3.0 \
or higher"

UNINSTALLPATCHPROERRMSG="Cannot uninstall PatchPro from the current \
directory: "

MISSINGPACKAGEMSG="This package is required: "
APPLYPACKAGEREQUESTMSG="The missing package(s) must be applied before \
PatchPro can be installed."

WHYCONFIGDATAISNEEDEDMSG="Before you can use PatchPro it needs to be \
configured. You will now be asked a few questions to help us configure your \
PatchPro installation."

CONNECTIONMSG="Select the mechanism your system will use to retrieve Sun \
patches. PatchPro 2.2 requires that your system be connected to the \
Internet.\n\n \
\t1. Direct Internet connection.\n\t2. Via a web proxy.\n \
\n\nMechanism [1,2,?,q]: "

QUESTIONMARKEXPLAIN="Select 1 or 2; or enter q to exit."

UNKNOWNCONNECTIONOPTION="Select 1 or 2; or enter q to exit."

PROXYQUESTIONMSG="Enter the name or IP address of the web proxy: "

PROXYEMPTYSTRINGWARNING="The web proxy name or IP address cannot be empty."

PROXYUNKNOWNFORMATWARNING="The web proxy name you entered is not in a \
recognizable format."

PROXYNUMERICSTRINGWARNING="The web proxy name or IP address cannot be numerical."

PROXYPORTQUESTIONMSG="Enter the port number of the web proxy: "

PROXYPORTEMPTYSTRINGWARNING="The web proxy port cannot be empty."

PROXYPORTUNKNOWNFORMATWARNING="The web proxy port you entered is not in a \
recognizable format."

PROXYPORTALPHAWARNING="The web proxy port cannot be alphabetical."

PROXYPORTALPHANUMERICWARNING="The web proxy port cannot be alpha-numerical."

AUTHPROXYQUESTIONMSG="Does the web proxy require authentication? "

AUTHPROXYUSERQUESTIONMSG="Enter the userid for the web proxy: "

AUTHPROXYPASSWDQUESTIONMSG="Enter the password for the web proxy: "

AUTHPROXYPASSWDQUESTIONCONFIRMMSG="Enter the password again: "

CONFIGSUMMARYMSG="You have entered the following configuration data:"

NOCONFIGSUMMARYMSG="No web proxy configuration needed."

PROXYMSG="Web Proxy Server: "

PROXYPORTMSG="Web Proxy Server port: "

AUTHPROXYUSERMSG="Web Proxy user ID: "

AUTHPROXYPASSWDMSG="Web Proxy password: "

AUTHPROXYPASSWDNOTMATCHMSG="The passwords do not match. Try again. "

CONFIGDATACONFIGMSG="Is this information correct? "

UPGRADEPKGSUMMARYMSG="Packages to upgrade: "

UPGRADEWARNINGMSG="The upgrade process will remove these existing packages: "

UPGRADEWARNINGMSG2="An older version of PatchPro product is already \
installed. Use setup -f UPGRADE=true if you want to proceed with \ 
upgrading PatchPro non-interactively."

FORCEUPGRADEWARNINGMSG="This script will now proceed with \
installing/upgrading PatchPro without asking you for configuration \
information. You may need to run \"/opt/SUNWppro/bin/pprosetup\" to \
configure PatchPro before using the product. See \"${PRODDIR}/README\" for \
instructions."

ASKCONTINUEMSG="Do you want to continue? "

RESTARTCIMOMMSG="For PatchPro to take effect, the Solaris \
WBEM Services must be restarted on your system after PatchPro is installed. \
\nDo you want these services restarted at that time? "

RESTARTCIMOMTFMSG="Restart Solaris WBEM Services after PatchPro is \
installed. "

NOTRESTARTCIMOMTFMSG="Do not restart Solaris WBEM Services after PatchPro is \
installed. "

EXITINSTALLMSG="Exiting installation."

# Declare an interrupt handler to catch various signals.
#
trap intrHandler INT HUP KILL TERM

# Re-enable the echo on stty, and do the clean up.
#
intrHandler() {
    stty echo
    exit
}

#
# This forms the upgrade statement
#
function formUpgradeStmt { # $1 is the package
    echo ${UPGRADESTMT%%pkg*} ${1} ${UPGRADESTMT##*pkg}
}

function isSmPackage {                # $1 s the name of the package
    if [ ${1} = ${SMPPKG} ]; then
      return 0
    else
      return 1
    fi
}

#
# This returns 0 if this is the jaxp package, 1 otherwise
#
function isJaxpPackage {	# $1 is the name of the package
    if [ ${1} = ${JAXPPKGS} ]; then
        return 0
    else
    	return 1
    fi
}

#
# This returns 0 if this is a Java package, 1 otherwise
#
function isJavaPackage {        # $1 is the name of the package
    for javapkg in ${JAVAPKGLIST}; do
	if [ ${1} = ${javapkg} ]; then
	    return 0
	fi
    done
    return 1
}

#
# This returns the entry in the package list that matches the 
# specified package base name. Otherwise, returns an empty string.
#
#       $1 is the package basename to search for in a package list
#       $2 is the package list to search

function getPkgInstance {
    for javapkg in $2; do
	if [ ${1%%.*} = ${javapkg} ]; then
            echo ${javapkg}
        fi
    done
    echo ""
}

#
# This takes a Java version string and returns the numbers.
#
function getVersion {	# $1 is the string
    return ${1#*version}
}

#
# This returns 0 if the argument #1 is identical to
# argument #2. 
#
function isIdentical {	# arguments are version strings
    [[ "${1}" = "${2}" ]]
}

#
# This returns 1 if the argument #1 represents a newer release than
# argument #2. 
#
function isNewer {	# arguments are version strings
    first=${1%,REV*}
    if [[ "${first}" = "" ]]; then
	first=${1}
    fi

    second=${2%,REV*}
    if [[ "${second}" = "" ]]; then
	second=${2}
    fi

    return $(/usr/bin/expr ${first} \<= ${second})
}

#
# This prints the newest package instance provided a list of 0 or more
# pkg instances
#
function getlatestpkg { # 1 is a list of pkginst's
    p=""
    vs=""
    for pk in ${1}; do
	nvs=$(${PKGPARAM} ${PKGCMDARGS} ${pk} VERSION)
	if [[ -n ${vs} ]]; then
	    if $(isNewer ${nvs} ${vs}); then
		nvs=${vs}
		p=${pk}
	    fi
	else
	    vs=${nvs}
	    p=${pk}
	fi
    done
    echo ${p}
}

#
# This returns the list of installed package instances of the provided
# package.
#
function getpkginsts { # $1 is the pkg
    l=$(${PKGINFO} ${PKGCMDARGS} ${1}.* 2> /dev/null)
    if [[ -n "${l}" ]]; then
	echo "${l}" | ${NAWK} ' { print $2;  } '
    else
	echo ""
    fi
}

#
# This adds a user interaction for removal. It asks the user if they
# want to remove the version of Java2 installed with PatchPro.
#
function notifyRemoveJava {
    prepend "if [[ "\$response" = "y" || "\$response" = "yes" || "\$response" = "Y" || "\$response" = "Yes" || "\$response" = "YES" ]]; then removejava=1; fi"
    prepend "response=\$(${CKYORN_NOQUIT} \"${REMOVEJAVA}\")"
}

#
# This simply installs a package
#
function installPackage {
    proddir=${1}
    pkg=${2}
    allowuninstall=${3}

    if [ ${2} = ${JAXPPKGS} ]; then
        ${PKGADD} ${PKGCMDARGS} -d ${proddir} ${pkg} >> ${LOG} 2>&1
    else
	${PKGADD} ${PKGCMDARGS} -d ${proddir} ${pkg} >> ${LOG} 2>&1
    fi

    exitcode=$?

    if [[ $exitcode -ne 0 ]]; then
	backoutnexit
    else
	# Obtain the latest package instance and create an uninstall entry
	# for this instance.
	#
	pkginsts=$(getpkginsts "${pkg}")
	pkginst=$(getlatestpkg "${pkginsts}")

	if [[ ${allowuninstall} != "false" ]]; then
	    if isJavaPackage ${pkg}; then
		INCLUDESJAVA=1
		prepend "if [[ \${removejava} -eq 1 ]]; then ${PKGRM} ${PKGCMDARGS} ${pkginst}; fi"
            elif isSmPackage ${pkg}; then
                prepend "${PKGRM} ${PKGCMDARGS} ${pkginst}"
	    else
		prepend "${PKGRM} ${PKGCMDARGS} ${pkginst}"
	    fi
	fi

	${PRINTINDENT} "${PKGSUCCESS}"
    fi
}

#
# This prepends a task to the backout script
#
function prepend { # $1 is the command
    echo $1 > ${REMOVEPATH}.new
    cat ${REMOVEPATH}.new ${REMOVEPATH} > ${REMOVEPATH}.tmp
    rm ${REMOVEPATH}.new
    mv ${REMOVEPATH}.tmp ${REMOVEPATH}
}

#
# This appends a task to the backout script
#
function append { # $1 is the command
    echo $1 > ${REMOVEPATH}.new
    cat ${REMOVEPATH} ${REMOVEPATH}.new > ${REMOVEPATH}.tmp
    rm ${REMOVEPATH}.new
    mv ${REMOVEPATH}.tmp ${REMOVEPATH}
}

#
# Get applied patches and put them into the PATCHLIST
#
function getappliedpatches {
    export APPLIEDPATCHLIST

    ${SHOWREV} ${PKGCMDARGS} -p 2>&1 | grep "Patch: " | while read patchline; do
	PATCHHEAD="${patchline%%Obsoletes*}"
	THISPATCH="${PATCHHEAD##Patch\: }"
	APPLIEDPATCHLIST="$APPLIEDPATCHLIST ${THISPATCH}"
    done
}

#
# This checks for installed versions of the provided package and decides what
# should be done about it.
#
function packagestatus { # $1 is the package instance
			 # $2 is to specify if it should interactively ask
			 #    whether upgrade is needed. If $2 is false,
			 #    UPGRADETHIS will be set to the latest package
			 #    instance available on the system.
    INSTALLPKG="false"
    ALREADYINSTALLED="false"
    UPGRADETHIS=""
    pkg=${1}
    pkginsts=$(getpkginsts ${pkg})

    ask="true"
    if [[ -n ${2} ]]; then
	ask=${2}
    fi

    if [[ -z ${pkginsts} ]]; then
	# It isn't installed, so go ahead
	INSTALLPKG="true"
    else
 	# There's already one installed
	pkginst=$(getlatestpkg "${pkginsts}")
	version=$(${PKGPARAM} ${PKGCMDARGS} ${pkginst} VERSION)
	installedversion=${version%%,REV=*}

	version=$(${PKGPARAM} ${PKGCMDARGS} -d ${PRODDIR} ${pkg} VERSION)
	ourversion=${version%%,REV=*}

	if $(isIdentical ${installedversion} ${ourversion}); then
	    ALREADYINSTALLED="true"
	elif $(isNewer ${installedversion} ${ourversion}); then
	    ALREADYINSTALLED="true"
	else
	    if [ "$ask" = "true" ]; then
		echo
		${PRINT} "$(formUpgradeStmt ${pkg})"
		response=$(${CKYORN} "${UPGRADEQRY}")

		if [[ "$response" = "y" ||
		    "$response" = "yes" ||
		    "$response" = "Y" ||
		    "$response" = "Yes" ||
		    "$response" = "YES" ]]; then
		    INSTALLPKG="true"
		    UPGRADETHIS="${pkginst}"
		fi
	    else
		INSTALLPKG="true"
		UPGRADETHIS="${pkginst}"
	    fi
	fi
    fi
}

#
# This returns 0 if the provided patch is not applied.
#
function patchnotapplied { # $1 is the patch ID
    NewPatch=$1
    NewBasecode=${NewPatch%%-*}
    NewVersion=${NewPatch##*-}

    # If the system has no patch applied, for sure we know that the 
    # input patch has not been applied.
    #
    if [ "$APPLIEDPATCHLIST" = " No patches are installed" ]; then
        return 0
    fi

    for appliedpatch in $APPLIEDPATCHLIST; do
	appliedbasecode=${appliedpatch%%-*}
	appliedversion=${appliedpatch##*-}

	if [[ $appliedbasecode -eq $NewBasecode ]]; then
	    if [[ $appliedversion -ge $NewVersion ]]; then
		return 1
	    fi
	fi
    done

    return 0
}

#
# This function backs out all changes and exits the installation
#
function backoutnexit {
    echo "Error detected."
    echo "Uninstalling PatchPro..."
    prepend "removejava=1"
    /bin/ksh ${REMOVEPATH}

    ${PRINT} "${BACKOUTMSG}"
    exit 0
}

#
# Ignores the revision information and only returns the version identifier from the
# package version information provided by the pkgparam command.
#
function getVersionID {      # argument is a version string <version_id,REV=...>
    versionID=${1%,REV*}
    if [[ "${versionID}" = "" ]]; then
        versionID=${1}
    fi

    echo ${versionID}
}

#
# Usage message.
#
function usage_msg {
	echo "usage : "

	echo "setup [-f] [-R root_path] [-a admin_file]"

	exit 1
}

#
# Display which packages are not installed. If any of the expected
# packages are not installed, terminate ...
#
function verifyPackagesInstalled { # $1 is a list of required packages
    Terminate="false"

    for pkg in $1; do
	${PKGINFO} -q ${pkg}

	if [[ $? -ne 0 ]]; then
	    ${PRINT} "${MISSINGPACKAGEMSG} ${pkg}"
	    Terminate="true"
	fi
    done

    if [ ${Terminate} = "true" ]; then
	echo
	${PRINT} "${APPLYPACKAGEREQUESTMSG}"
	exit 1
    fi
}

#
# Gathering configuration data and checking the consistency of the input
# data.
#
function gather_config_data {
    while :; do

	${PRINT} ""
	${PRINT} -n "${CONNECTIONMSG}"
	read -u0 connection_option
	# Treat CR as an invalid option.
	#
	connection_option=${connection_option:-0}
	case "$connection_option" in
	q*|Q*)
	    ${PRINT} ""
	    exit 1
	    ;;
	1)
	    proxy=""
	    proxy_port=""
	    proxy_user=""
	    proxy_passwd=""
	    break
	    ;;
	2)
	    # Prompt user to enter the name of the web proxy server.
	    # We will check the input data and make sure that the format is
	    # correct.
	    # We will keep looping and asking the user to enter the correct
	    # data if we found that the data input is incorrect.
	    #
	    looping_done=0
	    while [ $looping_done != 1 ]
	    do
		if [ "$proxy" = "TBD" ]; then
		# If this is the first time the user tells us what the proxy
		# server is.
		#
		    ${PRINTONELINE} "${PROXYQUESTIONMSG}\c"
		    read -u0 tmp_proxy
		else
		# If the user has already entered a proxy name previously.
		#
		    ${PRINTONELINE} "${PROXYQUESTIONMSG} [$proxy] \c "
		    read -u0
		    if [ x"$REPLY" != x ]; then
			tmp_proxy="$REPLY"
		    else
			tmp_proxy="$proxy"
		    fi
		fi

		# Check to see if the proxy server name specified by the user
		# has the correct format. If it is correct, the variable $proxy
		# will be populated with the input value, and looping_done will
		# be set to 1 to end the looping.
		#
		check_string_type $tmp_proxy
		string_type=$?
		if [[ $string_type -eq 1 ]]; then
		    ${PRINT} "${PROXYEMPTYSTRINGWARNING}"
		    looping_done=0
		elif [[ $string_type -eq 2 ]]; then
		    ${PRINT} "${PROXYUNKNOWNFORMATWARNING}"
		    looping_done=0
		elif [[ $string_type -eq 3 ]]; then
		    proxy="$tmp_proxy"
		    looping_done=1
		elif [[ $string_type -eq 4 ]]; then
		    proxy="$tmp_proxy"
		    looping_done=1
		elif [[ $string_type -eq 5 ]]; then
		    ${PRINT} "${PROXYNUMERICSTRINGWARNING}"
		    looping_done=0
		fi
	    done

	    # Prompt user to enter the name of the web proxy port.
	    # We will check the input data and make sure that the format is
	    # correct.
	    # We will keep looping and asking the user to enter the correct
	    # data if we found that the data input is incorrect.
	    #
	    looping_done=0
	    while [ $looping_done != 1 ]
	    do
		if [ "$proxy_port" = "TBD" ]; then
		# If this is the first time the user tells us what the proxy
		# port is.
		#
		    ${PRINTONELINE} "${PROXYPORTQUESTIONMSG}\c"
		    read -u0 tmp_proxy_port
		else
		# If the user has already entered a proxy port previously.
		#
		    ${PRINTONELINE} "${PROXYPORTQUESTIONMSG} [$proxy_port] \c "
		    read -u0
		    if [ x"$REPLY" != x ]; then
			tmp_proxy_port="$REPLY"
		    else
			tmp_proxy_port="$proxy_port"
		    fi
		fi

		# Check to see if the proxy server port specified by the user
		# has the correct format. If it is correct, the variable 
		# $proxy_port will be populated with the input value, and 
		# looping_done will be set to 1 to end the looping.
		#
		check_string_type $tmp_proxy_port
		string_type=$?
		if [[ $string_type -eq 1 ]]; then
		    ${PRINT} "${PROXYPORTEMPTYSTRINGWARNING}"
		    looping_done=0
		elif [[ $string_type -eq 2 ]]; then
		    ${PRINT} "${PROXYPORTUNKNOWNFORMATWARNING}"
		    looping_done=0
		elif [[ $string_type -eq 3 ]]; then
		    ${PRINT} "${PROXYPORTALPHAWARNING}"
		    looping_done=0
		elif [[ $string_type -eq 4 ]]; then
		    ${PRINT} "${PROXYPORTALPHANUMERICWARNING}"
		    looping_done=0
		elif [[ $string_type -eq 5 ]]; then
		    proxy_port="$tmp_proxy_port"
		    looping_done=1
		fi
	    done

	    config_response=$(${CKYORN_NOQUIT} "${AUTHPROXYQUESTIONMSG}")
	    if [[ "$config_response" = "y" ||
		"$config_response" = "yes" ||
		"$config_response" = "Y" ||
		"$config_response" = "Yes" ||
		"$config_response" = "YES" ]]; then

		if [ "$proxy_user" = "TBD" ]; then
		    ${PRINTONELINE} "${AUTHPROXYUSERQUESTIONMSG}\c"
		    read -u0 proxy_user
		else
		    ${PRINTONELINE} \
			"${AUTHPROXYUSERQUESTIONMSG} [$proxy_user] \c "
		    read -u0
		    if [ x"$REPLY" != x ]; then
			proxy_user="$REPLY"
		    fi
		fi

		# Prompt user to enter the name of the web proxy password.
		# We will prompt the user twice to reconfirm the entered 
		# password. We will keep looping and asking the user to 
		# enter the password again if the two passwords do not
		# match.
		#
		looping_done=0
		while [ $looping_done != 1 ]
		do
		    ${PRINTONELINE} "${AUTHPROXYPASSWDQUESTIONMSG}\c"
		    stty -echo
		    read -u0 tmp_proxy_passwd_1
		    stty echo
		    ${PRINT} ""
		    ${PRINTONELINE} "${AUTHPROXYPASSWDQUESTIONCONFIRMMSG}\c"
		    stty -echo
		    read -u0 tmp_proxy_passwd_2
		    stty echo

		    # Check to see if the two passwords match. If so, the
		    # variable $proxy_passwd will be populated with the input
		    # value, and the looping_done will be set to 1 to end the
		    # looping.
		    #
		    if [ "$tmp_proxy_passwd_1" = "$tmp_proxy_passwd_2" ]; then
			looping_done=1
			proxy_passwd="$tmp_proxy_passwd_1"
		    else
			${PRINT} "${AUTHPROXYPASSWDNOTMATCHMSG}"
			looping_done=0
		    fi
		done
	    else
		proxy_user=""
		proxy_passwd=""
	    fi
	    break
	    ;;
	"?")
	    ${PRINTINDENT} "${QUESTIONMARKEXPLAIN}"
	    ${PRINT} ""
	    ;;
	*)
	    ${PRINTINDENT} "${UNKNOWNCONNECTIONOPTION}"
	    ${PRINT} ""
	    ;;
	esac
    done

    # Check if we are running on S9 or above. If so, ask if the user wants
    # to restart CIMOM (Bug 4888779).
    if (( $SOLARISVERSION >= "9")); then
	restart_cimom_response=$(${CKYORN_NOQUIT} "${RESTARTCIMOMMSG}")
    	if [[ "$restart_cimom_response" == "y" || \
		"$restart_cimom_response" == "yes" || \
		"$restart_cimom_response" == "Y" || \
		"$restart_cimom_response" == "Yes" || \
		"$restart_cimom_response" == "YES" ]]; then
		restart_cimom="true"
	else
		restart_cimom="false"
	fi
    fi
}

function print_config_data_summary {
    ${PRINT} ""
    if [ "${proxy}" != "TBD" ] && [ ! -z ${proxy} ]; then
	${PRINT} "${CONFIGSUMMARYMSG}"
        ${PRINT} ""
	${PRINTINDENT} "${PROXYMSG} $proxy"
	${PRINTINDENT} "${PROXYPORTMSG} $proxy_port"
	if [ "$proxy_user" != "TBD" ]; then
		${PRINTINDENT} "${AUTHPROXYUSERMSG} $proxy_user"
	fi
	${PRINT} ""
    else
	${PRINTINDENT} "${NOCONFIGSUMMARYMSG}"
	${PRINT} ""
    fi

    if (( $SOLARISVERSION >= "9")); then
	if [ "${restart_cimom}" = "true" ]; then
		${PRINTINDENT} "${RESTARTCIMOMTFMSG}"
	else
		${PRINTINDENT} "${NOTRESTARTCIMOMTFMSG}"
	fi
	${PRINT} ""
    fi
}

# This function determines the input string type. It returns:
# 
# 1: Empty string
# 2: Unknown string type
# 3: Alphabetical string type
# 4: Alpha-numeric string type
# 5: Numeric string type
#
function check_string_type { # $1 the input string
    input_string=${1}
    string_type=2 # unknown string type
    if [[ "$input_string" == "" ]]; then
	string_type=1 # Empty string
	return $string_type
    fi

#    echo $input_string | $GREP -v "[a-zA-Z0-9]" > /dev/null
#    if [[ $? -eq 1 ]]; then
#	string_type=2 # Unknown string
#	return $string_type
#    fi

    echo "$input_string" | $GREP "[a-zA-Z.]" > /dev/null
    if [[ $? -eq 0 ]]; then
	echo "$input_string" | $GREP "[0-9]" > /dev/null
	if [[ $? -eq 0 ]]; then
	    string_type=4 # alpha-numeric string type
	else 
	    string_type=3 # alphabetical string type
	fi
    else
	echo "$input_string" | $GREP "[0-9]" > /dev/null
	if [[ $? -eq 0 ]]; then
	    string_type=5 # numeric string type
	fi
    fi

    return $string_type
}
    
#
# To determine if we are handling initial install or an upgrade.
#
function analyze_install_action { # $1 to indicate if it is interactive
				  #   install ("true" = yes, "false" = no)
				  # $2 to indicate if upgrade is OK
				  #   ("true" = yes, "false" = no)
    interactive_install="true"
    if [[ -n ${1} ]]; then
	interactive_install=${1}
    fi

    upgrade_ok="false"
    if [[ -n ${2} ]]; then
	upgrade_ok=${2}
    fi

    # Initialize the temporary variables.
    #
    patchpropkg_action=""
    UPDATED_SUPRTPKGLIST=""
    PKGS_TO_UPGRADE=""

    ALREADYINSTALLED="false"
    UPGRADETHIS=""
    INSTALLPKG="false"
    if [ ${interactive_install} == "true" ]; then
	packagestatus $PATCHPROPKG "true"
    else
	packagestatus $PATCHPROPKG "false"
    fi

    if [ "$ALREADYINSTALLED" == "true" ]; then
	${PRINT} "${PATCHPROALREADYINSTALLEDMSG}"
	exit 0;
    elif [ "$ALREADYINSTALLED" != true -a "$UPGRADETHIS" == "$PATCHPROPKG" ]; 
    then
	# Backing up the existing configuration file
	BASEDIR=$(${PKGPARAM} ${PKGCMDARGS} SUNWppro BASEDIR)
	CONFIGFILE="${BASEDIR}/etc/patchpro.conf"
	cp ${CONFIGFILE} ${BAK_CONFIGFILE}
	patchpropkg_action="upgrade"
	PKGS_TO_UPGRADE="$PATCHPROPKG"
    elif [ "$ALREADYINSTALLED" != true -a \
	"$UPGRADETHIS" == "" -a "$INSTALLPKG" == "true" ]; then
    
	# If SUNWppro has never been installed before.
	#
	patchpropkg_action="install"
	PKGS_TO_UPGRADE="$PATCHPROPKG"
    elif [ "$ALREADYINSTALLED" != true -a "$UPGRADETHIS" == "" ]; then
	# If the user does not want to upgrade.
	#
	${PRINT} ""
	${PRINT} "${SUSPENDING}"
	exit 0
    fi
    
    for pkg in ${SUPRTPKGLIST}; do

	# Initialize the temporary variables...
	#
	ALREADYINSTALLED="false"
	UPGRADETHIS=""
	INSTALLPKG="false"

	if [ ${interactive_install} == "true" ]; then
	    packagestatus ${pkg} "true"
	else
	    packagestatus ${pkg} "false"
	fi

	if [ "$ALREADYINSTALLED" != "true" -a "$UPGRADETHIS" == "$pkg" ]; 
	then  
	    UPDATED_SUPRTPKGLIST="$UPDATED_SUPRTPKGLIST $pkg"
	elif [ "$ALREADYINSTALLED" != true -a \
	    "$UPGRADETHIS" == "" -a "$INSTALLPKG" == "true" ]; then
	    UPDATED_SUPRTPKGLIST="$UPDATED_SUPRTPKGLIST $pkg"
	elif [ "$ALREADYINSTALLED" != true -a "$UPGRADETHIS" == "" ]; then
	    # To fix bug 4874316.
	    # If the user does not want to upgrade, we terminate the script.
	    #
	    ${PRINT} ""
	    ${PRINT} "${SUSPENDING}"
	    exit 0
	fi
    done
    
    if [ $patchpropkg_action = "upgrade" ]; then
	if [ ${interactive_install} == "true" ]; then
	    ${PRINT} "${UPGRADEWARNINGMSG} $PKGS_TO_UPGRADE \
		${UPDATED_SUPRTPKGLIST}"
	    confirm_response=$(${CKYORN} "${ASKCONTINUEMSG}")
	    if [ $confirm_response != "y" -a \
		$confirm_response != "yes" -a \
		$confirm_response != "Y" -a \
		$confirm_response != "Yes" -a \
		$confirm_response != "YES" ]; then

		${PRINT} "${EXITINSTALLMSG}"
		exit 1
	    fi
	else
	    if [ ${upgrade_ok} != "true" ]; then
		${PRINT} "${UPGRADEWARNINGMSG2}"
		${PRINT} "${EXITINSTALLMSG}"
		exit 1
	    fi
	fi
    fi
}

#
# main
#
# First check that the user is root
#

# Initialize the Configuration data
proxy="TBD"
proxy_port="TBD"
proxy_user="TBD"
proxy_passwd="TBD"
restart_cimom="false"
SOLARISVERSION=`echo $(uname -r) | awk -F. '{print $2}'`

typeset -i uid
uid=$(id | ${SED} 's/uid=\([0-9]*\)(.*/\1/')
if (( uid != 0 )); then
    ${PRINT} "${WRONGUSERMSG}"
    exit 1
fi

if [ ${SETUPDIRECTORY} = "." ]; then
    PRODDIR=`pwd`
fi

if (( $SOLARISVERSION == "6" )); then
    verifyPackagesInstalled "${REQS6PKGLIST}"
elif (( $SOLARISVERSION >= "7")); then
    verifyPackagesInstalled "${REQPKGLIST}"
fi

Force="false"
UpgradeOK="false"
PKG_INSTALL_ROOT=""

for i in $*; do
	case $i in
	-f)	Force="true";
		if [[ -n ${2} ]]; then
		    if [[ "${2}" == "UPGRADE=true" ]]; then
			UpgradeOK="true"
		    fi
		fi
		shift;;
	-R)     if [[ -n ${2} ]]; then
		    PKG_INSTALL_ROOT=$2; 
		else
		    usage_msg
		fi
		shift;;
	-a)	if [[ -n ${2} ]]; then
		    Admin=$2;
		else
		    usage_msg
		fi
		shift;;
	-*)	usage_msg; exit 2;;
	esac
done

if [ -n "${PKG_INSTALL_ROOT}" ]; then
    PKGCMDARGS="-R ${PKG_INSTALL_ROOT}"
fi

ADMINFILE=/var/sadm/install/admin/${Admin:-default}

#
# Determine if Java 2 has already been installed under /usr/j2se. 
# If Java 2 has been installed, determine if its package version is 1.3.0. 
# Version 1.3.0 requires SUNWjsse. Version 1.3.0+ requires nothing additional. 
# If Java 2 has not been installed, then install the basic Java packages 
#	(SUNWj3rt, SUNWlj3rt and SUNWWj3dev), 
# and Java Secure Socket Extension package (SUNWjsse) as needed. 
#
j2sepkglist=$(${PKGCHK} ${PKGCMDARGS} -lp /usr/j2se | nawk /SUNW/ 2> /dev/null)

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

    pkginst=$(getPkgInstance "SUNWj3rt" "${j2sepkglist}")

    if [[ -n "${pkginst}" ]]; then
	#   Verify that it is 1.3 or higher
	jdkver=$(${PKGPARAM} ${PKGCMDARGS} ${pkginst} VERSION)
	pkgver=$(getVersionID "${jdkver}")

	if [[ ${pkgver} = "1.3.0" || (${pkgver} > "1.3.0" && ${pkgver} < "1.4.0") ]]; then
	    SUPRTPKGLIST="${JREJSPKGS} SUNWsdb SUNWapcy SUNWppmn ${SMPPKG}"
	elif [[ ${pkgver} = "1.4.0" || ${pkgver} > "1.4.0" ]]; then
	    SUPRTPKGLIST="SUNWsdb SUNWapcy SUNWppmn ${SMPPKG}"
	else
	#   Unexpected version of Java detected. This should not happen. 
	#   But if it does, we are covered.
	    ${PRINT} "${JAVAVERSIONMSG} ${pkgver}"
	    ${PRINT} "${VALIDJAVAVERSIONMSG}"
	    exit 1
	fi

    else
	#   SUNWj3rt not found: Install our j2se
	SUPRTPKGLIST="${JAVAPKGLIST} SUNWsdb SUNWapcy SUNWppmn ${SMPPKG}"

	# Now check for a completely bogus yet possibly usable copy of Java
	if [ -h ${PKG_INSTALL_ROOT}/usr/j2se/bin/java -o \
	     -f ${PKG_INSTALL_ROOT}/usr/j2se/bin/java ]; then
	    ${PRINT} "${BOGUSJAVAMSG}"
	    exit 1
	fi
    fi
else
    #   No Java packages were found: Install our j2se
    SUPRTPKGLIST="${JAVAPKGLIST} SUNWsdb SUNWapcy SUNWppmn ${SMPPKG}"

	# Now check for a completely bogus yet possibly usable copy of Java
	if [ -h ${PKG_INSTALL_ROOT}/usr/j2se/bin/java -o \
	     -f ${PKG_INSTALL_ROOT}/usr/j2se/bin/java ]; then
	    ${PRINT} "${BOGUSJAVAMSG}"
	    exit 1
	fi
fi

# Determine the OS level of the target. If its 5.6, 5.7 or 5.8, then check
# under /usr/share to see if the SUNWjaxp package is installed. If not install
# it.

# Check the OS level. If the OS level is not higher than 5.8, then install.
if (( $SOLARISVERSION <= "8" )); then
  # Determine if SUNWjaxp has already been installed under /usr/share
  # Get the list of SUNWjaxp packages.
  jaxppkglist=$(${PKGCHK} ${PKGCMDARGS} -lp /usr/share | nawk /SUNWjaxp/ 2> /dev/null)
  #Get the SUNWjaxp package from the list.
  pkginst=$(getPkgInstance "SUNWjaxp" "${jaxppkglist}")
    
  # if SUNWjaxp is installed, then don't install it.(You don't need to check
  # the version.)
  if [[ ! -n "${pkginst}" ]]; then
    # SUNWcsl is a required package for SUNWjaxp but it is not present in
    # a standard 5.6 installation. For now we do not install SUNWjaxp on
    # 5.6 system.
    if (( $SOLARISVERSION > "6")); then
	# SUNWjaxp is not installed. So add the SUNWjaxp to the list of 
	# support packages - SUPRTPKGLIST to be installed.
	SUPRTPKGLIST="${SUPRTPKGLIST} SUNWjaxp"
    fi
  fi
fi

#
# .. then make sure we are in the appropriate directory
#
for pkg in $SUPRTPKGLIST $PKGLIST; do
    if [[ ! -d ${SETUPDIRECTORY}/SUNWppro ]]; then
	${PRINT} "${WRONGBUNDLEMSG}"
	exit 1
    fi
done

#
# ... and that this is the right target
#
if [ ${Force} = "false" ]; then
    TARGETOS="5.9"
    ACTUALOS=$(nawk -F \= '/VERSION/ { n=index($2, ".");
	if (n == 0) {
	    printf("5.%s", $2);
	} else {
	    printf("5%s", substr($2, n));
	};
    } ' < ${PKG_INSTALL_ROOT:}/var/sadm/softinfo/INST_RELEASE)

    ACTUALARCH=$(uname -p)
    OSMATCH="false"

    for os in ${TARGETOS}; do
	if [[ "$os" == "$ACTUALOS" ]]; then
	    OSMATCH="true"
	    break;
	fi
    done

    if [[ "$OSMATCH" == "false" ]]; then
	${PRINT} "This Product will not run on \
		SunOS $ACTUALOS."
	exit 1
    fi


    # Tell the user what's happening
    echo
    echo
    ${PRINT} "${INTROMSG}"
    echo
    ${PRINT} "${SINGLEUSERMSG}"
    echo
    ${PRINT} "${INTERACTMSG}"

    continue_response=$(${CKYORN} "${CONTINUEQRY}")
    if [ $continue_response != "y" -a \
	 $continue_response != "yes" -a \
	 $continue_response != "Y" -a \
	 $continue_response != "Yes" -a \
	 $continue_response != "YES" ]; then
	exit 1
    fi

    ${PRINT} ""
    ${PRINT} "${NOTIFYLOGLOCATIONMSG}"

    ALREADYINSTALLED=""
    packagestatus $PATCHPROPKG "false"
    if [ "$ALREADYINSTALLED" == "true" ]; then
        ${PRINT} "${PATCHPROALREADYINSTALLEDMSG}"
        exit 1;
    fi

    # Prompt user for required configuration data.
    ${PRINT} ""
    ${PRINT} "${WHYCONFIGDATAISNEEDEDMSG}"
    
    gather_config_data;
    print_config_data_summary;

    config_response=$(${CKYORN_NOQUIT} "${CONFIGDATACONFIGMSG}")
    if [[ "$config_response" == "q" || \
	 "$config_response" == "Q" || \
	 "$config_response" == "quit" || \
	 "$config_response" == "Quit" || \
	 "$config_response" == "QUIT" ]]; then
	 exit 1
    fi

    while [ $config_response != "y" -a \
	 $config_response != "yes" -a \
	 $config_response != "Y" -a \
	 $config_response != "Yes" -a \
	 $config_response != "YES" ]
    do

	if [[ "$config_response" == "q" || \
	    "$config_response" == "Q" || \
	    "$config_response" == "quit" || \
	    "$config_response" == "Quit" || \
	    "$config_response" == "QUIT" ]]; then
	    exit 1
	fi

	gather_config_data;
	print_config_data_summary;
	config_response=$(${CKYORN_NOQUIT} "${CONFIGDATACONFIGMSG}")
    done
else
    ALREADYINSTALLED=""
    packagestatus $PATCHPROPKG "false"
    if [ "$ALREADYINSTALLED" == "true" ]; then
        ${PRINT} "${PATCHPROALREADYINSTALLEDMSG}"
        exit 1;
    fi

    ${PRINT} ""
    ${PRINT} "$FORCEUPGRADEWARNINGMSG"
    ${PRINT} ""
    continue_response="y"
fi

#
# To determine if we are handling initial install or an upgrade.
#
patchpropkg_action=""
UPDATED_SUPRTPKGLIST=""
PKGS_TO_UPGRADE=""
if [ ${Force} == "false" ]; then
    analyze_install_action "true" "$UpgradeOK"
else
    analyze_install_action "false" "$UpgradeOK"
fi

rebootrequired="false"

if [[ "$continue_response" = "y" ||
	"$continue_response" = "yes" ||
	"$continue_response" = "Y" ||
	"$continue_response" = "Yes" ||
	"$continue_response" = "YES" ]]; then
    #
    # Add the users permission to execute the procedure scripts to
    # the default admin file.
    #
    sed -n '/action/i\
action\=nocheck
	/action/D
	p' < ${ADMINFILE} > ${MODADMINFILE}

${CP} ${MODADMINFILE} ${MODADMINFILETMP}    

    sed -n '/conflict/i\
conflict\=nocheck
	/conflict/D
	p' < ${MODADMINFILETMP} > ${MODADMINFILE}

${CP} ${MODADMINFILE} ${MODADMINFILETMP}    

    sed -n '/space/i\
space\=quit
	/space/D
	p' < ${MODADMINFILETMP} > ${MODADMINFILE}

    if (( $SOLARISVERSION >= "9")); then
	${CP} ${MODADMINFILE} ${MODADMINFILETMP}    
	sed -n '/instance/i\
instance\=overwrite
	/instance/D
	p' < ${MODADMINFILETMP} > ${MODADMINFILE}
    fi

    echo

    ${PRINT} "${BEGINNING}"

    rm ${MODADMINFILETMP}
else
    ${PRINT} "${SUSPENDING}"
    exit 0
fi

getappliedpatches

# Set up the uninstall file.
cd /var/tmp
if [[ -f ${REMOVEPATH} ]]; then
    rm ${REMOVEPATH}
fi
touch ${REMOVEPATH}
prepend "rm ${MODADMINFILE}"

#
# Install the support package if ours is newer
#
${PRINT} ""
${PRINT} "${INSTALLINGPKGS}"

# Create the base directories for SUNWapcy, SUNWsdb and SUNWppro first
# before installing them.
#
${MKDIR} ${SUNW_APCY_BASE_DIR}
${MKDIR} ${SUNW_SDB_BASE_DIR}
${MKDIR} ${SUNW_PPRO_BASE_DIR}

PKGINSTS_TO_REMOVE=""
for pkg in ${UPDATED_SUPRTPKGLIST}; do
    ${PRINTINDENT} "$pkg"

    if [ $pkg == ${JREJSPKGS} ]; then
	    # Create the base directory for SUNWjsse first before installing
	    # it.
	    ${MKDIR} ${SUNW_JSSE_BASE_DIR}
    fi

    pkginsts=$(getpkginsts ${pkg})
    if [[ -z ${pkginsts} ]]; then 
	# This package is not installed yet.
	installPackage ${PRODDIR} ${pkg} "true"
    else
	# A package of this name is already installed.

	# Get the package instance
	suppkginsts=$(getpkginsts ${pkg})
	suppkginst=$(getlatestpkg ${pkginsts})

	ourversion=$(${PKGPARAM} ${PKGCMDARGS} -d ${PRODDIR} ${pkg} VERSION)
	installedversion=$(${PKGPARAM} ${PKGCMDARGS} ${suppkginst} VERSION)
	if $(isIdentical ${installedversion} ${ourversion}); then
	    ${PRINTINDENT} "${ALREADYINSTALLEDMSG}"
	else
	    if $(isNewer ${installedversion} ${ourversion}); then
		${PRINTINDENT} "${NEWERINSTALLEDMSG}"
	    else
		${PRINTINDENT} "${UPGRADINGMSG}"
		installPackage ${PRODDIR} ${pkg} "true"
		PKGINSTS_TO_REMOVE="${suppkginst} ${PKGINSTS_TO_REMOVE}"
	    fi
	fi
    fi
done

# Now install the patches.
if [[ -n "${PATCHLIST}" ]]; then
    ${PRINT} ""
    ${PRINT} "${INSTALLINGPATCHES}"

    for patch in ${PATCHLIST}; do
	${PRINTINDENT} "$patch"

	if patchnotapplied $patch; then
	    zcat $PRODDIR/$patch.tar.Z | tar xvf - > /dev/null 2>&1
	    ${PATCHADD} $patch >> ${LOG}

	    exitcode=$?

	    if [[ $exitcode -ne 0 ]]; then
		if [[ $exitcode -eq 8 ]]; then
		    ${PRINTINDENT} "${NOTREQUIRED}"
		elif [[ $exitcode -eq 6 ]]; then
		    ${PRINTINDENT} "${OBSOLETEDMSG}"
		elif [[ $exitcode -eq 2 ]]; then
		    ${PRINTINDENT} "${ALREADYAPPLIEDMSG}"
		else
		    rm -rf $patch
		    backoutnexit
		fi
	    else
		rebootrequired="true"
		prepend "if [[ \${removejava} -eq 1 ]]; then ${PATCHRM} $patch; fi"
		${PRINTINDENT} "${PATCHSUCCESS}"
	    fi

	    rm -rf $patch
	else
	    ${PRINTINDENT} "${ALREADYAPPLIEDMSG}"
	fi
    done
fi

status=0

# Now install SUNWppro
#
${PRINT} ""
${PRINT} "${INSTALLINGPPPKGS}"
${PRINTINDENT} "${PATCHPROPKG}"
pkginsts=$(getpkginsts SUNWppmn)
pkginst=$(getlatestpkg "${pkginsts}")
BASEDIR=$(${PKGPARAM} ${PKGCMDARGS} $pkginst BASEDIR)
rm -rf ${BASEDIR}/lib/cache/patchprodb.zip
rm -rf ${BASEDIR}/lib/cache/pprodetectors.jar

pkginsts=$(getpkginsts "$PATCHPROPKG")
pkginst=$(getlatestpkg "${pkginsts}")
${PKGADD} ${PKGCMDARGS} -d ${PRODDIR} $PATCHPROPKG >> ${LOG} 2>&1
status=$?
if [[ ${status} -ne 0 ]]; then
	backoutnexit
else
    PKGINSTS_TO_REMOVE="${pkginst} ${PKGINSTS_TO_REMOVE}"

    BASEDIR=$(${PKGPARAM} ${PKGCMDARGS} SUNWppro BASEDIR)
    # If there's a root directory, we need to adjust BASEDIR
    if [ -n PKG_INSTALL_DIR ]; then
        BASEDIR=${PKG_INSTALL_DIR}${BASEDIR}
    fi

    CONFIGFILE="${BASEDIR}/etc/patchpro.conf"
    FINALREMOVEPATH="${BASEDIR}/bin/${BACKOUTSCRIPT}"

    pp_pkginsts=$(getpkginsts $PATCHPROPKG)
    pp_pkginst=$(getlatestpkg "${pp_pkginsts}")

    prepend "${PKGRM} ${PKGCMDARGS} ${pp_pkginst}"
	
    ${PRINTINDENT} "${PKGSUCCESS}"
fi

# Install the configuration package(s)
#
${PRINT} ""
${PRINT} "${INSTALLINGCFGPKGS}"

for pkg in ${CFGPKGLIST}; do
    ${PRINTINDENT} "$pkg"

    pkginsts=$(getpkginsts ${pkg})
    if [[ -z ${pkginsts} ]]; then 
	# This package is not installed yet.
	installPackage ${PRODDIR} ${pkg} "true"
    else
	# A package of this name is already installed.

	# Get the package instance
	suppkginsts=$(getpkginsts ${pkg})
	suppkginst=$(getlatestpkg ${pkginsts})

	ourversion=$(${PKGPARAM} ${PKGCMDARGS} -d ${PRODDIR} ${pkg} VERSION)
	installedversion=$(${PKGPARAM} ${PKGCMDARGS} ${suppkginst} VERSION)
	if $(isIdentical ${installedversion} ${ourversion}); then
	    ${PRINTINDENT} "${ALREADYINSTALLEDMSG}"
	else
	    if $(isNewer ${installedversion} ${ourversion}); then
		${PRINTINDENT} "${NEWERINSTALLEDMSG}"
	    else
		${PRINTINDENT} "${UPGRADINGMSG}"
		installPackage ${PRODDIR} ${pkg} "true"
	    fi
	fi
    fi
done

#
# Back up any previous uninstall script
#
if [[ -f ${FINALREMOVEPATH} ]]; then
    mv ${FINALREMOVEPATH} ${FINALREMOVEPATH}.$(date +%m-%d-%T)
fi

# The merging code is here.
#
if [[ $patchpropkg_action == "upgrade" ]]; then
    patchpro_log_file_to_replace=`egrep patchpro.log.file ${CONFIGFILE}`
    patchpro_log_file_to_retain=`egrep patchpro.log.file ${BAK_CONFIGFILE}`
    ${SED} 's:${patchpro_log_file_to_replace}:${patchpro_log_file_to_retain}:g' ${CONFIGFILE} > ${CONFIGFILE}.new.$$ || backoutnexit >> ${LOG} 2>&1
    ${MV} ${CONFIGFILE}.new.$$ ${CONFIGFILE}

    patchpro_log_size_to_replace=`egrep patchpro.log.size ${CONFIGFILE}`
    patchpro_log_size_to_retain=`egrep patchpro.log.size ${BAK_CONFIGFILE}`
    ${SED} 's:${patchpro_log_size_to_replace}:${patchpro_log_size_to_retain}:g' ${CONFIGFILE} > ${CONFIGFILE}.new.$$ || backoutnexit
    ${MV} ${CONFIGFILE}.new.$$ ${CONFIGFILE}

    patchpro_log_level_to_replace=`egrep patchpro.log.level ${CONFIGFILE}`
    patchpro_log_level_to_retain=`egrep patchpro.log.level ${BAK_CONFIGFILE}`
    ${SED} 's:${patchpro_log_level_to_replace}:${patchpro_log_level_to_retain}:g' ${CONFIGFILE} > ${CONFIGFILE}.new.$$ || backoutnexit >> ${LOG} 2>&1
    ${MV} ${CONFIGFILE}.new.$$ ${CONFIGFILE}

    patchpro_patch_download_directory_to_replace=`egrep patchpro.patch.download.directory ${CONFIGFILE}`
    patchpro_patch_download_directory_to_retain=`egrep patchpro.patch.download.directory ${BAK_CONFIGFILE}`
    ${SED} 's:${patchpro_patch_download_directory_to_replace}:${patchpro_patch_download_directory_to_retain}:g' ${CONFIGFILE} > ${CONFIGFILE}.new.$$ || backoutnexit >> ${LOG} 2>&1
    ${MV} ${CONFIGFILE}.new.$$ ${CONFIGFILE}

    patchpro_patch_sequester_directory_to_replace=`egrep patchpro.patch.sequester.directory ${CONFIGFILE}`
    patchpro_patch_sequester_directory_to_retain=`egrep patchpro.patch.sequester.directory ${BAK_CONFIGFILE}`
    ${SED} 's:${patchpro_patch_sequester_directory_to_replace}:${patchpro_patch_sequester_directory_to_retain}:g' ${CONFIGFILE} > ${CONFIGFILE}.new.$$ || backoutnexit >> ${LOG} 2>&1
    ${MV} ${CONFIGFILE}.new.$$ ${CONFIGFILE}

    patchpro_patch_install_patchtype_to_replace=`egrep patchpro.patch.install.patchtype ${CONFIGFILE}`
    patchpro_patch_install_patchtype_to_retain=`egrep patchpro.patch.install.patchtype ${BAK_CONFIGFILE}`
    ${SED} 's:${patchpro_patch_install_patchtype_to_replace}:${patchpro_patch_install_patchtype_to_retain}:g' ${CONFIGFILE} > ${CONFIGFILE}.new.$$ || backoutnexit >> ${LOG} 2>&1
    ${MV} ${CONFIGFILE}.new.$$ ${CONFIGFILE}
    rm ${BAK_CONFIGFILE}
fi

# Removing old package instances
#
if [ $patchpropkg_action == "upgrade" ]; then
    if (( $SOLARISVERSION < "9" )); then
	echo "Packages to be removed: ${PKGINSTS_TO_REMOVE}"
	for pkg in ${PKGINSTS_TO_REMOVE}; do
		${PRINTINDENT} "Removing ${pkg}"
		${PKGRM} ${PKGCMDARGS} -n ${pkg}
    	done
    fi
fi

prepend "p' < /var/sadm/install/admin/default > ${MODADMINFILE}"
prepend "/action/D"
prepend "action\=nocheck"
prepend "sed -n '/action/i\\"
if [[ ${INCLUDESJAVA} -eq 1 ]]; then notifyRemoveJava; fi
prepend "echo \"Uninstalling PatchPro...\""
prepend "trap \"exit\" 0 1 2 3 15"
prepend "removejava=0"
prepend "cd /"
prepend "#!/bin/ksh"

append "rm ${FINALREMOVEPATH}"
append "rm -rf ${BASEDIR}/bin"

${SED} -e s/EvAl/$/g < ${REMOVEPATH} > ${REMOVEPATH}.new
chmod a+x ${REMOVEPATH}.new

rm ${REMOVEPATH}
mv ${REMOVEPATH}.new ${FINALREMOVEPATH}

if [[ ${REMOTEDIST} = "true" ]]; then
    ${PRINT} "${REMOTEDISTMSG}"
fi

echo
${PRINT} "Configuring PatchPro..."
if [ "${proxy}" != "TBD" ] && [ "${proxy_port}" != "TBD" ]; then
    if [ ! -z ${proxy} ] && [ ! -z ${proxy_port} ]; then
	${PRINTINDENT} "Setting the web proxy server and port..."
	eval "/opt/SUNWppro/bin/pprosetup -x ${proxy}:${proxy_port}"
    fi
fi

if [ "${proxy_user}" != "TBD" ] && [ "${proxy_passwd}" != "TBD" ]; then
    if [ ! -z ${proxy_user} ] && [ ! -z ${proxy_passwd} ]; then
	${PRINTINDENT} "Setting the web proxy server credentials.."
	eval "/opt/SUNWppro/bin/pprosetup -U ${proxy_user}"

	print -r -- "${proxy_passwd}" > ${SUNW_PPRO_BASE_DIR}/lib/.proxypw
	chmod go-rwx ${SUNW_PPRO_BASE_DIR}/lib/.proxypw
    fi
fi

${PRINT} "PatchPro configuration done."

# Restart the Solaris WBEM Services if needed.
#
# Also, remove legacy serialized data if exists.
#
${PRINT} ""
    if (( $SOLARISVERSION >= "9" )); then
	if [[ ${restart_cimom} = "true" ]]; then
		if [ -x /etc/init.d/init.wbem ]; then
			${PRINT} "Restarting Solaris WBEM Services..."
			eval "/etc/init.d/init.wbem stop"
			sleep 2
			eval "/etc/init.d/init.wbem start"
			${PRINT} "Done restarting Solaris WBEM Services."
		fi
	fi

	if [ -r /var/tmp/ppro_host.obj ]; then
		/usr/bin/rm -rf /var/tmp/ppro_host.obj
	fi	
    fi

${PRINT} ""
${PRINT} "Current PatchPro settings:"
eval "/opt/SUNWppro/bin/pprosetup -L"

echo
${PRINT} "Installation is complete and verified. Be sure to:"
echo
if [[ -n $BASEDIR ]]; then
    ${PRINTINDENT} "o Add \"$BASEDIR/bin\" and \"/usr/sadm/bin\" to   your \
 PATH. Set this in your .cshrc or .profile   to make it permanent."
fi
${PRINTINDENT} "o To configure PatchPro, see \"${PRODDIR}/README\" for \
 instructions."
if (( $SOLARISVERSION >= "9")); then
	if [[ ${restart_cimom} = "false" ]]; then
		${PRINTINDENT} "o For PatchPro to take effect, you must \
restart the Solaris WBEM Services on your system at the appropriate time. \
See PatchPro 2.2 Signed Patches Administration Guide for instructions."
	fi
fi
${PRINTINDENT} "o Run the \"$FINALREMOVEPATH\" script from the root \
 directory to uninstall PatchPro."

if [[ ${rebootrequired} = "true" ]]; then
    echo ""
    ${PRINT} "You must now reboot your system."
fi

rm ${MODADMINFILE}
