#!/bin/sh
# Copyright 06/02/05 Sun Microsystems, Inc. All Rights Reserved.
# pragma ident  "@(#)install-functions.sh	1.156 05/06/02 Sun Microsystems"

ARCH=`/usr/bin/uname -p`

case $ARCH in
    sparc) IMGPREFIX=""
    	DOTPREFIX=""
    ;;
    i386) IMGPREFIX=x86
    	DOTPREFIX="../"
    ;;
esac
OLDIMGPREFIX=$IMGPREFIX
OLDDOTPREFIX=$DOTPREFIX

# << BEGIN top level queries<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #
# Initializes the source directory.
# Sets    : SRC_DIR SRC_PKGVER
#
getSourceDirectory() {
    #1st priority to command line
    checkSourceDirectory 
    
    if [ $? -eq 0 ] ; then
        #2nd priority to ../image
        curr_wd=`$CMD_PWD`
        cd $SCRIPT_DIR
        SRC_DIR=../image               
        checkSourceDirectory
        ret=$?
        cd $curr_wd
        if [ $ret -ne 1 ] ; then        
            READ_RESPONSE_ONCE=0 
            #3rd priority to response file        
            while [ 1 ] ; do            
                fetch_response_text "TAG=SOURCE_DIRECTORY" "Enter the source directory of the installation files: "
                [ "$?" = "$SUMMARY_READ_ERROR" ] && EXIT_FLAG=$BAD_SOURCE_DIR && exit_SunMC    
            
                [ -z "$answer" ] && continue
            
                SRC_DIR=`getPathName $answer`
                if [ "$PROGNAME" = "archive-tool" ]; then
                  # Archive Tool should be independent of OS it is running on
                  # In case the source imageis x86, it has only solaris 9 bits
                  # The next function, checkSourceDirectory only checks for 
                  # SRC_DIR/Solaris_{OSVERS} which is 8 on a solaris 8 machine.
                  # So image tool running on 8 cannot create base image for x86
                  # bug id 5011744

                  l_old_OSVERS="$OSVERS"
                  l_all_os=`find_available_os_versions`
                  for each_os in `$CMD_ECHO "$l_all_os" | $CMD_AWK -F ',' '{ for (i=1; i<=NF; i++) print $i }'`
                  do
		      if [ $each_os -eq 10 ]; then
			[ -d "${SRC_DIR}/${BASE_PRODUCT_DIR}/Solaris_10" ] && OSVERS=10 && break
			[ -d "${SRC_DIR}/${BASE_PRODUCT_DIR}/Solaris_9" ] && OSVERS=9 && break
                      else
			[ -d "${SRC_DIR}/${BASE_PRODUCT_DIR}/Solaris_${each_os}" ] && OSVERS="$each_os" && break
		      fi
                  done
                fi # is progname archive-tool

                checkSourceDirectory
                [ $? -eq 1 ] && break

                $CMD_ECHO "  \c"
                echolog '  Invalid source directory: $2' "$SRC_DIR"
                echolog ''        
            done
        fi # valid ../image
    fi # valid -S
    SRC_DIR=`getPathName $SRC_DIR`
    if [ "$SOURCE_IMAGE" = "DEFAULT" -a "$PROGNAME" != "archive-tool" ] ; then
    TEXTDOMAINDIR="$SRC_DIR/../image/PE/CommonForSolaris/locale"
    fi
    echolog 'Installation files source directory: $2' "$SRC_DIR"
    echologverbose '$2' "$LOG_LINE"
    echolog ''
    saveAutoConfig "SOURCE_DIRECTORY" "$SRC_DIR"
    LOCALE_CONFIG_FILE="$SRC_DIR/${BASE_PRODUCT_DIR}/.locales"
    if [ "$SOURCE_IMAGE" = "DEFAULT" -a "$PROGNAME" != "archive-tool" ] ; then
        getLocaleDir
        setup_textdomain
    fi
    
    # reset OSVERS for archive tool 
    if [ "$PROGNAME" = "archive-tool" ]; then
        OSVERS="$l_old_OSVERS"
    fi

}

#reads $SRC_DIR
getSourceVersion() {    

    if [ "$PROGNAME" = "archive-tool" ]; then
        # Archive Tool should be independent of OS it is running on
        # In case the source imageis x86, it has only solaris 9 bits
        # The next code in this function only checks for 
        # SRC_DIR/Solaris_{OSVERS} which is 8 on a solaris 8 machine.
        # So image tool running on 8 cannot create base image for x86
        # bug id 5011744

        l_old_OSVERS="$OSVERS"
        l_all_os=`find_available_os_versions`
        for each_os in `$CMD_ECHO "$l_all_os" | $CMD_AWK -F ',' '{ for (i=1; i<=NF; i++) print $i }'`
        do
	    if [ $each_os -eq 10 ]; then
	      [ -d "${SRC_DIR}/${BASE_PRODUCT_DIR}/Solaris_10" ] && OSVERS=10 && break
	      [ -d "${SRC_DIR}/${BASE_PRODUCT_DIR}/Solaris_9" ] && OSVERS=9 && break
	    else
              [ -d "${SRC_DIR}/${BASE_PRODUCT_DIR}/Solaris_${each_os}" ] && OSVERS="$each_os" && break
	    fi
        done
    fi

    [ "$SOURCE_IMAGE" != "DEFAULT" ] && return
     
    getPackageVersion "$SRC_DIR"/${BASE_PRODUCT_DIR}/Solaris_${OSVERS}/Basic/SUNWescom
         
    checkString "$PACKAGE_VERSION" "_" # Check to see if it has an underscore  
    
    if [ $? -eq 0 ] ; then
       SRC_PKGVER=`$CMD_EXPR "$PACKAGE_VERSION" : '\(.*\)_'` # Remove all after the underscore
    else
        SRC_PKGVER=$PACKAGE_VERSION
    fi
    
    if [ -n "$AUTOCONFIG_RUNFILE" ] ; then
        tmp_version=`getAutoConfig "SUNMC_VERSION"`
        if [ "$tmp_version" != "$SRC_PKGVER" ] ; then
            echolog ''
            echolog 'WARNING: Version conflict in response file: $2' "$AUTOCONFIG_RUNFILE" 
            echolog 'Some questions may be redirected to console.'               
        fi
    fi

    saveAutoConfig "SUNMC_VERSION" "$SRC_PKGVER"
    export SRC_PKGVER

    # reset OSVERS for archive tool 
    if [ "$PROGNAME" = "archive-tool" ]; then
        OSVERS="$l_old_OSVERS"
    fi
               
}


# Checks the validity of the source directory
# Reads   : $SRC_DIR
# Returns : 1 if valid; 0 otherwise
# Sets    : SOURCE_IMAGE=ADDON_ONLY if the source does not point to ${BASE_PRODUCT_DIR}
checkSourceDirectory() {
    ret=0    
    if [ "$SRC_DIR" != "" ] ; then # Source dir exists
	# For S10, if Solaris_10 directory exists, then use it
	# else, use Solaris_9 as the default directory
	if [ $OSVERS -eq 10 ]; then
	    [ -d "${SRC_DIR}/${BASE_PRODUCT_DIR}" ] && [ ! -d "${SRC_DIR}/${BASE_PRODUCT_DIR}/Solaris_10" ] && OSVERS=9
	fi
	os_dir="${SRC_DIR}/${BASE_PRODUCT_DIR}/Solaris_${OSVERS}"
        pe_info="${os_dir}/installation.info"
        pe_properties="${os_dir}/installation.properties"
            
        if [ -f "$pe_info" -a -f "$pe_properties" ]  ; then
            ret=1
            INSTALL_TYPE=BASE
            setInstallationInfoInstallationProperties
        elif [ -d "${SRC_DIR}/Addons" ] ; then
            SOURCE_IMAGE="ADDON_ONLY" 
            ret=1
        else
            checkPatchOnlyDirectory
	    if [ $? -eq 1 ] ; then
	        SOURCE_IMAGE="PATCH_ONLY"	        
	        ret=1
	    fi                        
        fi    
    fi 
    
    return $ret
}

# Checks whether a different version of SunMC exists
# Reads   : SRC_PKGVER INSTALL_TYPE
# Returns : 1 if exists; 0 otherwise
#
checkOldSunMCExists() {
  
    [ "$SOURCE_IMAGE" = "ADDON_ONLY" ] && return 0 # source does not have BASE_PRODUCT_DIR
    
    $CMD_PKGINFO $RELOC_PARAM -qi SUNWescom
    [ $? -ne 0 ] && return 0
    
    INSTALLED_PKGVER=`$CMD_PKGPARAM $RELOC_PARAM SUNWescom SUNW_PRODVERS`    
    while [ 1 ] ; do        
        checkString "$INSTALLED_PKGVER" "_" # Check to see if it has an underscore
        [ $? -ne 0 ] && break
        INSTALLED_PKGVER=`$CMD_EXPR "$INSTALLED_PKGVER" : '\(.*\)_'` # Remove all after the underscore
    done
    
    [ "$INSTALLED_PKGVER" = "$SRC_PKGVER" ] && return 0  
   
    export INSTALLED_PKGVER
    return 1
}

# Gets the target directory
getTargetDirectory() {
    echolog ''
    checkTargetDirectoryExists
    if [ $? -eq 0 ] ; then  #does not exist
        #1st priority to command line
        checkInstallDirectory $TARGET_DIR        
        if [ $? -ne 0 ] ; then 
            READ_RESPONSE_ONCE=0
            temp_dir="${RELOCATED_ROOT}/opt"
            while [ 1 ] ; do        
                fetch_response_text "TAG=TARGET_DIRECTORY" 'Enter the directory in which you want to install: [ $3 ]' "$temp_dir"
                [ "$?" = "$SUMMARY_READ_ERROR" ] && EXIT_FLAG=$BAD_TARGET_DIR && exit_SunMC         
                [ -z "$answer" ] && answer="$temp_dir"
                                
                if [ -z "$RELOCATED_ROOT" -o "$RELOCATED_ROOT" = "/" ] ; then
                    TARGET_DIR_WITHOUT_RELOC=`getPathName "$answer"`
                    TARGET_DIR=`getPathName "$answer"`
                else
                    verifyTargetDirectoryAndGetBaseDir $answer
                    [ $? -eq 1 ] && continue
                    TARGET_DIR_WITHOUT_RELOC="$LOCAL_BASEDIR"
                    TARGET_DIR=`getRelocPathName "$LOCAL_BASEDIR"`
                fi    
                                       
                checkInstallDirectory $TARGET_DIR        
                [ $? -eq 0 ] && break                        
            done     
        fi
    fi
    [ "$SOURCE_IMAGE" != "PATCH_ONLY" ] && echolog 'Installation destination directory: $2' "$TARGET_DIR"   
    
    echologverbose '$2' "$LOG_LINE"
    echolog ''
            
    export TARGET_DIR
    saveAutoConfig "TARGET_DIRECTORY" "$TARGET_DIR_WITHOUT_RELOC"   

}

verifyTargetDirectoryAndGetBaseDir() {
    local_target_dir=`$CMD_ECHO $1 | $CMD_SED -e 's|//*|/|g'`
    local_root_dir=`$CMD_ECHO $RELOCATED_ROOT | $CMD_SED -e 's|//*|/|g'`
    echo "$local_target_dir" | $CMD_GREP "^$local_root_dir" > /dev/null 2>&1
    if [ $? -ne 0 ] ; then
        [ -n "$LOGFILE" ] && echolog 'The path entered is not located on $2' "$local_root_dir"
        return 1
    fi
    LOCAL_BASEDIR=`$CMD_ECHO $local_target_dir | $CMD_SED -e "s|^$local_root_dir|/|"`
    LOCAL_BASEDIR=`echo "$LOCAL_BASEDIR" | $CMD_SED -e 's|//*|/|g'`
    unset local_target_dir local_root_dir
    return 0    
}

# Checks the validity of any install directory, creating it if necessary.
# Inputss   : $1 - install directory
# Returns : 0 if valid
#Performs the following checks: 
#    1. Create if it does not exist.
#    2. Check if it is in /tmp
#    3. Check if it is writeable
#    4. Check if it is a nfs mounted file system
#    5. Check if minimum 5mb space is available on this partition
#
checkInstallDirectory() {
    install_directory=$@
    words=`$CMD_ECHO "$install_directory" | $CMD_WC -w 2> /dev/null`
    if [ $words -gt 1 ] ; then
        echolog 'The directory name must not contain spaces.'
        return 1
    fi
     
    if [ -n "$install_directory" ] ; then  
        install_directory=`getPathName "$install_directory"`   
        #    1. Create if it does not exist
        if [ ! -d "$install_directory" ] ; then                       
            $CMD_ECHO "  \c"
            echolog 'The directory $2 does not exist!' "$install_directory"
            $CMD_ECHO "  \c"
            if [ "$install_directory" != "$VAROPTDIR" ] ; then 
                if [ -z "$AUTOCONFIG_RUNFILE" ] ; then
                    ask_user 'Do you want to create it now '
                    [ $answer -eq 0 ] && return 1
                fi    
              
                $CMD_MKDIR -p "$install_directory" > /dev/null 2>&1
                if [ $? -ne 0 ] ; then
                    $CMD_ECHO "    \c"                    
                    echolog 'This directory could not be created sucessfully!'
                    $CMD_ECHO "    \c" 
                    echolog 'Check the permissions and try again.'               
                    return 1            
                fi
            else
                return 1
            fi                
        fi
                
        #    2. Check if it is in /tmp
        checkForTmp $install_directory
        if [ $? -eq 1 ] ; then
            if [ "$install_directory" != "$VAROPTDIR" ] ; then 
                return 2
            else
                exit_SunMC "$BAD_TARGET_DIR"
            fi
        fi


        
        #    3. Check if it is writeable
        $CMD_TOUCH "${install_directory}/testfile" >/dev/null 2>&1
        if [ $? -ne 0 ] ; then
            $CMD_ECHO "    \c"
            echolog 'Cannot write to the location: $2' "$install_directory"                
            if [ "$install_directory" != "$VAROPTDIR" ] ; then 
                return 3
            else
                exit_SunMC "$BAD_TARGET_DIR"
            fi
        fi
        
        
        #    4. Check if it is a nfs mounted file system, without root access       
        owner=`$CMD_LS -o ${install_directory}/testfile | $CMD_AWK '{print $3}'`
        $CMD_RM "${install_directory}/testfile" 
        
        if [ "$owner" != "root" ] ; then            
            echolog 'Invalid location : $2' "$install_directory"
            echolog 'You do not have permission to create files as superuser here.'
            echolog 'This directory could be mounted from a remote file system.'            
            if [ "$install_directory" != "$VAROPTDIR" ] ; then
                echolog 'You must enter a directory mounted on this host.'
                return 4
            else
                echolog 'Mount $2 on this system before attempting to install Sun Management Center' "$VAROPTDIR"
                exit_SunMC "$BAD_TARGET_DIR"
            fi                              
        fi
        
        #    5. Check if minimum 5mb space is available on this partition
        space=`$CMD_DF -k ${install_directory} | tail -1 | awk '{ print $4 }'`
        space=`$CMD_EXPR $space`
        if [ $space -lt 5000 ] ; then            
            echolog 'Minimum space requirement check failed!!'            
            if [ "$install_directory" != "$VAROPTDIR" -o $CLUSTER_INSTALLED -eq 1 ] ; then
                echolog 'You must specify a directory where atleast 5mb space is available'
                return 1
            else
                echolog 'Atleast 5mb space should be available on $2 before attempting to install Sun Management Center' "$VAROPTDIR"
                EXIT_FLAG=$BAD_TARGET_DIR
                exit_SunMC
            fi
        fi
        #    All ok.. return 0  
        return 0           
    fi
    return 1
}


# Checks if SunMC is installed and a target directory exists
# Returns: 1 if exists and valid
checkTargetDirectoryExists() {    
    # If some components are installed in a directory already,
    # force TARGET_DIR to be that directory.
    EXISTS=`$CMD_PKGPARAM $RELOC_PARAM SUNWescom BASEDIR 2> /dev/null`
    if [ $? -eq 0 ] ; then # Exists
        CORRUPT=0        
        EXISTS_PATH=`getRelocPathName $EXISTS`  
        
        # check if existing SUNWescom is valid
        # check only for this package, as detailed check is in the scope of validation tool.        
        
        $CMD_PKGCHK $RELOC_PARAM -q SUNWescom
        [ $? -ne 0 ] && CORRUPT=1 && EXIT_FLAG="$BAD_INSTALLATION_ERROR"   
        
        if [ "$INSTALLED_PKGVER" = "SRC_PKGVER" ] ; then
            [ ! -f "$REGISTRY" ] && CORRUPT=1 && EXIT_FLAG="$REGISTRY_READ_ERROR"
        fi
        
        if [ $CORRUPT -eq 1 ] ; then
            echolog 'The existing Sun Management Center installation is corrupt!!!'
            echolog 'Possible causes are :'
            echolog '1\\\) Manual cleanup of the installation directory $2' "$EXISTS"
            echolog '2\\\) Manual cleanup of the configuration directory $2' "$VAROPTDIR"
            echolog '3\\\) Missing installation and configuration Registry'
            echolog '4\\\) Any other corruption of the installed packages'
            echolog ''
            echolog 'We recommend that you clean up the system and re-attempt install.'
            echolog 'To clean the system, quit now and run the following command:'
            echolog "${SCRIPT_DIR}/es-uninst -X"
            echolog ''
            echolog '' 
            continueAfterConfirm
        fi
        #        
        
        if [ -n "$TARGET_DIR" ] ; then
            echolog ''
            echolog 'Some components have already been installed in $2' "$EXISTS_PATH"
            echolog ''        
        fi
        TARGET_DIR_WITHOUT_RELOC="$EXISTS"
        TARGET_DIR="$EXISTS_PATH"    
        ret=1
    else        
        ret=0
    fi
    return $ret
}

# Checks if the target directory is under /tmp
# Returns 1 if target is under tmp else returns 0
checkForTmp()
{
    check_directory=$1
    PWD=`$CMD_PWD`
    cd $check_directory
    TARGET_WD=`$CMD_PWD`
    TEST_TMPVAR=$TARGET_WD
    [ "$TARGET_WD" != "/" ] && TEST_TMPVAR=`$CMD_EXPR $TARGET_WD : '\(....\).*'`
    if [ "$TEST_TMPVAR" = "/tmp" ] ; then
        echolog 'The specified directory $2 cannot be under /tmp' "$check_directory"
        cd $PWD
        ret=1
    else
        cd $PWD
        ret=0
    fi
    return $ret
}



    
# 
# Reads   :
# Returns :
# Sets    : HA_INSTALL, DE_INSTALL
#    
getInstallEnvironment() {

    [ "$SOURCE_IMAGE" != "DEFAULT" ] && return    
    
    #first check if this is an incremental install, and if there is a response summary mismatch    
    tmp_inc=0
    $CMD_PKGINFO $RELOC_PARAM -qi SUNWescom 2>/dev/null
    [ $? -eq 0 ] && tmp_inc=1
    
    if [ "$tmp_inc" = "1" ] ; then #incremental
        tmp_components=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=${BASE_PRODUCT_KEY}" "component" "key" 2>/dev/null`
            
        checkString "$tmp_components" "COMPONENT.SDK"
        [ $? -eq 0 ] && [ "$ARCH" = "sparc" ] && DE_INSTALL=1
        
        checkString "$tmp_components" "COMPONENT.HA"
        [ $? -eq 0 ] && [ "$ARCH" = "sparc" ] && HA_INSTALL=1 
        
        #now check for mismatches
        #
        if [ -n "$AUTOCONFIG_RUNFILE" ] ; then #automated
            product=`getAutoConfig "ENVIRONMENT"`
            [ "$product" = "1" ] && tmp_PE=1
            [ "$product" = "2" ] && [ "$ARCH" = "sparc" ] && tmp_DE=1
            [ "$product" = "3" ] && [ "$ARCH" = "sparc" ] && tmp_HA=1
            
            PE="Product Environment"
            HA="Product Environment with HA Server"
            DE="Developer Environment"
            if [ "$tmp_DE" = "1" -a $DE_INSTALL -eq 0 ] ; then
                if [ $HA_INSTALL -eq 1 ] ; then
                    echolog '$2 is already installed on this machine.' "$HA"
                elif [ $HA_INSTALL -eq 0 ] ; then
                    echolog '$2 is already installed on this machine.' "$PE"
                fi
                echolog 'Unable to continue automated installation of $2.' "$DE"
                exit_SunMC "$PRODUCT_MISMATCH"
            elif [ "$tmp_HA" = "1" -a $HA_INSTALL -eq 0 ] ; then #not HA in resp file
                if [ $DE_INSTALL -eq 1  ] ; then                     
                    echolog '$2 is already installed on this machine.' "$DE"
                elif [ $DE_INSTALL -eq 0 ] ; then
                    echolog '$2 is already installed on this machine.' "$PE"
                fi
                echolog 'Unable to continue automated installation of $2.' "$HA"
                exit_SunMC "$PRODUCT_MISMATCH"
            elif [ "$tmp_PE" = "1" ] ; then
                if [ $DE_INSTALL -eq 1 ] ; then
                    echolog '$2 is already installed on this machine.' "$DE"
                elif [ $HA_INSTALL -eq 1 ] ; then 
                    echolog '$2 is already installed on this machine.' "$HA"
                fi         
                echolog 'Unable to continue automated installation of $2.' "$PE"
                exit_SunMC "$PRODUCT_MISMATCH"
            fi 
        fi
    else #fresh install        

        if [ "$AGENT_ONLY" != "1" ] ; then
            if [ "$OSVERS" != "2.6" -a "$OSVERS" != "7" -a "$ARCH" = "sparc" ] ; then
                        
                ##$CMD_PKGINFO $RELOC_PARAM -qi SUNWscr > /dev/null 2>&1
                ##[ $? -eq 0 ] && CLUSTER_INSTALLED=1
                echolog ''
                echolog 'Sun Management Center provides two types of environments: '
                echolog ''
                $CMD_ECHO "  \c"
                echolog '\\\(1\\\) Production Environment \\\(PE\\\)'
                $CMD_ECHO "  \c"
                multiline_echolog 'Choose PE for an active environment in which you can manage and monitor\n  your subsystems, components, and peripherals. You will be prompted to\n  select the components (Server, Agent and|or Console) you want to install.'
                echolog''
                $CMD_ECHO "  \c"
                echolog '\\\(2\\\) Developer Environment \\\(DE\\\)' 
                $CMD_ECHO "  \c"
                multiline_echolog 'Choose DE if you are a developer who wants to create and test your own\n  customized modules. Selecting DE installs all of the components (Server,\n  Agent and Console)'      
                if [ $CLUSTER_INSTALLED -eq 1 ] ; then
                    echolog''
                    $CMD_ECHO "  \c"
                    echolog '\\\(3\\\) Production Environment \\\(PE\\\) with Highly Available Server'
                    $CMD_ECHO "  \c"
                    echolog 'Note: The Sun Cluster package has been detected on this system.' 
                fi
                echolog ''

                
                READ_RESPONSE_ONCE=0
                if [ $CLUSTER_INSTALLED -eq 1 ] ; then
                    while fetch_response_text "TAG=ENVIRONMENT" 'Choose 1 or 2 or 3: [ 1 ]'; do                    
                        [ -z "$answer" ] && answer=1
                        [ "$answer" = "1" ] && break            
                        [ "$answer" = "2" ] && DE_INSTALL=1 && break
                        [ "$answer" = "3" ] && HA_INSTALL=1 && break
                        echolog 'You must enter 1 or 2 or 3.'
                    done
                else
                    while fetch_response_text "TAG=ENVIRONMENT" 'Choose 1 or 2: [ 1 ]'; do                    
                        [ -z "$answer" ] && answer=1
                        [ "$answer" = "1" ] && break            
                        [ "$answer" = "2" ] && DE_INSTALL=1 && break
                        echolog 'You must enter 1 or 2.'
                    done
                fi                
                saveAutoConfig "ENVIRONMENT" "$answer"
                [ "$HA_INSTALL" = "1" ] && getGlobalDir
            else
                saveAutoConfig "ENVIRONMENT" "1"
            fi
        fi
    fi 
       
    echologverbose '$2' "$LOG_LINE" 
    echolog ''
    export HA_INSTALL DE_INSTALL 
}

warning_message() {

  if [ "$keepData" = "true" ] ; then
      
      if [ "$agent_only_data" = "YES" ] ; then
          echolog ''
          echolog 'Internally detected previous agent-only installation.'
          echolog 'If you want to install server layer, please upgrade your OS to Solaris 8 or higher and re-run the installation.'
          echolog ''
      else
          echolog ''
          echolog 'If you choose to install agent and console layer now, your server data will not be migrated to a new release.'
          echolog 'In order to retain the server data, please upgrade your OS to Solaris 8 or higher and re-run the installation.'
          echolog ''
      fi

	READ_RESPONSE_ONCE=0

 	$CMD_ECHO ""
	fetch_response_yes_no "TAG=UPGRADE_OS" "Do you want to exit the installation to perform OS upgrade "
	do_it=$answer


	if [ $do_it -eq 1   ] ; then
		$CMD_ECHO ""
		exit_SunMC $NO_ERROR
	fi
  fi
}

getBaseLayers() {

    #
    #The if block below is for agent only installation. This will be used
    #when user has used our script to create agent only product from our 
    #CD and wants to install it. User will run es-inst -a to set AGENT_ONLY=1 
    #
    if [ "$AGENT_ONLY" = "1" ] ; then    
        INSTALL_LAYERS="LAYER.AGENT"
        saveAutoConfig "LAYER.AGENT" "1"
        saveAutoConfig "LAYER.CONSOLE" "0"
        saveAutoConfig "LAYER.SERVER" "0"
        
        getI18NMessage "LAYER.AGENT"
        echolog 'Selecting : $2' "$MSG"
        echolog ''
        return
    fi
    
    if [ "$SOURCE_IMAGE" != "DEFAULT" ] ; then    
        #
        #INSTALL_LAYERS needs to be set from the Registry
        #
        if [ "$PROGNAME" != "archive-tool" ] ; then
            INSTALL_LAYERS=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "layer" "key" 2>/dev/null`
        fi
        return
    fi 
     
    # get FULL_LAYER_LIST and selectable_layers
    #
    getLayerListFromFile

    if [ "$OSVERS" = "2.6" -o "$OSVERS" = "7" ] ; then
        echolog 'This machine is running Solaris $2' "$OSVERS"
        echolog 'You can install the Agent and Console components on Solaris $2' "$OSVERS"
        echolog 'Server components may ONLY be installed on a machine running Solaris 8 or above.' 
    
        
        #
        # This is to check the message.
        # If user chose to keep data this caution message should come up.
        #
        
        warning_message
    else         
        if [ "$ARCH" = "sparc" ]; then
            [ $HA_INSTALL -eq 1 ] && selectable_layers=1
        fi
    fi

    EXISTING_LAYER_LIST=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "layer" "key" 2>/dev/null`
    #[ $? -gt 0 ] && EXIT_FLAG=$REGISTRY_READ_ERROR && exit_SunMC        
    if [ -n "$EXISTING_LAYER_LIST" ] ; then #some layers are installed
        LAYER_LIST=""
        selectable_layers=0
        for each_installable_layer in $FULL_LAYER_LIST ; do        
            checkString "$EXISTING_LAYER_LIST" "$each_installable_layer"
            if [ $? -ne 0 ] ; then
                selectable_layers=`$CMD_EXPR $selectable_layers + 1`
                if [ -z "$LAYER_LIST" ] ; then
                    LAYER_LIST="$each_installable_layer"
                else
                    LAYER_LIST="$LAYER_LIST $each_installable_layer"
                fi
            else
               if [ -z "$INSTALL_LAYERS" ] ; then
                    INSTALL_LAYERS="$each_installable_layer"
                else
                    INSTALL_LAYERS="${INSTALL_LAYERS},$each_installable_layer"
                fi 
            fi
        done
        if [ -z "$LAYER_LIST" ] ; then
           echolog ''
           echolog 'All Sun Management Center Base components are already installed.'            
        fi      
    else
        LAYER_LIST=${FULL_LAYER_LIST}                
    fi
   
    if [ $DE_INSTALL -eq 0 -a -n "$LAYER_LIST" ] ; then
        echolog ''
        echolog 'Select the Sun Management Center components to install:'
        echolog '' 
        if [ -n "$EXISTING_LAYER_LIST" ] ; then
            EXISTING_LAYER_LIST=`$CMD_ECHO $EXISTING_LAYER_LIST | $CMD_SED "s/,/ /g"`
            echolog 'The following components are already installed: ' 
            string=""
            for layer in $EXISTING_LAYER_LIST
            do
                getI18NMessage $layer
                if [ -z "$string" ] ; then
                    string="$MSG"
                else
                    string="${string}, ${MSG}"
                fi                
            done 
            echolog '\r\t$2' "$string"
        fi
                
        echolog '$2 component\\\(s\\\) are available for your selection:' "$selectable_layers"
    fi

    for i in $LAYER_LIST ; do
        if [ $DE_INSTALL -eq 1 ] ; then
            [ -z "$INSTALL_LAYERS" ] && INSTALL_LAYERS="LAYER.SERVER,LAYER.AGENT,LAYER.CONSOLE"
            JAVA_CHECK_REQUIRED=1 
            WBSVR_CHECK_REQUIRED=1       
        else            
            checkString "$EXISTING_LAYER_LIST" "$i"        
            [ $? -eq 0 ] && continue 
            
            answer=""
            if [  $HA_INSTALL -eq 1 ] ; then
                [ "$i" = "LAYER.SERVER" -o "$i" = "LAYER.AGENT" ] && answer=1
            fi
            
            checkString "$INSTALL_LAYERS" "$i"
            [ $? -eq 0 ] && continue        
                   
            getI18NMessage $i                          
            
            
            if [ -z "$answer" ] ; then
                READ_RESPONSE_ONCE=0
                $CMD_ECHO "  \c"        
                fetch_response_yes_no "TAG=${i}" 'Do you want to install the $MSG component '
                saveAutoConfig "$i" "$answer"
            fi
            
            if [ "$answer" = "1" ] ; then 
                if [ -z "$INSTALL_LAYERS" ] ; then
                    INSTALL_LAYERS="$i"
                else
                    INSTALL_LAYERS="${INSTALL_LAYERS},$i"
                fi
            
                if [ "$i" = "LAYER.SERVER" ] ; then
                    checkString "$INSTALL_LAYERS" "LAYER.AGENT"
                    if [ $? -ne 0 ] ; then
                        checkString "$EXISTING_LAYER_LIST" "LAYER.AGENT"
                        if [ $? -ne 0 ] ; then
                            INSTALL_LAYERS="${INSTALL_LAYERS},LAYER.AGENT"
                            $CMD_ECHO "    \c" 
                            echolog  'Note: The Agent component will be installed automatically.'
                        fi
                    fi
                fi              
            fi     
        fi
    done
    
    if [ -z "$INSTALL_LAYERS" ] ; then
        echolog 'No components have been selected for installation.'
        echolog 'Exiting...'
        exit_SunMC $NO_ERROR
    fi
    
    if [ -z "$RELOCATED_ROOT" -o "$RELOCATED_ROOT" = "/" ] ; then
        checkString "$INSTALL_LAYERS" "LAYER.SERVER" OR "LAYER.CONSOLE"
        [ $? -eq 0 ] && JAVA_CHECK_REQUIRED=1
    fi
    
    checkString "$INSTALL_LAYERS" "LAYER.SERVER"
    [ $? -eq 0 ] && WBSVR_CHECK_REQUIRED=1
    
    echologverbose '$2' "$LOG_LINE"
    echolog ''    
   
    #If server is selected for install then do some early checks.
    #
    checkString "$INSTALL_LAYERS" "LAYER.SERVER"
    if [ $? -eq 0 ] ; then
        smcdb_check_memory_available
	checkSolarisExecutables	
	checkOldOraPackage            
    fi
    
    if [ "$JAVA_CHECK_REQUIRED" = "1" ] ; then
        echologverbose 'Looking for valid JDK.' 
        
        checkJavaOK        
        if [ $? -ne 0 ] ; then             
            exit_SunMC "$JAVA_ERROR"
        else
            echologverbose 'JDK check OK.'
            echologverbose ''
        fi
    fi
 
    if [ "$WBSVR_CHECK_REQUIRED" = "1" ] ; then
        echologverbose 'Looking for Tomcat Webserver.' 
 
        checkWebserverInstallRequired          
        if [ $? -eq 1 ] ; then
            multiline_echologverbose 'The necessary Tomcat Webserver packages are not installed on your system.\n\t\tOR\nThe Tomcat Webserver packages installed on your system are not of the required version.'
            echologverbose 'The following packages are required for the Sun Management Center Server:'
            echologverbose '$WBSVR_PKGLIST_TO_INSTALL'
	    echologverbose 'The required version of Tomcat Webserver packages shall be installed/upgraded.' 
            saveAutoConfig "INSTALL_WEBSERVER" "1"  
            INSTALL_WEBSERVER=1
        elif [ $? -eq 2 ] ; then
            echolog 'WARNING:'            
            echolog 'Tomcat Webserver installed on your system appears to be of an outdated version'
            echolog 'You may encounter some problems during setup.'
            echolog ''
        else
            echologverbose 'Webserver check OK.'
            echologverbose ''
        fi
        checkJavaHelpInstallRequired 
        [ $? -eq 1 ] && INSTALL_JAVAHELP=1
        # Check if lockhart is to be installed. If yes, then export the appropriate var
        checkSunWebconsoleInstallRequired
        [ $? -eq 1 ] && INSTALL_LH_WEBCONSOLE=1 
        
    fi    
}

#
# Get LAYER list from the installation.info file.
# This function creates FULL_LAYER_LIST and selectable_layers variables.
#
getLayerListFromFile () {
    FULL_LAYER_LIST=""
    selectable_layers=0

    for COMPONENT_KEY in `$CMD_CAT $INSTALLATION_INFO | $CMD_AWK -F= '/COMPONENT_KEY/ {print $2}'`
    do
	if [ "$COMPONENT_KEY" = "COMPONENT.SERVER" \
          -o "$COMPONENT_KEY" = "COMPONENT.AGENT" \
          -o "$COMPONENT_KEY" = "COMPONENT.CONSOLE" ]; then

	    FULL_LAYER_LIST="$FULL_LAYER_LIST $COMPONENT_KEY"
	    selectable_layers=`expr $selectable_layers + 1`
	fi
    done

    FULL_LAYER_LIST=`$CMD_ECHO $FULL_LAYER_LIST | $CMD_SED 's/COMPONENT/LAYER/g'`
}

checkOldOraPackage() { 
    [ ! -d "${SRC_DIR}/db/SUNWesora" ] && return     # Add-On only image.   
    #
    # check if the package has been installed alreadly
    #
    $CMD_PKGINFO -q $RELOC_PARAM "SUNWesora"  >/dev/null 2>&1 # Disallow partial installs and mismatches
    if [ $? -eq 0 ] ; then
        # this message would appear in every incremental install, hence verbose.
        echologverbose 'The SUNWesora Sun Management Center database package is already installed on your system.'        
        
        #check if version matches
        src_ora_vers=`$CMD_PKGPARAM  -f ${SRC_DIR}/db/SUNWesora/pkginfo SUNW_PRODVERS`
        installed_ora_vers=`$CMD_PKGPARAM $RELOC_PARAM SUNWesora SUNW_PRODVERS`
        
        [ "$src_ora_vers" = "$installed_ora_vers" ] && return 
        
        echolog 'The installed version of SUNWesora differs from the one required for Sun Management Center 3.5 Update 1' 
        echolog 'Installation cannot continue.'     
	exit_SunMC $ORACLE_INSTALLATION_FAILED
    fi
}

getLocales() {

    INSTALL_LOCALES=""    
    if [ "$SOURCE_IMAGE" != "DEFAULT" ] ; then # addon-only or patch-only image
        if [ "$PROGNAME" != "archive-tool" ] ; then
            INSTALL_LOCALES=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "locale" "key" 2>/dev/null`
        fi
        return
    fi
    
    [ ! -s "$LOCALE_CONFIG_FILE" ] && INSTALL_LOCALES=C && return #no localization
      
    onlyC=0
    
    ALL_LOCALES=`get_value_from_cfgfile $LOCALE_CONFIG_FILE ALL_LOCALES =`

    [ "$INSTALL_LAYERS" = "LAYER.AGENT" ] && INSTALL_LOCALES="$ALL_LOCALES" && return    
    
    echolog ''
    echolog 'Sun Management Center can be installed in the following languages:'
    
    for lang in `$CMD_ECHO "$ALL_LOCALES" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'` ; do
            language="`get_value_from_cfgfile $LOCALE_CONFIG_FILE ${lang} =`"
            $CMD_ECHO "  \c"
            echolog "$language"
    done
    echolog ''

    if [ "$PROGNAME" != "archive-tool" ] ; then
        EXISTING_LOCALE_LIST=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "locale" "key" 2>/dev/null`
        #[ $? -gt 0 ] && EXIT_FLAG=$REGISTRY_READ_ERROR && exit_SunMC
    fi
    
    if [ -n "$EXISTING_LOCALE_LIST" ] ; then 
        [ "$EXISTING_LOCALE_LIST" = "C" ] && onlyC=1 
             
        LOCALE_LIST=""
        for each_installable_locale in `$CMD_ECHO "$ALL_LOCALES" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'` ; do
            checkString "$EXISTING_LOCALE_LIST," "$each_installable_locale,"
            if [ $? -ne 0 ] ; then                
                if [ -z "$LOCALE_LIST" ] ; then
                    LOCALE_LIST="$each_installable_locale"
                else
                    LOCALE_LIST="$LOCALE_LIST,$each_installable_locale"
                fi           
            fi
        done
        [ -z "$LOCALE_LIST" ] && INSTALL_LOCALES="$ALL_LOCALES" && echolog 'All supported languages are installed' && return
        
        if [ $onlyC -ne 1 ] ; then
            echolog 'English and the following languages have been installed previously:'
            for locale in `$CMD_ECHO "$EXISTING_LOCALE_LIST" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
            do
                [ "$locale" = "C" ] && continue
                $CMD_ECHO "  \c"
                language="`get_value_from_cfgfile $LOCALE_CONFIG_FILE $locale =`"
                echolog "$language"
            done
        
        else
            echolog 'English has been installed previously.'
        fi
        echologverbose '$2' "$LOG_LINE"        
    else
        LOCALE_LIST=$ALL_LOCALES
    fi
    
    #
    # Have to do some jugglery here to manage filtering of stuff like
    # zh_TW.BIG5 and zh_TW.UTF-8, as well as ja_JP.PCK and fr.UTF-8
    # LOCALE_CODE variable is internal to es-inst, and used for filtering 
    # and displaying Language choices to the user. LANG is used to pick 
    # up the messages from the po file.
    #
    # Note hardcoding of zh_TW and zh_HK. If there are more like this, we
    # need to update this logic.
    #
    
    checkString "$LOCALE_CODE" "zh_TW" "OR" "zh_HK"
    if [ $? -eq 0 ]; then
        LOCALE_CODE=`/usr/bin/expr "$LOCALE_CODE" : '\(.....\).*'`    	    
    else
        LOCALE_CODE=`/usr/bin/expr "$LOCALE_CODE" : '\(..\).*'`
    fi
    
    
    [ "$LOCALE_CODE" != "C" ] && language="`get_value_from_cfgfile $LOCALE_CONFIG_FILE ${LOCALE_CODE} =`"
    
    if [ "$LOCALE_CODE" = "C"  -o -z "$language" ] ; then            
        [ $onlyC -ne 1 ] && echolog 'English is installed by default.'
    else         
        language=`$CMD_GETTEXT "$language"`
        echolog '${language} and English are installed by default.'
    fi
    
    READ_RESPONSE_ONCE=0
    fetch_response_yes_no "TAG=INSTALL_LOCALES" "Are other languages required "
    saveAutoConfig "INSTALL_LOCALES" "$answer"   
    if [ "$answer" = "1" ] ; then
        for i in `$CMD_ECHO "$LOCALE_LIST" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'` ; do
            if [ "$i" = "$LOCALE_CODE" -o "$i" = "C" ] ; then
                 answer=1
            else            
                READ_RESPONSE_ONCE=0
                answer=""
                language="`get_value_from_cfgfile $LOCALE_CONFIG_FILE $i =`"
                $CMD_ECHO "  \c"        
                fetch_response_yes_no "TAG=${i}" "$language"                
            fi
            saveAutoConfig "$i" "$answer"
            if [ "$answer" = "1" ] ; then
                if [ -z "$INSTALL_LOCALES" ] ; then
                    INSTALL_LOCALES="$i"  
                else 
                    INSTALL_LOCALES="${INSTALL_LOCALES},$i" 
                fi               
            fi
        done     
    else
        [ "$LOCALE_CODE" != "C" ] && INSTALL_LOCALES="${INSTALL_LOCALES},${LOCALE_CODE}"   
    fi     
    
    [ -z "$EXISTING_LOCALE_LIST" -a $onlyC -ne 1 ] && INSTALL_LOCALES="${INSTALL_LOCALES},C"
   
    if [ "$PROGNAME" != "archive-tool" ] ; then
        existing_locales=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "locale" "key" 2>/dev/null`
    fi
    if [ -n "$existing_locales" ] ; then
        for locale in `$CMD_ECHO "$existing_locales" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'` ; do
            checkString "$INSTALL_LOCALES," "$locale,"
            [ $? -eq 0 ] && continue
            INSTALL_LOCALES="${INSTALL_LOCALES},${locale}"
        done
    fi    
    echologverbose '$2' "$LOG_LINE"
    echolog ''
}

# << END top level queries<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #


# << BEGIN validity checking<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #


checkOld2XDataOnlyExists() {

ret_code=0

[ "$SOURCE_IMAGE" = "ADDON_ONLY" ] && return 0 # source does not point to PE/DE

    # first check if 3.5 is installed
    $CMD_PKGINFO $RELOC_PARAM -qi SUNWescom
    if [ $? -eq 0 ] ; then
        PKGVER=`$CMD_PKGPARAM $RELOC_PARAM SUNWescom VERSION`
        tmp_pkgversion=`$CMD_EXPR "$PKGVER" : '\(...\).*'`
	# For correct comparison, bring the $SRC_PKGVER to the same 
	# format as $tmp_pkgversion,
  	# that is, to two digits separated by dot.
	tmp_src_pkgver=`$CMD_EXPR "$SRC_PKGVER" : '\(...\).*'`

        if [ "$tmp_pkgversion" = "$tmp_src_pkgver" ] ; then
            return 0
        fi
    fi

    #
    # Sanity checks:
    # - check if a 3.0 or 3.5 migration is in progress; if so, don't bother
    #   checking for 2.x data.
    #
    if [ -d $VAROPTDIR/upgrade ] ; then
        return 0
    fi

    smc30_db_dir="${VAROPTDIR}/SunMCDB02"
    if [ -d "$smc30_db_dir" -o -d "${smc30_db_dir}.backup" ] ; then
        return 0
    fi


# ret_code=2 if 2.x raw data exists
# ret_code=3 if 2.x exported data exists
# ret_code=4 if configuration data only exists (agent only)
# ret_code=0 if neither data nor export files exist

   # Initialize some variables.

   # For existing 2.x data only: 
   smc2x_event_data="${VAROPTDIR}/db/eventmgr"
   smc2x_topo_data="${VAROPTDIR}/db/topology"
   smc2x_cfg_data="${VAROPTDIR}/cfg"

   # For exported 2.x data:
   smc2x_extracted_db="${VAROPTDIR}/2x/db"
   smc2x_extracted_cfg="${VAROPTDIR}/2x/cfg"
   smc2x_export_log="${VAROPTDIR}/2x/db-export.log"

   # Detect if 2.x data has been exported.

   if [ -d "$smc2x_extracted_db" -a -d "$smc2x_extracted_cfg" -a -f "$smc2x_export_log" ]; then
      # 2.x has been extracted already.
      # Set appropriate $ret_code of 3.
      ret_code=3
   else 
      if [ -d "$smc2x_topo_data" -a -d "$smc2x_event_data" -a -d "$smc2x_cfg_data" ]; then
            # 2.x data only exists
            # Set appropriate $ret_code of 2.
            ret_code=2
      else
    	    # If only the cfg subdir exists, then we still need to
    	    # copy over the persistent dat files
    	    #
            cfg_cnt=0
	    [ -d "$smc2x_cfg_data" ] && cfg_cnt=`$CMD_LS -1 "$smc2x_cfg_data" | $CMD_WC -l` 
    	    if [ -d "$smc2x_cfg_data" -a "$cfg_cnt" -gt 0 ] ; then
               ret_code=4
	    else
	       ret_code=0	
    	    fi	
      fi
   fi

   return $ret_code

}


#Checks whether SunMC 3.x data only exists
# Return: 1 if exists; 0 otherwise
checkOld30DataOnlyExists() {

    ret_code=0

    # Do data-only migration if the current installation is 3.0
    # Returns 0 if this is not 3.0 installation
    # This additional check is required as you can incrementally do ADD-ON
    # installations on top of an existing 3.0 installation.

    #first check if 3.0 is installed
    $CMD_PKGINFO $RELOC_PARAM -qi SUNWescom
    if [ $? -eq 0 ] ; then
        PKGVER=`$CMD_PKGPARAM $RELOC_PARAM SUNWescom VERSION`
        tmp_pkgversion=`$CMD_EXPR "$PKGVER" : '\(...\).*'`
	# For correct comparison, bring the $SRC_PKGVER to the same
	# format as $tmp_pkgversion,
	# that is, to two digits separated by dot.
	tmp_src_pkgver=`$CMD_EXPR "$SRC_PKGVER" : '\(...\).*'`

        if [ "$tmp_pkgversion" = "$tmp_src_pkgver" ] ; then
            return 0
        fi
    fi
    smc30_ora_data="${VAROPTDIR}/SunMCDB02"
    smc_cfg_dir="${VAROPTDIR}/cfg"


    #
    # both the 3.0 data directory and the old cfg
    # directory must exist in order to return true
    # If both subdirs exists, then we need to do export
    #
    if [ -d "$smc30_ora_data" -o -h "$smc30_ora_data" ] ; then
        if [ -d "$smc_cfg_dir" ] ; then
            ret_code=1
        fi
    fi

    return $ret_code
}

# Get the correct directory
# $1 - the suffix to be added to the return directory
# Return: $CORRECT_DIR
getCorrectDirectory() {
    if [ "$INSTALL_TYPE" = "BASE" ] ; then        
	if [ "$OSVERS" = "10" ]; then
	    CORRECT_DIR="${SRC_DIR}/${BASE_PRODUCT_DIR}/Solaris_10/$1" # OS
	    [ -d "$CORRECT_DIR" ] && return 1
	    OSVERS=9
	fi

        CORRECT_DIR="${SRC_DIR}/${BASE_PRODUCT_DIR}/Solaris_${OSVERS}/$1" # OS
        [ -d "$CORRECT_DIR" ] && return 1
        
        CORRECT_DIR="${SRC_DIR}/${BASE_PRODUCT_DIR}/CommonForSolaris/$1" 
        [ -d "$CORRECT_DIR" ] && return 1

        CORRECT_DIR="${SRC_DIR}/${BASE_PRODUCT_DIR}/Common/$1" 
        [ -d "$CORRECT_DIR" ] && return 1        
    else # Addons

       # Reset OSVERS=10 whenever possible
    if [ "$PROGNAME" != "archive-tool" ]; then
        if [ "$OSVERS_BITS" = "" ]; then
            OSVERS_CURRENT=`$CMD_UNAME -r`
            if [ "$OSVERS_CURRENT" = "5.10" ]; then
                OSVERS="10"
            fi
        else
            if [ "$OSVERS_BITS" = "10" ]; then
                OSVERS="10"
            fi
        fi
    fi
        dir=`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" "SOURCE_DIR"`
        
	if [ "$OSVERS" = "10" ]; then
	    CORRECT_DIR="${SRC_DIR}/Addons/${dir}/Solaris_10/$1" # OS
	    [ -d "$CORRECT_DIR" ] && return 1
	    [ -d "${SRC_DIR}/Addons/$dir/Solaris_9/$1" ] && OSVERS=9
	fi

        CORRECT_DIR="${SRC_DIR}/Addons/${dir}/Solaris_${OSVERS}/$1" # OS
        [ -d "$CORRECT_DIR" ] && return 1
        
        CORRECT_DIR="${SRC_DIR}/Addons/${dir}/CommonForSolaris/$1" 
        [ -d "$CORRECT_DIR" ] && return 1 

        CORRECT_DIR="${SRC_DIR}/Addons/${dir}/Common/$1" 
        [ -d "$CORRECT_DIR" ] && return 1     
    fi    
    CORRECT_DIR=""
    return 0
}

# << END validity checking<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #



# << BEGIN initializations<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #

displayWelcomeMessage() {
    $CMD_CLEAR
    echolog ''    
    echolog '$2' "$LOG_LINE"  
    echolog 'This script installs Sun \\(TM\\) Management Center 3.5 Update 1'                 
    echolog '$2' "$LOG_LINE"
    echolog ''
    echolog ''
}

displayFinalMessage() {
    echolog ''
    echolog 'Install logfile is : $2' "$LOGFILE"
    echolog ''
    echologverbose "$LOG_LINE"
    echo    "                        \c"
    echolog '$2End of Installation' "\r\t\t\t" 
    echologverbose "$LOG_LINE"
    echolog ''

    exit_SunMC $NO_ERROR
}


# Returns:
#	0	3.5 data not found
#	1	3.5 data is found
checkOldSunMC35DataOnlyExists() {

    ret_code=0

    #
    # Check if 3.5 export data is present.
    #

    db_migr_read_meta SUNMC_OWNER
    if [ $? -ne 0 ] ; then
        return 0
    else
        if [ "$MIGR_CORE_PRODUCT_VER" -eq "3.5" ] ; then
            return 1
        fi
    fi

    return 0
}

processOld35Data() {

echolog ''
echolog 'Existing Sun Management Center 3.5 Update 1 Data detected.'

    #
    # Ask user if they wish to proceed. Tackles response summary
    #
    askAboutOldData #this will set keepData="true" or "false"

}

processOldSunMC() {

    # Remove old SunMC installation
    # 
    while [ 1 ] ; do
       checkOldSunMCExists
        if [ $? -eq 1 ] ; then
            removeOldSunMC # installed version
        else
	   checkOldSunMC35DataOnlyExists
    	   if [ $? -eq 0 ] ; then
	      # Save any pre-3.5 data that may exist
              processOldData
	   fi
	   break	
        fi
        EXIT_FLAG=$NO_ERROR
    done
}

setInstallFlags() {
    OSVERS_BITS=""      # variable to set osversion for Solaris S10 and S9 bits
    BASE_PRODUCT_DIR=PE
    BASE_PRODUCT_KEY=PRODUCT.PE
    TRIED_UNINST=0    
    VERBOSE=OFF
    AGENT_ONLY=0
    CLUSTER_INSTALLED=0
    HA_INSTALL=0
    DE_INSTALL=0
    LOCALE_CONFIG_FILE=""
    ROOT=""    
    RELOC_PARAM=""
    RELOC_PLATFORM=""
    CFGINFOFILE_SETTING=""
    EOL=$
    INSTALL_COMPONENTS=""
    INSTALL_PACKAGES=""
    INSTALLATION_INFO=""
    INSTALLATION_PROPERTIES=""
    LOGFILE=""
    ADMIN=""
    DEFADMIN=""
    INSTALL_TYPE="BASE"
    SRC_DIR=""
    SRC_PKGVER=""
    INSTALLED_PKGVER=""
    TARGET_DIR_WITHOUT_RELOC=""
    TARGET_DIR=""
    ORACLE_TARGET_DIR=""
    READ_RESPONSE_ONCE=0
    SOURCE_IMAGE="DEFAULT"
    AUTOCONFIG_SAVEFILE=""
    AUTOCONFIG_RUNFILE=""
    CURRENT_INSTALL_TYPE=""
    COMPONENTS_NOT_TO_BE_INSTALLED=""
    ADDON_COMPONENTS_NOT_TO_BE_INSTALLED=""
    FAIL_LIST=""
    SOURCE_LIST=""
    FAILED_PACKAGES=""
    FAILED_PATCHES=""
    MISMATCH_LIST=""
    LOG_LINE="----------------------------------------------------------------------------"
    EXIT_FLAG=$NO_ERROR
    ALL_SELECTED_OPTIONALS=""
    ALL_SELECTED_OPTIONAL_PACKAGES=""
    REJECT_PACKAGE_LIST=""
    INSTALL_SUNMC_PATCHES=0  
    INSTALL_WEBSERVER=0      
    INSTALL_LH_WEBCONSOLE=0
    INSTALL_JAVAHELP=0
    OPTIMIZE_FOR_ES_INST=0
    checkString "$PROGNAME" "es-inst"
    [ $? -eq 0 ] && OPTIMIZE_FOR_ES_INST=1  
    flash_questions_to_console=1   
    SIGHUP=1
    SIGINT=2
    SIGQUIT=3
    SIGTERM=15 

    # Variable to fix RFE: 4826819
    INSTALL_DOCS="FALSE"
}

printUsage() {
    echo ""
    eval echo "\"`$CMD_GETTEXT 'Usage: $PROGNAME [-S dir][-T dir][-R dir][-C file][-A file][avh]\n   where the options represent:\n'`\""

    $CMD_GETTEXT '     S <dir> : installs Sun Management Center using <dir> as the source directory\n'
    $CMD_GETTEXT '     T <dir> : installs Sun Management Center using <dir> as the target directory\n'
    $CMD_GETTEXT '     R <dir> : installs Sun Management Center on a machine whose root filesystem \n               is mounted at <dir>.\n'
    $CMD_GETTEXT '     C <file>: stores configuration details of this installation in <file>\n'
    $CMD_GETTEXT '     A <file>: does an automated installation using <file> configuration file\n'
    $CMD_GETTEXT '     a : installs Sun Management Center Agent layer only\n'
    $CMD_GETTEXT '     v : installs Sun Management Center in verbose mode\n'
    $CMD_GETTEXT '     h : prints this usage report\n'
    echo ""
}

    
# new
# $@ - options to es-inst.
# flag: "COPY_FLAG" - indicates that es-inst has to call itself from TMP_DIR.
#       This option only sets the $OPTION string.

processInstallOptions(){

        
    if [ "$COPY_FLAG" = "1" ] ; then         
        OPTION=""
        SRC_DIR=""
        SRC_OPTION_FOUND=0
        while getopts S:T:C:A:R:aehv OPT ; do
            case $OPT in
                S)  SRC_DIR="$OPTARG"
                OPTION="$OPTION -S $SRC_DIR"
                SRC_OPTION_FOUND=1
                ;;
                e)  # This option is for smart-update
                # If this option specified, setup will not redirect the questions to console
                # instead it will exit if TAG not found in response summary file
                #
                OPTION="$OPTION -e"
                ;;
                R)  
                OPTION="$OPTION -R $OPTARG"	        
	        ;;
                T)
                OPTION="$OPTION -T $OPTARG"
                ;;
                C)
                OPTION="$OPTION -C $OPTARG"
                ;;
                A)
                OPTION="$OPTION -A $OPTARG"
                ;;
                a)
                OPTION="$OPTION -a"
                ;;
                v)
                OPTION="$OPTION -v"
                ;;
                h)  printUsage
                exit 0
                ;; 
                *)  printUsage
                exit 0
                ;;               
            esac
        done
        #
        #Put the LANG value also in the option
        #
        if [ -z "$LANG" ] ; then
           LANG=C
        fi    
        OPTION="$OPTION -L $LANG"        
        cd $SCRIPT_DIR
        if [ $SRC_OPTION_FOUND -eq 0 ] ; then
            cd ..            
                SRC_DIR=`$CMD_PWD`/image
            cd $SCRIPT_DIR
            if [ -d "$SRC_DIR" ] ; then
                OPTION="$OPTION -S $SRC_DIR"
            fi
        fi
        
        #
        #Put a flag to pause before collapsing cmdtool or dtterm
        #
        if [ "$EXEC_FLAG" = "0" ] ; then
            OPTION="$OPTION -p"
        fi
     
    else    # really doing the work
        # Get command line parameters
        has_S=0
        has_T=0
        PAUSE_BEFORE_EXIT="false"
        
        while getopts L:R:S:T:C:A:vahep ARG ; do       
            temp_dir=`getPathName $OPTARG`
            
            case $ARG in
                L)  
                LANG="$OPTARG"
                export LANG
                ;;
                S)  SRC_DIR="$temp_dir"
                if [ ! -d "$SRC_DIR" ] ; then
                    $CMD_GETTEXT ''
                    $CMD_GETTEXT "Invalid directory: $SRC_DIR"
                    SRC_DIR=""
                else
                    has_S=1
                fi
                ;;
                e)  # This option is for smart-update
                # If this option specified, setup will not redirect the questions to console
                # instead it will exit if TAG not found in response summary file
                #
                flash_questions_to_console=0
                export flash_questions_to_console
                ;;
                T)  TARGET_DIR="$temp_dir"                
                has_T=1
                ;;
                C)  AUTOCONFIG_SAVEFILE=`getPathName $OPTARG`
                ;;
                A)  AUTOCONFIG_RUNFILE=`getPathName $OPTARG`                    
                ;;
                R)  RELOCATED_ROOT="$temp_dir"
	        if [ ! -d "$RELOCATED_ROOT" ]; then
		    $CMD_GETTEXT ''
		    $CMD_GETTEXT "Invalid directory: $RELOCATED_ROOT"
		    exit_SunMC
	        fi
	        RELOC_PARAM="-R $RELOCATED_ROOT" 
	        ;; 
                a)  AGENT_ONLY=1
                ;;
                v)  VERBOSE=ON
                ;;
                p) PAUSE_BEFORE_EXIT="true"
                ;;
                h)  printUsage
                exit 0
                ;;
                *)  printUsage
                exit 0
                ;;                 
            esac
        done
        if [ -n "$TARGET_DIR" ] ; then
            verifyTargetDirectoryAndGetBaseDir $TARGET_DIR
            if [ $? -eq 0 ]; then
                TARGET_DIR_WITHOUT_RELOC="$LOCAL_BASEDIR"
                TARGET_DIR=`getRelocPathName "$LOCAL_BASEDIR"`                
            else
                TARGET_DIR=""
            fi 
        fi
    fi    
}    


initializeTempDirectory() {
    set_temp_directory
    # Check if pwd is in $TMP_DIR
    # do not remove in that case
    pwdir=`$CMD_PWD`
    echo $pwdir | grep "^${TMP_DIR}" > /dev/null 2>&1
    if [ $? -ne 0 ] ; then
        remove_temp_directory
        create_temp_directory
    fi    
} 


#Check if CD will get locked if this script runs from its present location and
#if necessary, copy all scripts and locales to tmp location and call es-inst from there.

checkForCDLocking() {

    cd $SCRIPT_DIR
    set_copy_exec_flags 

#
#Here if COPY_FLAG = 1 then this script is called from
#CD. If EXEC_FLAG = 1 then it needs to exec cmdtool else
#it does not need to exec cmdtool.
#If COPY_FLAG = 0 then we dont need to set TEXTDOAMIN or
#TEXETDOMAINDIR at this time. But if COPY_FLAG = 1 then
#we need to set the TEXTDOMAIN and TEXTDOMAINDIR for the
#following messages related to copy of scripts to tmp dir.
#One thing to note here is if we exec es-inst, it carries
#all other env variables but not LANG. So we will have to
#pass LANG somehow.
#


    if [ $COPY_FLAG -eq 0 ] ; then
        cd $PREV_DIR
    else        
        echolog "You have called es-inst from the cd image."                
        if [ $EXEC_FLAG -eq 0 ] ; then
            multiline_echolog 'You must run Sun Management Center installation by using the\ncomplete path after changing directory to /.'
            exit_SunMC $DISPLAY_ERROR
        fi
        copySbinLocale
        processInstallOptions $@ 2>/dev/null
        cd ${TMP_DIR}/sbin
        commandline=`$CMD_ECHO "exec ${TMP_DIR}/sbin/es-inst $OPTION"`
        $commandline         
        exit
    fi
}


check_if_called_from_installed_place() {
    checkString "$SCRIPT_DIR" "SUNWsymon/sbin"
    [ $? -eq 0 ] && return 0    
    return 1
}


check_if_called_from_disk_image() {
#
#This function returns 0 if being called from disk image
#else, it returns 1.
#
    if [ ! -d "${DOTPREFIX}../../disk1/${IMGPREFIX}/image" ]; then
       if [ -d "../../disk1/image" ]; then
           # this is for agent update
           # Image tool does not create x86 dir
           # Install Client does not know x86 dir
           # This should be reverted back if we decide to create generic image
           OLDIMGPREFIX=${IMGPREFIX}
           OLDDOTPREFIX=${DOTPREFIX}
           DOTPREFIX=""
           IMGPREFIX=""
           return 0
       fi
       return 1
    else
       return 0
    fi

}


check_if_userdirisin_cdromfilesystem() {
#
#This function returns 0 if the users shell dir is not
#in the cdrom path. Else it returns 1.
#
    mountpoint=`$CMD_DIRNAME "$SCRIPT_DIR"`
    checkString "$PREV_DIR" "$mountpoint"
    [ $? -eq 0 ] && return 1
    return 0
}

#new
set_copy_exec_flags() {
    COPY_FLAG=0
    EXEC_FLAG=0
    check_if_called_from_disk_image 
    if [ $? -ne 0 ] ; then
        # not called from disk image
        check_if_called_from_installed_place 
        if [ $? -ne 0 ] ; then
            #Not called from installed place
            #Assume that it is being called from CD
            #
            if [ -d "../image" ] ; then
                COPY_FLAG=1
                check_if_userdirisin_cdromfilesystem
                if [ $? -eq 0 ] ; then
                    EXEC_FLAG=1
                else
                    EXEC_FLAG=0
                fi
            fi
        fi    
    fi
    
}

checkDiskImage() {

    [ ! -d "${SRC_DIR}/${DOTPREFIX}../../disk1/${IMGPREFIX}/image" ] && return
    getLastCD
    [ "$LAST_CD" = "1" -o -z "$LAST_CD" ] && return 
    #1st disk is checked anyway
    
    disk_number=1
    prev_dir=`$CMD_PWD`
    while [ "$disk_number" != "$LAST_CD" ] ; do
      disk_number=`$CMD_EXPR $disk_number + 1`   
      if [ -d "${SRC_DIR}/${DOTPREFIX}../../disk${disk_number}/${IMGPREFIX}/image" ] ; then
          path=`getPathName ${SRC_DIR}/${DOTPREFIX}../../disk${disk_number}/${IMGPREFIX}/image`
          cd $path 2> /dev/null
          if [ $? -ne 0 ] ; then          
              echolog 'The install directory $2 is not accessible.' "$path"
              echolog 'You may encounter some difficulty during Add-On installation.'
              continueAfterConfirm
          fi
          cd $prev_dir 2> /dev/null
      else
          echolog 'The install directory for disk $2 can not be found.' "$disk_number"
          echolog 'You may encounter some difficulty during Add-On installation.' 
          continueAfterConfirm
      fi
    done
}

#new
copySbinLocale() {     
        
    $CMD_MKDIR -m 700 -p ${TMP_DIR}/sbin >> /dev/null
    if [ $? -ne 0 ] ; then
        echolog 'Can not create the directory $2' "${TMP_DIR}/sbin"
        EXIT_FLAG=$TMP_DIR_ERROR
        exit_SunMC
    fi
    $CMD_CP -Rf $SCRIPT_DIR/* ${TMP_DIR}/sbin/
    if [ $? -ne 0 ] ; then
        echolog 'Can not copy the required files to $2' "${TMP_DIR}/sbin"
        EXIT_FLAG=$TMP_DIR_ERROR
        exit_SunMC
    fi
    
    $CMD_MKDIR -m 700 -p ${TMP_DIR}/lib/sbin
    if [ $? -ne 0 ] ; then
        echolog 'Can not create the directory $2' "${TMP_DIR}/lib"
        EXIT_FLAG=$TMP_DIR_ERROR
        exit_SunMC
    fi
    $CMD_CP -Rf $TOOLS_DIR/* ${TMP_DIR}/lib/sbin/
    if [ $? -ne 0 ] ; then
        echolog 'Can not copy the required files to $2' "${TMP_DIR}/lib"
        EXIT_FLAG=$TMP_DIR_ERROR
        exit_SunMC
    fi

    if [ -z "$LOCALE_DIRECTORY" ] ; then
        $CMD_GETTEXT "Can not find the locale directory\n"
        exit
    else
        $CMD_MKDIR -m 700 -p ${TMP_DIR}/locale
        if [ $? -ne 0 ] ; then
            echolog 'Can not create the directory $2' "${TMP_DIR}/locale"
            EXIT_FLAG=$TMP_DIR_ERROR
            exit_SunMC
        fi
    
        $CMD_CP -Rf $LOCALE_DIRECTORY/* ${TMP_DIR}/locale/
        if [ $? -ne 0 ] ; then
            echolog 'Can not copy the required files to $2' "${TMP_DIR}/locale"
            EXIT_FLAG=$TMP_DIR_ERROR
            exit_SunMC
        fi
        TEXTDOMAINDIR=${TMP_DIR}/locale
        export TEXTDOMAINDIR
    fi
}

setLocales() {
    
    curr_wd=`$CMD_PWD`     
    cd $SCRIPT_DIR     
    if [ -d "../image" ] ; then         
         SRC_DIR=`getPathName ../image`  
         LOCALE_CONFIG_FILE="$SRC_DIR/${BASE_PRODUCT_DIR}/.locales" 
    fi
    cd $curr_wd
    
    check_for_l10n
    
    LOCALE_CODE="$L10N_CODE"    
    [ "$LOCALE_CODE" = "en" ] && LOCALE_CODE="C" 
    
    getLocaleDir
    setup_textdomain
    
    check_root

}




performChecksAndInitializations() {  
  
    [ -z "$LOCALE_DIRECTORY" ] && setLocales    
    
    [ -z "$TMP_DIR" ] && create_temp_directory
    
    set_commondirs "$RELOCATED_ROOT"    
        
    checkInstallDirectory "$VAROPTDIR"
    
    [ -f "${VAROPTDIR}/.java_home" ] && $CMD_RM "${VAROPTDIR}/.java_home"

    # If the LOGFILE variable is already set then don't reset the same.
    # this can possibly happen when this function is getting called
    # by the gui installation. 

    if [ -z  "$LOGFILE" ] ; then
        check_logfile "install"       
    else 
        export LOGFILE
    fi
 
    displayWelcomeMessage      

    [ -n "$AUTOCONFIG_RUNFILE" ] || [ -n "$AUTOCONFIG_SAVEFILE" ] && setup_response_summary
    if [ -z "${SETUP_AGENTUPDATE_FLAG}" ]; then
	# Normal install
        IMGPREFIX=${OLDIMGPREFIX}
	DOTPREFIX=${OLDDOTPREFIX}
    fi
    PRTOUT=`$CMD_UNAME -i`
    if [ -f /usr/platform/"$PRTOUT"/sbin/prtdiag ] ; then
        PRTOUT=`/usr/platform/"$PRTOUT"/sbin/prtdiag | $CMD_HEAD -1 | $CMD_CUT -f2 -d:`      
    fi 
    
    if [ -n "$RELOCATED_ROOT" -a "$RELOCATED_ROOT" != "/" ]; then
        OSVERS=`$CMD_UNAME -r`
        echolog ''
        multiline_echolog 'For installing Sun Management Center on $2, we need to know the\noperating system on $3. This should be the output of the command\n/usr/bin/uname -r. The command must be executed on a machine booted with\nthe disk mounted on $4' "$RELOCATED_ROOT" "$RELOCATED_ROOT" "$RELOCATED_ROOT"
        echolog ''
        READ_RESPONSE_ONCE=0
        fetch_response_text "TAG=OSVERS" 'Enter the OS version for \\\"$3\\\" \\\[ $4 \\\]: ' "$RELOCATED_ROOT" "$OSVERS"
        [ "$answer" != "" ] && OSVERS="$answer"
        case $OSVERS in
	    5.5.1*) OSVERS=5.5.1 ;;
	    2.5*)   OSVERS=5.5.1 ;;
	    5)      OSVERS=5.5.1 ;;
	    5.6*)   OSVERS=5.6   ;;
	    2.6*)   OSVERS=5.6   ;;
	    6)      OSVERS=5.6   ;;
	    5.7*)   OSVERS=5.7   ;;
	    2.7*)   OSVERS=5.7   ;;
	    7)      OSVERS=5.7   ;;
	    5.8*)   OSVERS=5.8   ;;
	    2.8*)   OSVERS=5.8   ;;
	    8)      OSVERS=5.8   ;;
	    5.9*)   OSVERS=5.9   ;;
	    2.9*)   OSVERS=5.9   ;;
	    9)      OSVERS=5.9   ;;	    
	    5.10*)   OSVERS=5.10   ;;
	    2.10*)   OSVERS=5.10   ;;
	    10)      OSVERS=5.10   ;;	    
	    *)      echolog ''
		    echolog 'Unsupported OS version: $2' "$OSVERS"
	            exit_SunMC "$OS_ERROR"         ;;
        esac
        
        if [ "$OSVERS" = "5.10" ]; then    #added to set s10 bits
            OSVERS_BITS="10"
        else
            OSVERS_BITS="other"
        fi


        checkOSVersion "$OSVERS"        
        
        echolog ''
        multiline_echolog 'For installing Sun Management Center on $2, we need to know\nthe type of machine whose root filesystem is or will be mounted\non $3. This should be the output of the following command where\nPLATFORM is the output of /usr/bin/uname -i' "$RELOCATED_ROOT" "$RELOCATED_ROOT"
        echolog '    /usr/platform/PLATFORM/sbin/prtdiag \\\| /usr/bin/head -1 \\\| $CMD_CUT -f2 -d:'
        echolog 'The above commands must be executed on the target machine.'
        echolog '' 
        READ_RESPONSE_ONCE=0
        fetch_response_text "TAG=PRTOUT" 'Enter the platform for \\\"$3\\\" \\\[ ${PRTOUT} ]: ' "$RELOCATED_ROOT"
        [ "$answer" != "" ] && PRTOUT="${answer}"    
        echolog ''
        multiline_echolog 'If you are planing to install Sun Management Center Server component on\n$2, before proceeding further, you must ensure that Sun Management Center\ndatabase user and group exist on target machine. To create database\nuser and group, execute the following commands on target machine.\n' "$RELOCATED_ROOT"
        echolog '1. /usr/sbin/groupadd smcorag'
        echolog '2. /usr/sbin/useradd -d /var/opt/SUNWsymon/smcorau -m -g smcorag -s /bin/sh smcorau '
        echolog ''
        if [ -z "$AUTOCONFIG_RUNFILE" ] ; then
           echolog 'Press RETURN to proceed with the installation...'
           $CMD_READ pause
        fi                     
    else
        checkOSVersion           
    fi
    
    saveAutoConfig "OSVERS" "$OSVERS"
    saveAutoConfig "PRTOUT" "$PRTOUT" 

    $CMD_LOCALE > $LOGDIR/env_file
    $CMD_ECHO "OS_VERSION=$OSVERS" >> $LOGDIR/env_file
    $CMD_ECHO "OS_DIR=Solaris_$OSVERS" >> $LOGDIR/env_file

}

getGlobalDir() {        
    temp_dir="/global/SUNWsymon"
    READ_RESPONSE_ONCE=0
    while [ 1 ] ; do    
        fetch_response_text "TAG=GLOBAL_DIR" 'Enter the global file system to link $3 : [ $4 ]' "$VAROPTDIR" "$temp_dir"
        #[ "$?" = "$SUMMARY_READ_ERROR" ] && EXIT_FLAG=$BAD_TARGET_DIR && exit_SunMC            
        [ -z "$answer" ] && answer="$temp_dir"
        GLOBAL_DIR=`getPathName "$answer"`
        
        if [ ! -d "$GLOBAL_DIR" ] ; then
            echolog 'Invalid: $2 . You must specify a valid directory.' "$GLOBAL_DIR"
        else
            #GLOBAL_DIR is a directory
            #check if VAROPTDIR already points to GLOBAL_DIR
            tmp_global=`$CMD_LS -ld $VAROPTDIR | awk '{print $NF}'`
            tmp_global=`getPathName "$tmp_global"`
                
            if [ "$tmp_global" != "$GLOBAL_DIR" ] ; then
                 #directory / old link to something else. Old data???
                [ -d "/var/opt/SUNWsymon_tmp" ] && $CMD_RM -rf "/var/opt/SUNWsymon_tmp"
                echolog 'Creating link'
                $CMD_MV $VAROPTDIR "/var/opt/SUNWsymon_tmp"                    
                $CMD_LN -s $GLOBAL_DIR $VAROPTDIR                                                        
                if [ -d "/var/opt/SUNWsymon_tmp" ] ; then
                   $CMD_CP -R /var/opt/SUNWsymon_tmp/* $VAROPTDIR
                   $CMD_RM -rf "/var/opt/SUNWsymon_tmp"
                fi     
            fi
            checkInstallDirectory $GLOBAL_DIR
            [ $? -eq 0 ] && break            
        fi                   
    done
    saveAutoConfig GLOBAL_DIR $GLOBAL_DIR
}



getLocaleDir() 
{
     LOCALE_DIRECTORY=""
     
     #     
     #If called from disk image, SRC_DIR should be set by now. 
     #
           
     if [ -n "$SRC_DIR" -a "$SOURCE_IMAGE" != "ADDON_ONLY" ] ; then
         #         
         #Either called from CD (copied to tmp area), or es-inst
         #called with -S option from installed place.
         #In either case, its OK to set locale directory to
         #$SRC_DIR/${BASE_PRODUCT_DIR}/<whatever>/locale. 
         #

         getCorrectDirectory "locale"
         if [ $? -eq 1 ] ; then
             LOCALE_DIRECTORY=`getPathName $CORRECT_DIR`
             return 0
         else
             return 1
         fi        
     fi

     #
     #Called from installed place. We should use already installed message
     #objects. This will be messages for installation. 3.5 onwards, all the
     #messages will be installed in /opt area.
     #
     $CMD_PKGINFO -qi SUNWescom 2>/dev/null
     [ $? -ne 0 ] && return 1
     optdir="`$CMD_PKGINFO -r SUNWescom`/SUNWsymon"
     LOCALE_DIRECTORY="$optdir/lib/locale"
     return 0

}



#check if all wbsvr packages are installed
# return 0 - all required packages are installed
# return 1 - one or more packages are not installed
# return 2 - possible version mismatch
# WEBSERVER_BASEDIR - BASEDIR for SUNWtcatu, if returning 0
# WBSVR_PKGLIST_TO_INSTALL - list of packages, if returning 1
#
#
checkWebserverInstallRequired() {
    retval=0
    REQUIRED_SPACE_WBSVR=0

    WBSVR_SRC_DIR="${SRC_DIR}/Webserver/Solaris_${OSVERS}"    
    if [ -d $WBSVR_SRC_DIR ] ; then
        WBSVR_PKGLIST=`$CMD_LS $WBSVR_SRC_DIR` 
    else
        WBSVR_PKGLIST="SUNWtcatr SUNWtcatu" # Hardcoded in case Add-On Only image.
    fi
    WBSVR_PKGLIST=`$CMD_ECHO "$WBSVR_PKGLIST" | $CMD_SED "s/\\n/ /g"`
    WBSVR_PKGLIST_TO_INSTALL=""

    # First check if hte tomcat is installed. In case it is installed
    # check the version if found that tomcat is installed.
    #

    isWebserverPresent=0
    $CMD_PKGINFO $RELOC_PARAM -qi SUNWtcatu
    if [ $? -eq 0 ] ; then
        TC_VERSION=`$CMD_PKGPARAM SUNWtcatu VERSION | $CMD_AWK '{print $NF}'`
        major=`$CMD_ECHO $TC_VERSION | $CMD_CUT -d"." -f1`
        minor=`$CMD_ECHO $TC_VERSION | $CMD_CUT -d"." -f2`
        # If the version string is of 11.8 form then we have 
        # older tomcat. 
        if [ $major -eq 11 -a $minor -eq 8 ] ; then
           isWebserverPresent=1
        else
           isWebserverPresent=2
        fi
    fi
    
    #first check if any packages are missing
    for WBSVR_PKG in `$CMD_ECHO "$WBSVR_PKGLIST" | $CMD_AWK 'BEGIN{RS=" "} {print}'`
    do       
        if [ $isWebserverPresent -eq 0 ] ; then 
            $CMD_PKGINFO $RELOC_PARAM -qi "$WBSVR_PKG"    
            if [ $? -ne 0 ] ; then
                retval=1
                if [ -d $WBSVR_SRC_DIR ] ; then
                    required_space=`getPackageSize "${WBSVR_SRC_DIR}/${WBSVR_PKG}"` 
                    required_space=`$CMD_EXPR $required_space`           
                    REQUIRED_SPACE_WBSVR=`$CMD_EXPR $required_space + $REQUIRED_SPACE_WBSVR`
                else
                    REQUIRED_SPACE_WBSVR=0 #As no webserver packages are available for install                
                fi
                if [ -z "$WBSVR_PKGLIST_TO_INSTALL" ] ; then
                    WBSVR_PKGLIST_TO_INSTALL="$WBSVR_PKG"
                else   
                    WBSVR_PKGLIST_TO_INSTALL="${WBSVR_PKGLIST_TO_INSTALL},$WBSVR_PKG"
                fi
            fi        
        elif [ $isWebserverPresent -eq 1 ] ; then # we will just add the disk space required.
            retval=1
            if [ -d $WBSVR_SRC_DIR ] ; then
                required_space=`getPackageSize "${WBSVR_SRC_DIR}/${WBSVR_PKG}"`
                required_space=`$CMD_EXPR $required_space`
                REQUIRED_SPACE_WBSVR=`$CMD_EXPR $required_space + $REQUIRED_SPACE_WBSVR`
            else
                REQUIRED_SPACE_WBSVR=0 #As no webserver packages are available for install
            fi
            if [ -z "$WBSVR_PKGLIST_TO_INSTALL" ] ; then
                WBSVR_PKGLIST_TO_INSTALL="$WBSVR_PKG"
            else
                WBSVR_PKGLIST_TO_INSTALL="${WBSVR_PKGLIST_TO_INSTALL},$WBSVR_PKG"
            fi
        else # Tomcat is found but is of some unknown version. Leave it as is but log a message
            retval=2 
        fi
      
    done
    
    return $retval
}

checkJavaHelpInstallRequired() {
    # Check to see of JavaHelp * SUNWjhrt" already exists.
    JAVAHELP_PKGS="SUNWjhrt SUNWjhdev SUNWjhdoc SUNWjhdem"
    $CMD_PKGINFO $RELOC_PARAM -qi SUNWjhrt
    ret=$?
    if [ $ret -ne 0 ] ; then
        return $ret
    fi
   javaHelpRequired=`versionString2Num 2.0`
    # If it does, then check if version less than 2.0. If less than 2.0 then
    # we need to upgrade. If not then return 0 to indicate NO JavaHelp install
    # needed.
    retValue=0
    version=`env LANG=C LC_ALL=C $CMD_PKGPARAM $RELOC_PARAM SUNWjhrt VERSION | $CMD_AWK -F. '{print $1}'`
 
    weHave=`versionString2Num $version`
    # if the pkg instance we have is less than 2.0
    # remove the package

    if [ ${weHave} -lt ${javaHelpRequired} ]; then
        retValue=1
    else
       JAVAHELP_HOME=`$CMD_PKGINFO  $RELOC_PARAM -r SUNWjhrt`
       JAVAHELP_HOME=$JAVAHELP_HOME/j2se/opt/javahelp
       export JAVAHELP_HOME
    fi
    if [ $retValue -eq 1 ] ; then
         JAVAHELP_SRC_DIR="${SRC_DIR}/Lockhart2.2.3/$ARCH"
         for pkg in `$CMD_ECHO $JAVAHELP_PKGS`
         do
             required_space=`getPackageSize "$JAVAHELP_SRC_DIR/Common/$pkg"`
             required_space=`$CMD_EXPR $required_space`
             REQUIRED_SPACE_WBSVR=`$CMD_EXPR $required_space + $REQUIRED_SPACE_WBSVR`
         done
    fi
    return $retValue
}


checkSunWebconsoleInstallRequired() {

    retval=0
    $CMD_PKGINFO -qi SUNWmcon
    ret=$?
    if [ "$ret" = "0" ] ; then
        # Since we have Lockhart installed, check to see
        # if the same is of version expected. If not then
        # return error condition.
        SMCWEBSERVER=/usr/sbin/smcwebserver
        if [ ! -x $SMCWEBSERVER ]; then
            SMCWEBSERVER=/usr/sadm/bin/smcwebserver
        fi
        if [ -x $SMCWEBSERVER ]; then
            version=`$SMCWEBSERVER --version | $CMD_AWK '{print $NF}'`
            version=`$CMD_ECHO $version | $CMD_CUT -d"-" -f1`
            major=`$CMD_ECHO $version | $CMD_CUT -d"." -f1`
            minor=`$CMD_ECHO $version | $CMD_CUT -d"." -f2`
            micro=`$CMD_ECHO $version | $CMD_CUT -d"." -f3`
	    #
	    # Upgrade if 1.0 or less than 2.2.3 Return otherwise
	    # that is when a higher version is already installed
	    # If its equal to 2.2.3 then check if all packages from
	    # the list are installed correctly, therefore, don't return
	    # a 1/0 from the second else if block
	    #
	    if [ -n "$major" -a -n "$minor" ]; then
		if [ $major -lt 2 ]; then
	             return 1
		elif [ $major -eq 2 -a $minor -lt 2 ]; then 
                     return 1  
		elif [ $major -eq 2 -a $minor -eq 2 ]; then 
			if [ -z "$micro" ]; then
				return 1
			elif [ $micro -lt 3 ]; then
				return 1
			elif [ $micro -ge 3 ]; then
				return 0
			fi
		elif [ $major -ge 3 ]; then
			return 0
		fi
	    fi
        fi
    fi
    return 1 
}

# << END initializations<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #


# << BEGIN LIST related functions<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #

#function getProductAttr
#      $1 LIST = any list of products, containing fields in the form of 
#                 "KEY=value1#ATTR1=value2..@KEY=value3#ATTR1=value4..@KEY=value5#ATTR1=value6.."
#      $2 KEY  = key of the product which we want some value
#      $3 ATTR = attribute name which is wanted
#
# Return: echoes the value of the specified attribute of the specified product
#
getProductAttr() {
    list=$1
    key=$2
    attr=$3
    
    #
    # this means : 
    # "s/^${match_anything}KEY='$key'#${not_end_of_record}*'$attr'=\(${not_end_of_field}*\)${match_anything}$/\${first_grabbed}/p"
    #  

    $CMD_ECHO $list | $CMD_SED -n 's/^.*KEY='$key'#[^@]*'$attr'=\([^#@]*\).*$/\1/p' 
    
#
}

#
# $1 list
#Return: echoes all key values seperated by spaces
#
getKeys() {
    list=$1
    $CMD_ECHO $list | $CMD_AWK -F [#=] 'BEGIN {RS="@"} /KEY/ {print $2}'  
}


# $1 list        - into which prod_string has to be inserted
# $2 match_key   - KEY of product to be replaced
# $3 prod_string - new Attr=values string to add to product.
#
addAttributesToProduct() {
list=$1
match_key=$2
add_string=$3
tmp_list=""

OLD_IFS=$IFS
IFS=@
for each_product in $list ; do
    prod_key=`$CMD_ECHO $each_product | cut -d# -f1 | cut -d= -f2`
    if [ "$match_key" = "$prod_key" ] ; then
        if [ -z "$tmp_list" ] ; then
            tmp_list="${each_product}#${add_string}"
        else
            tmp_list="${tmp_list}@${each_product}#${add_string}"
        fi
    else
        if [ -z "$tmp_list" ] ; then
            tmp_list=${each_product}
        else
            tmp_list="${tmp_list}@${each_product}"
        fi
    fi
done
IFS=$OLD_IFS

$CMD_ECHO $tmp_list

}


# $1 match_key  - KEY of product to be copied
# $2 s_list     - list from which the product should be taken
# $3 d_list     - list into which the product has to be inserted. 
#                 If null, its a fresh list.
#
copyProduct() {
match_key=$1
s_list=$2
d_list=""
[ -n "$3" ] && d_list=$3

OLD_IFS=$IFS
IFS=@
for prod in $s_list ; do
s_key=`$CMD_ECHO $prod | cut -d# -f1 | cut -d= -f2`
    [ "$s_key" != "$match_key" ] && continue
   
    if [ -z "$d_list" ] ; then
        d_list=${prod}
    else
        d_list="${d_list}@${prod}"
    fi
done
IFS=$OLD_IFS
$CMD_ECHO $d_list
}



# << END LIST related functions<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #




# << BEGIN miscellaneous functions<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #

continueAfterConfirm() {
    [ "$AUTOCONFIG_RUNFILE" != "" ] && return
    $CMD_ECHO "    \c"
    ask_user 'Do you want to proceed '
    echolog ''
    if [ $answer -eq 0 ] ; then
    exit_SunMC
    fi
}

userConfirmation() {
    echolog 'The installation will now exit. Press RETURN to exit.'
    echolog ''
    read some_answer
}


# Exit the program
exit_SunMC_install() {
    
    if [ "$ADMIN" != "" ] ; then
        $CMD_ECHO "Admin File Contents:" >> "$LOGFILE"
        $CMD_CAT "$ADMIN" >> "$LOGFILE"  2>&1        
    fi
    
    echolog ''
    echolog 'Exiting Sun Management Center installation.'
    echolog ''
        
    [ -n "$1" ] && EXIT_FLAG=$1   
    if [ "$EXIT_FLAG" != "$NO_ERROR" -a -n "$EXIT_FLAG" ] ; then        
        error_file="${TOOLS_DIR}/script-errors.sh"
        error_val=`$CMD_CAT "$error_file" | $CMD_AWK -F= '/'$EXIT_FLAG'/ {print $1}'`
        if [ -n "$error_val" ] ; then
            echologverbose 'Exit value corresponds to $2' "$error_val"
        else
            echologverbose 'Exit value is $2' "$EXIT_FLAG"
        fi    
    fi
    [ -d "$TMP_DIR" ] && cd / && $CMD_RM -rf $TMP_DIR > /dev/null 2>&1

    if [ "$PAUSE_BEFORE_EXIT" = "true" ] ; then
        if [ -z "$AUTOCONFIG_RUNFILE" ]; then 
          $CMD_SLEEP 5                
        fi
    else
        $CMD_SLEEP 2 
    fi  
   
    exit $EXIT_FLAG 
    
}


# Copy locale files
# $1 - Directory above locale
copyLocaleFiles() {
    #
    #first copy from Source image
    #
    if [ -d  "${1}/Solaris_${OSVERS}/locale" ] ; then
        DIR="${1}/Solaris_${OSVERS}/locale"
    elif [ -d "${1}/Common*/locale" ] ; then
        DIR="${1}/Common*/locale"
        DIR=`getPathName $DIR`
    else
        DIR="${1}/locale" ## could just be a 2.x addon
    fi    
    for lang in `$CMD_ECHO "$INSTALL_LOCALES" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
    do        
        if [ -d "$DIR/$lang" ] ; then
            $CMD_MKDIR -p $VAROPTDIR/locale/$lang > /dev/null 2>&1
            $CMD_CP -rf $DIR/$lang/* $VAROPTDIR/locale/$lang > /dev/null 2>&1
            if [ $? -ne 0 ] ; then
                echolog ''
                echolog 'Error copying the locale files to: $2' "$VAROPTDIR/locale/$lang"
                echolog 'Script will use English.'
                echolog ''
            fi
        fi
    done    
}


# Gets the package version
# $1 = absolute package directory
# Returns: $PACKAGE_VERSION
getPackageVersion() {
    PACKAGE_VERSION=""
    if [ ! -d "$1" ] || [ ! -f "$1/pkginfo" ] ; then
	PACKAGE_VERSION="??"
	return
    fi

    PACKAGE_VERSION=`$CMD_PKGPARAM -f "$1/pkginfo" SUNW_PRODVERS`
}

# Checks whether a package exists on the host
# $1 - package name
# Return: 0 = does not exist; 1 = exist and versions matched; 2 = exist and versions not matched
packageExists() {
    $CMD_PKGINFO $RELOC_PARAM -qi "$1"
    if [ $? -ne 0 ] ; then
        return 0
    else # Exists
        # Check package version
        SADM_PKG=`getRelocPathName "/var/sadm/pkg"`
        getPackageVersion "$SADM_PKG/$1"    
        ipkg="$PACKAGE_VERSION"
        getPackageDirectory "$1" 
        [ $? -eq 0 ] && return 0
        getPackageVersion "$PACKAGE_DIR"
        spkg="$PACKAGE_VERSION"
        [ "$ipkg" = "$spkg" ] && return 1 # Version matched
        return 2
    fi
}

# Checks if the packages have already been installed.

# $1 - packages list
# Return: 0 for false; 1 if versions matched; 2 if versions not matched
packagesExist() {
    INSTALLED_PKGS=""
    MATCH_VERSION=1
    for pkgname in `$CMD_ECHO "$1" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
    do
    # Check for existence
    packageExists "$pkgname"
    ret="$?"
    [ $ret -eq 0 ] && return 0
    [ $ret -eq 2 ] && MATCH_VERSION=0
    if [ "$INSTALLED_PKGS" = "" ] ; then
        INSTALLED_PKGS="$pkgname"
    else
        INSTALLED_PKGS="${INSTALLED_PKGS}, $pkgname"
    fi
    done

    if [ $MATCH_VERSION -eq 1 ] ; then
    return 1
    else
    return 2
    #here ipkg and spkg are set
    fi
}

# Set up package admin files
setAdminFiles() {

    DATE_FORMAT=`eval echo "+\\\%y\\\%m\\\%d\\\%H\\\%M\\\%S"`
    TIMESTAMP=`$CMD_DATE $DATE_FORMAT`
    DEFADMIN="${LOGDIR}/defadminfile.$TIMESTAMP.$$"
    $CMD_CAT << !EOF > "$DEFADMIN"
mail=
instance=overwrite
partial=nocheck
runlevel=nocheck
idepend=nocheck
rdepend=nocheck
space=nocheck
setuid=nocheck
conflict=nochange
action=nocheck
basedir=default
!EOF

    DATE_FORMAT=`eval echo "+\\\%y\\\%m\\\%d\\\%H\\\%M\\\%S"`
    TIMESTAMP=`$CMD_DATE $DATE_FORMAT`
    ADMIN="${LOGDIR}/adminfile.$TIMESTAMP.$$"
    $CMD_TOUCH "$ADMIN"
}




# << END miscellaneous functions<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #



# << BEGIN actual install of all functions<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #

installExternalPackages() {
    
    [ "$SOURCE_IMAGE" = "PATCH_ONLY" ] && return
    [ "$SOURCE_IMAGE" = "ADDON_ONLY" ] && return
    
    checkString "$INSTALL_LAYERS" "LAYER.SERVER" 
    [ $? -eq 1 ] && return    
    
    #server layer installed / selected for install
    echologverbose ''
    echologverbose 'Validating Oracle and Webserver installation...'
    echologverbose ''
    
    validateDatabaseInRegistry        
    checkWebserverInstallRequired
    [ $? -eq 1 ] && INSTALL_WEBSERVER=1

    checkSunWebconsoleInstallRequired
    [ $? -eq 1 ] && INSTALL_LH_WEBCONSOLE=1

     checkJavaHelpInstallRequired
    [ $? -eq 1 ] && INSTALL_JAVAHELP=1

    [ $INSTALL_DB -eq 0 -a $INSTALL_WEBSERVER -eq 0 -a $INSTALL_LH_WEBCONSOLE -eq 0 -a $INSTALL_JAVAHELP -eq 0 ] && return
    
    setAdminFiles
    
    if [ "$SOURCE_IMAGE" != "DEFAULT" ] ; then
        echolog 'It appears that the following essential packages are not present on your system:'
        [ $INSTALL_DB -eq 1 ] && echolog "    $DB_PKGLIST_TO_INSTALL"
        [ $INSTALL_WEBSERVER -eq 1 ] && echolog "    $WBSVR_PKGLIST_TO_INSTALL"
        echolog ''
        echolog 'Unrecoverable error.'
        exit_SunMC "$ESSENTIAL_PACKAGE_MISSING"
    fi
    
    if [ $INSTALL_DB -eq 1 ] ; then
        db_cmd="${TOOLS_DIR}/es-db"
        if [ -f "$db_cmd" ] ; then
            . "$db_cmd"
            [ -z "$DB_TABLES_DIR" ] && DB_TABLES_DIR="/var/opt/SUNWsymon"            
            installDB "${SRC_DIR}/db" "$TARGET_DIR_WITHOUT_RELOC" "$DB_TABLES_DIR" "$RELOCATED_ROOT" 
            [ $? -eq 0 ] && EXIT_FLAG=$ORACLE_INSTALLATION_FAILED && exit_SunMC # Oracle installation failed
        fi
    fi
    validateDatabaseInRegistry
 
    if [ $INSTALL_WEBSERVER -eq 1 ] ; then
        ws_cmd="${TOOLS_DIR}/es-webserver"
        if [ -f "$ws_cmd" ] ; then
            . "$ws_cmd"            
            installWebserver "$RELOCATED_ROOT"
            [ $? -eq 0 ] && EXIT_FLAG=$WEBSERVER_INSTALLATION_FAILED && exit_SunMC # Webserver installation failed                    
        fi
    fi 


   #Source es-lhwebconsole if needed ; to install javahelp or lockhart
   if [ "$INSTALL_JAVAHELP" = "1"  -o "$INSTALL_LH_WEBCONSOLE" = "1" ] ; then 
        ws_cmd="${TOOLS_DIR}/es-lhwebconsole"
        if [ -f "$ws_cmd" ] ; then
            . "$ws_cmd"
         fi
    fi

    # Install Javahelp if required.
 
    if [ "$INSTALL_JAVAHELP" = "1" ] ; then 
        installJavaHelp
        ret=$?
        if [ $ret -eq 0 ] ; then
           echo "Installed Java help correctly"
        else
           echo "Could not install JavaHelp2.0"
        fi
     fi


    # Install lockhart. Check that it is
    # not a relocation and then install.
    # Lockhart setup doesn't have any
    # relocation support hence this
    # limitation
    #
    if [ "$INSTALL_LH_WEBCONSOLE" = "1" ] ; then
       installWebconsole
       ret=$?
       if [ "$ret" = "0" ] ; then
          if [ "$INSTALL_LH_WEBCONSOLE" = "1" ] ; then
                $API_SET_ATTRIBUTE "$REGISTRY" "category=Installation" "lockhart_installed=1" > /dev/null 2>&1
                $API_SET_ATTRIBUTE "$REGISTRY" "category=Installation" "lockhart_packages=${WBCONSOLE_INSTALLED_PKGLIST}" > /dev/null 2>&1
          fi
       else
          echolog "Sun Web Console was not completed successfully"
          echolog "Sun Management Center installation will now exit"
          EXIT_FLAG=$WEBSERVER_INSTALLATION_FAILED && exit_SunMC # Webserver installation failed
       fi
    fi





    $API_SET_ATTRIBUTE "$REGISTRY" "category=Installation" "webserver_basedir=$WEBSERVER_BASEDIR" >/dev/null 2>&1 
}



installComponents() {    
    
    [ "$SOURCE_IMAGE" = "PATCH_ONLY" ] && return

    [ -z "$INSTALL_KEYS" ] && return
    setAdminFiles
    
    echologverbose ''
    echologverbose 'Installing the components...'
    echologverbose ''
     
    for each_pkglist in `$CMD_ECHO "$SORTED_INSTALL_COMPONENTS_LIST"`
    do    
    PRODUCT_KEY=`$CMD_ECHO "$each_pkglist" | $CMD_AWK -F ':' '{ print $4 }'`
    COMPONENT_KEY=`$CMD_ECHO "$each_pkglist" | $CMD_AWK -F ':' '{ print $1 }'`
    tmp_cd=`$CMD_ECHO "$each_pkglist" | $CMD_AWK -F ':' '{ print $3 }'`
    tmp_last=`$CMD_ECHO "$each_pkglist" | $CMD_AWK -F ':' '{ print $5 }'`    
    each_pkglist=`$CMD_ECHO "$each_pkglist" | $CMD_AWK -F ':' '{ print $2 }'`                
    
    echologverbose '$2' $LOG_LINE
    
    comp_list=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=${PRODUCT_KEY}" "component" "key" 2>/dev/null`
    checkString "$comp_list" "$COMPONENT_KEY"
    [ $? -ne 0 ] && $API_INSERT_TAG "$REGISTRY" "category=SunMC" "product=${PRODUCT_KEY}" "component=${COMPONENT_KEY}" > /dev/null 2>&1
    
    patches_already=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=${PRODUCT_KEY}" "component=${COMPONENT_KEY}" "patches" > /dev/null 2>&1`
    if [ -z "$patch_already" ] ; then
        patch_list=`getProductAttr "$INIT_COMP_DETAILS" "$PRODUCT_KEY" "PATCHES_${COMPONENT_KEY}"`
        $API_SET_ATTRIBUTE "$REGISTRY" "category=SunMC" "product=${PRODUCT_KEY}" "component=${COMPONENT_KEY}" "patches-required=${patch_list}" > /dev/null 2>&1
    fi
    
    if [ "$PRODUCT_KEY" = "${BASE_PRODUCT_KEY}" ] ; then
        INSTALL_TYPE="BASE"          
    else
        INSTALL_TYPE="ADDON"                
    fi
    
    #now get into the component loops 
        echologverbose 'Installing... $PRODUCT_KEY $COMPONENT_KEY'
    
        for PKG_NAME in `$CMD_ECHO "$each_pkglist" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
        do
            packageExists "$PKG_NAME"
            ret=$?
            
            if [ $ret -eq 1 ] ; then                
                $CMD_ECHO "  \c"
                echolog 'Package $2 is already installed on this system.' "$PKG_NAME"
                echologverbose 'Validating the Registry entry.'
                package=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=${PRODUCT_KEY}" "component=${COMPONENT_KEY}" "package" "key" WHERE "key=${PKG_NAME}" 2>/dev/null`
                [ -z "$package" ] && $API_INSERT_TAG "$REGISTRY" "category=SunMC" "product=${PRODUCT_KEY}" "component=${COMPONENT_KEY}" "package=${PKG_NAME}" >/dev/null 2>&1
                $API_SET_ATTRIBUTE "$REGISTRY" "category=SunMC" "product=${PRODUCT_KEY}" "component=${COMPONENT_KEY}" "package=${PKG_NAME}" "status=1" >/dev/null 2>&1
                continue
            fi

            getPackageDirectory "$PKG_NAME"
            ret=$?
            if [ ! -d "${PACKAGE_DIR}/reloc" ] || [ $ret -eq 0 ] ; then
                checkCD "$tmp_cd" "$PKG_NAME"
            fi

            # Hardcoding package name in order to fix RFE: 4826819
            if [ "$PKG_NAME" = "SUNWpsmd" -o "$PKG_NAME" = "SUNWsmd" ]; then
              if [ "$CURRENT_CD" = "2" ]; then
                # Save old pkgname
                OLD_PKGNAME="$PKG_NAME"
                if [ -x "${TOOLS_DIR}/install-doc-pkg.sh" ]; then
                    #export SOURCE_LIST
                    export SRC_DIR
                    export ADMIN
                    ${TOOLS_DIR}/install-doc-pkg.sh
                fi
                # restore old pkgname
                PKG_NAME="$OLD_PKGNAME"
              fi
            fi

            pkginfo="${PACKAGE_DIR}/pkginfo"
            PKG_DIR=`$CMD_DIRNAME $PACKAGE_DIR`            
             
            pkg_def_base=`$CMD_PKGPARAM -f "$pkginfo" BASEDIR`
            installPackage "$pkg_def_base" "$PKG_DIR" "$PKG_NAME"
            
            package=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=${PRODUCT_KEY}" "component=${COMPONENT_KEY}" "package" "key" WHERE "key=${PKG_NAME}" 2>/dev/null`
                
            [ -z "$package" ] && $API_INSERT_TAG "$REGISTRY" "category=SunMC" "product=${PRODUCT_KEY}" "component=${COMPONENT_KEY}" "package=${PKG_NAME}" >/dev/null 2>&1
            $API_SET_ATTRIBUTE "$REGISTRY" "category=SunMC" "product=${PRODUCT_KEY}" "component=${COMPONENT_KEY}" "package=${PKG_NAME}" "status=0" >/dev/null 2>&1
            
            #
            #check if successful
            #            
            packageExists "$PKG_NAME"
            if [ $? -ne 1 ] ; then                
                echolog ''
                $CMD_ECHO "  \c"
                echolog 'Error installing package: $2' "$PKG_NAME"
                echolog ''
            
                if [ "$INSTALL_TYPE" = "BASE" ] ; then                
                    exit_SunMC "$BASE_PRODUCT_PKGADD_FAILED"
                else                
                    if [ -z "$FAIL_LIST" ] ; then
                        FAIL_LIST="KEY=${PRODUCT_KEY}#BECAUSE=packages"
                    else
                        checkString "$FAIL_LIST" "KEY=${PRODUCT_KEY}"
                        if [ $? -eq 1 ] ; then
                            FAIL_LIST="${FAIL_LIST}@KEY=${PRODUCT_KEY}#BECAUSE=packages" 
                        fi
                    fi
                fi
            else
                #successfully installed
                $API_SET_ATTRIBUTE "$REGISTRY" "category=SunMC" "product=${PRODUCT_KEY}" "component=${COMPONENT_KEY}" "package=${PKG_NAME}" "status=1" >/dev/null 2>&1        
            fi

            # to create s10 links
            if [ "$PKG_NAME" = "SUNWesaem" ]; then
                create_s10_links
            fi

            
            # condition added to reset OSVERS variable to "10"
            if [ "$PROGNAME" != "archive-tool" ]; then
                if [ "$OSVERS_BITS" = "" ]; then
                    OSVERS_CURRENT=`$CMD_UNAME -r`
                    if [ "$OSVERS_CURRENT" = "5.10" ]; then
                        OSVERS="10"
                    fi
                else
                    if [ "$OSVERS_BITS" = "10" ]; then
                        OSVERS="10"
                    fi
                fi
            fi

        done
        
        if [ -n "$tmp_last" ] ; then 
            installed=0
            checkString "$FAIL_LIST" "KEY=${PRODUCT_KEY}#BECAUSE=packages"
            if [ $? -eq 0 ] ; then                
                #check if none are installed
                t_packages=`$API_QUERY_REGISTRY "$REGISTRY" "product=$PRODUCT_KEY" "package" "key" 2>/dev/null`
                t_packages=`$CMD_ECHO $t_packages | $CMD_SED "s/,/ /g" 2>/dev/null`
                for each_instance in $t_packages ; do
                    $CMD_PKGINFO $RELOC_PARAM -qi $each_instance
                    if [ $? -eq 0 ] ; then
                        installed=1  #even if one package is installed, show that the product is installed.
                        break
                    fi  
                done
            else
                installed=1            
            fi
            
            $API_SET_ATTRIBUTE "$REGISTRY" "category=SunMC" "product=$PRODUCT_KEY" "install-status=${installed}" >/dev/null 2>&1
            
            if [ "$INSTALL_TYPE" = "ADDON" ] ; then
                tmp_src=`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" "SOURCE_DIR"`
                if [ "$COMPONENT_KEY" != "DEFAULT" ] ; then
                    copyLocaleFiles "${SRC_DIR}/Addons/${tmp_src}"
                else
                    copyLocaleFiles "${SRC_DIR}/Addons/SunMC2.X/Solaris_${OSVERS}/${tmp_src}"
                fi
            fi
        fi        
    done
       
    echolog ''      
}


# Installs a package
# $1 - pkg_def_base
# $2 - PKG_DIR
# $3 - PKG_NAME
installPackage() {
    if [ "$4" = "" ] ; then
        $CMD_PKGINFO $RELOC_PARAM -qi $3 > /dev/null 2>&1
        if [ $? -eq 0 ] ; then
            return 0
        fi
    fi
    if [ "$1" = "/" ] ; then
        tmp_dir1=""
        tmp_dir2=""
    else
        tmp_dir1=`$CMD_EXPR "$1" : '\(/opt\).*'`
        tmp_dir2=`$CMD_EXPR "$1" : '/opt\(.*\)'`
    fi
    PKGADD_PARAM=""
    if [ -z "$RELOCATED_ROOT" -o "$RELOCATED_ROOT" = "/" ]; then
	[ `${CMD_UNAME} -r` = "5.10" ] && PKGADD_PARAM="-G"
    fi
    if [ "$tmp_dir1" = "/opt" ] ; then
        if [ "$tmp_dir2" = "" ] ; then
            tmp_basedir="$TARGET_DIR_WITHOUT_RELOC"
        else
            tmp_basedir="${TARGET_DIR_WITHOUT_RELOC}$tmp_dir2"
        fi

        $CMD_CAT << !EOF > "$ADMIN"
mail=
instance=overwrite
partial=nocheck
runlevel=nocheck
idepend=nocheck
rdepend=nocheck
space=nocheck
setuid=nocheck
conflict=nochange
action=nocheck
basedir="$tmp_basedir"
!EOF
        $CMD_PKGADD $PKGADD_PARAM $RELOC_PARAM -a $ADMIN -d $2 $3 2>&1 | $CMD_TEE -a $LOGFILE
        ret=$?
    else
        $CMD_PKGADD $PKGADD_PARAM $RELOC_PARAM -a $DEFADMIN -d $2 $3 2>&1 | $CMD_TEE -a $LOGFILE
        ret=$?
    fi
    
    return $ret    
}



getCurrentCD() {
cd_file="${SRC_DIR}/../.CD"
if [ -f "$cd_file" ] ; then
    CURRENT_CD=`get_value_from_cfgfile "$cd_file" "CURRENT" "="`
    #CURRENT_CD=`$CMD_CAT $cd_file | $CMD_CUT -dO -f1`    
    CURRENT_CD=`$CMD_EXPR $CURRENT_CD`
else
    echologverbose 'WARNING: .CD file not found at $2' "$cd_file"
    CURRENT_CD=1 #default
fi
}

#update later to parse .CD file.
getLastCD() {
cd_file="${SRC_DIR}/../.CD"
if [ -f "$cd_file" ] ; then
    LAST_CD=`get_value_from_cfgfile "$cd_file" "LAST" "="`
    #LAST_CD=`$CMD_CAT $cd_file | $CMD_CUT -dF -f2`    
    LAST_CD=`$CMD_EXPR $LAST_CD`
else
    echologverbose 'WARNING: .CD file not found at $2' "$cd_file"
    LAST_CD=1 #default
fi
}

# Prompt for a CD change if required
# reads: COMPONENT_KEY
# $1 - the CD number
# $2 - the package name

checkCD() {
    check_cd=$1    
    tmp_package="$2"
    
    getLastCD

    [ "$check_cd" = "99" ] && check_cd=$LAST_CD
    check_cd=`$CMD_EXPR $check_cd`

    getCurrentCD

    [ "$check_cd" -eq "$CURRENT_CD" ] && [ -d "${PACKAGE_DIR}/reloc" ] && return 
    
    
    MSG=`getProductAttr "$COMP_NAMES" "$PRODUCT_KEY" "$COMPONENT_KEY"` 
while [ 1 -eq 1 ] ; do
    echologverbose 'Component \\\"$2\\\" resides on CD \\\#$3.' "$MSG" "$check_cd"
    if [ -d "${SRC_DIR}/${DOTPREFIX}../../disk${check_cd}/${IMGPREFIX}/image" ] ; then # Default CD 
        answer=`getPathName "${SRC_DIR}/${DOTPREFIX}../../disk${check_cd}/${IMGPREFIX}/image"`
        echologverbose 'New source directory: $2' "$answer"
    else
        cd /
        eject -q cd 2> /dev/null
        [ $? -eq 0 ] && eject cd 2> /dev/null
        if [ "$AUTOCONFIG_RUNFILE" != "" ] ; then # Run autoconfig
            tmp_auto=`getAutoConfig "CORE_DISK${check_cd}"`
            answer=$tmp_auto
        else
            tmp_auto="/cdrom/cdrom0/image"
            get_input_from_user 'Insert the CD or enter the source directory for disk $2 \\\[$3\\\]' "${check_cd}" "$tmp_auto"
        fi
    fi
    
    if [ -z "$answer" ] ; then
        answer=$tmp_auto
    else
        answer=`getPathName "$answer"`
    fi

    saveAutoConfig "CORE_DISK${check_cd}" "$answer"
    

    echologverbose 'New source directory: $2' "$answer"
        cd_count=0
        while [ 1 ]
        do
            sleep 1
            if [ -d "$answer" ] ; then
                break
            fi
            cd_count=`$CMD_EXPR $cd_count + 1`
            if [ $cd_count -ge 10 ] ; then
                echolog 'Invalid directory $2' "$answer"
                break
            fi
        done

    SRC_DIR="$answer"
    if  [ -d "$SRC_DIR" ]; then
        checkSourceDirArch $ARCH
        [ $? -ne 0 ] && continue 
    fi
    
    getPackageDirectory "$tmp_package"
    ret=$?
    
    if  [ ! -d "${PACKAGE_DIR}/reloc" ] || [ $ret -eq 0 ] ; then
        echo " "
        echo "    \c"    # align with continueAfterConfirm
                       # The message below is in .po file
        echolog '  Invalid source directory: $2' "$SRC_DIR"
        continueAfterConfirm 
    else
        break
    fi
done
    getCurrentCD    
 
}



#
# this function sets a list called INIT_PRODUCT_LIST_3X containing basic info about all 
# 3.X products under the source directory. The base product is also treated as an Addon.
#
readProductInfo() {
    
    COMPONENT_FILTERS_LIST="" 
    COMP_NAMES=""
    INIT_COMP_DETAILS=""
    start=0
    SOURCE_LIST=""
    LICENSE_AGREEMENTS_LIST=""
    ALL_OPTIONAL_COMPONENTS=""    

    put_var_in_cfgfile "${PROGRESS_FILE}" "PROCESS" "Found" "="

    addon_dir_list=`$CMD_LS "${SRC_DIR}/Addons"`
    addon_dir_list=`$CMD_ECHO "$addon_dir_list" | $CMD_SED "s/\\n/ /g"`
    [ "$SOURCE_IMAGE" = "DEFAULT" ] && addon_dir_list="${BASE_PRODUCT_DIR} ${addon_dir_list}"
    [ "$SOURCE_IMAGE" = "DEFAULT" ] && [ "$PROGNAME" = "archive-tool" ] && [ "$ARCHIVE_ADDON_FLAG" = "0" ] && addon_dir_list="${BASE_PRODUCT_DIR}"

    no_of_prods=`$CMD_ECHO "$addon_dir_list" | $CMD_WC -w 2> /dev/null`
    if [ -d "${SRC_DIR}/Addons/SunMC2.X" ] ; then
        no_of_prods=`$CMD_EXPR $no_of_prods - 1`
        no_of_2x_prods=`$CMD_LS -1 "${SRC_DIR}/Addons/SunMC2.X/Solaris_${OSVERS}" | $CMD_GREP -v locale | $CMD_WC -l 2> /dev/null`
        
        no_of_prods=`$CMD_EXPR $no_of_prods + $no_of_2x_prods`        
    fi
    [ -d "${SRC_DIR}/Addons/Windows" ] && no_of_prods=`$CMD_EXPR $no_of_prods - 1`
    
    put_var_in_cfgfile "${PROGRESS_FILE}" "NUMBER_OF_PRODUCTS" "$no_of_prods" "="    
    
    # Check for SunMC addon products
    for dir in `$CMD_ECHO $addon_dir_list`
    do
        if [ "$dir" != "SunMC2.X" -a "$dir" != "Windows" ] ; then # Not SunMC 2.X addon products
            value=""
            if [ "$dir" != "$BASE_PRODUCT_DIR" ] ; then # Not Base        
                INSTALL_TYPE="ADDON"                    
                setInstallationInfoInstallationProperties "${dir}"                                  
                [ $? -eq 0 ] && continue            
            else
                setInstallationInfoInstallationProperties
            fi   
        
            getProductInfoFromFile

	    if [ "$PROGNAME" = "archive-tool" ]; then
	        su_compatibles="$SMARTUPDATE_COMPATIBLE_PRODUCTS"
	        checkString "$su_compatibles" "$PRODUCT_KEY"
	        if [ $? -ne 0 ]; then
		    echologverbose 'Found: $2' "$PRODUCT_NAME"
		    echologverbose 'Dynamic Agent Update server components of this product are not installed'
		    echologverbose 'This product will not be listed for selection'
		    echologverbose ' '
		    unsetInstallationInfoInstallationProperties
		    continue
	        fi
	    fi 
            
            if [ $start -eq 0 ] ; then
                start=1
                COMPONENT_FILTERS_LIST="KEY=${PRODUCT_KEY}"
                COMP_NAMES="KEY=${PRODUCT_KEY}"
                INIT_COMP_DETAILS="KEY=${PRODUCT_KEY}"
                SOURCE_LIST="KEY=${PRODUCT_KEY}"
                LICENSE_AGREEMENTS_LIST="KEY=${PRODUCT_KEY}"
            else       
                COMPONENT_FILTERS_LIST="${COMPONENT_FILTERS_LIST}@KEY=${PRODUCT_KEY}"
                COMP_NAMES="${COMP_NAMES}@KEY=${PRODUCT_KEY}"
                INIT_COMP_DETAILS="${INIT_COMP_DETAILS}@KEY=${PRODUCT_KEY}"
                SOURCE_LIST="${SOURCE_LIST}@KEY=${PRODUCT_KEY}"
                LICENSE_AGREEMENTS_LIST="${LICENSE_AGREEMENTS_LIST}@KEY=${PRODUCT_KEY}"
            fi            
            
            put_var_in_cfgfile "${PROGRESS_FILE}" "NAME" "$PRODUCT_NAME" "="
            
            if [ "$PRODUCT_KEY" != "$BASE_PRODUCT_KEY" ] ; then                
                $CMD_ECHO "    \c"
                echolog 'Found: $2' "$PRODUCT_NAME"
            fi
            
            value="NAME=${PRODUCT_NAME}#SOURCE_DIR=${dir}#VERSION=3X"        
            [ -n "${INSTALL_SUBDIR}" ] && value="${value}#TARGET_DIR=${INSTALL_SUBDIR}"        
            [ -n "${PACKAGES_SUBDIR}" ] && value="${value}#SUBDIR=${PACKAGES_SUBDIR}"        
            [ -n "${PACK_SUBDIR}" ] && value="${value}#SUBDIR=${PACK_SUBDIR}"
            
        
            SOURCE_LIST=`addAttributesToProduct "${SOURCE_LIST}" "$PRODUCT_KEY" "$value"`                
            
            # get more info that should not go into source list
            #
            getComponentListFromFile

            INIT_COMP_DETAILS=`addAttributesToProduct "$INIT_COMP_DETAILS" "$PRODUCT_KEY" "COMPONENT_LIST=${COMPONENT_LIST}"`      
            #LICENSE_AGREEMENTS_LIST=`addAttributesToProduct "$LICENSE_AGREEMENTS_LIST" "$PRODUCT_KEY" "COMPONENT_LIST=${COMPONENT_LIST}"`      
            #echo stage1 "$LICENSE_AGREEMENTS_LIST"
           
            CD=""
            PATCHES=""
            OPTIONAL_COMPONENTS=""
            list_c=""
            list_bcl=""
            
            [ -n "$PACK_CD" ] && CD=$PACK_CD
            
            for COMPONENT_KEY in `$CMD_ECHO "$COMPONENT_LIST" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
            do
                value=""
                getComponentInfo "LAYER"
                [ -n "${COMPONENT_INFO}" ] && value="${COMPONENT_KEY}.LAYER=${COMPONENT_INFO}"
                
                getComponentInfo "LANG"
                [ -n "${COMPONENT_INFO}" ] && value="${value}#${COMPONENT_KEY}.LANG=${COMPONENT_INFO}"
                
                getComponentInfo "DEPENDENCIES"
                if [ -n "${COMPONENT_INFO}" ] ; then
                    echologverbose "$PRODUCT_NAME"
                    echologverbose 'Component Dependency found for Component : $2' $COMPONENT_KEY
                    echologverbose 'This tag is not processed. Please use LAYER to achieve the same results.'
                fi 
                
                getComponentInfo "COMPONENT_SCRIPT"
                [ -n "${COMPONENT_INFO}" ] && value="${value}#${COMPONENT_KEY}.SCRIPT=${COMPONENT_INFO}"
                
                COMPONENT_FILTERS_LIST=`addAttributesToProduct "$COMPONENT_FILTERS_LIST" "$PRODUCT_KEY" "${value}"`      
                
                if [ -z "$PACK_CD" ] ; then
                    getComponentInfo "COMPONENT_CD"
                
                    if [ -n "$COMPONENT_INFO" ] ; then
                        CD=$COMPONENT_INFO
                    else   
                        CD=1 #default to 1
                    fi
                fi             
                
                getI18NMessage "$COMPONENT_KEY"
                COMP_NAMES=`addAttributesToProduct "$COMP_NAMES" "$PRODUCT_KEY" "${COMPONENT_KEY}=${MSG}"`
                                                
                getComponentInfo "ESSENTIAL"
                if [ "$COMPONENT_INFO" = "false" -o "$COMPONENT_INFO" = "FALSE" ] ; then
                    OPTIONAL_COMPONENTS="${OPTIONAL_COMPONENTS} ${COMPONENT_KEY}"                
                fi                 
                
                getComponentInfo "PATCHES_REQUIRED"
                patches=${COMPONENT_INFO}
                patches=`$CMD_ECHO "${patches}" | $CMD_SED "s/ /,/g" 2> /dev/null`
                
                if [ -n "$patches" ] ; then                 
                    INIT_COMP_DETAILS=`addAttributesToProduct "$INIT_COMP_DETAILS" "$PRODUCT_KEY" "PATCHES_${COMPONENT_KEY}=${patches}"`            
                    if [ -z "$PATCHES" ] ; then
                        PATCHES="$patches"
                    else
                        PATCHES="${PATCHES},${patches}"
                    fi
                fi
                
                if [ -n "$LOCALE_CODE" ] ; then    
                    getComponentInfo "PACKAGES" "$LOCALE_CODE"
                else
                    getComponentInfo "PACKAGES"
                fi
                packages=${COMPONENT_INFO}                
                PACKAGES=`$CMD_ECHO "${packages}" | $CMD_SED "s/ /,/g" 2> /dev/null`
                
                if [ -z "${list_c}"  ] ; then
                    list_c="${COMPONENT_KEY}:${PACKAGES}:${CD}"
                else              
                    list_c="${list_c} ${COMPONENT_KEY}:${PACKAGES}:${CD}"
                fi
            
                # Scan for BCL
                #
                getComponentInfo "LICENSE_AGREEMENT"
                if [ "${COMPONENT_INFO}" = "TRUE" -o "${COMPONENT_INFO}" = "true" ]; then
                   BCL=1              
                else
                   BCL=0                
                fi
                
                if [ -z "${list_bcl}"  ] ; then
                    list_bcl="${COMPONENT_KEY}:${BCL}"
                else              
                    list_bcl="${list_bcl} ${COMPONENT_KEY}:${BCL}"
                fi
            done            

            INIT_COMP_DETAILS=`addAttributesToProduct "$INIT_COMP_DETAILS" "$PRODUCT_KEY" "COMP_DETAILS=${list_c}"`
            LICENSE_AGREEMENTS_LIST=`addAttributesToProduct "$LICENSE_AGREEMENTS_LIST" "$PRODUCT_KEY" "COMP_DETAILS=${list_bcl}"`
            
            if [ -n "${OPTIONAL_COMPONENTS}" ] ; then
                SOURCE_LIST=`addAttributesToProduct "${SOURCE_LIST}" "$PRODUCT_KEY" "OPTIONAL_COMPONENTS=${OPTIONAL_COMPONENTS}"`                      
                    
                if [ -z "$ALL_OPTIONAL_COMPONENTS" ] ; then
                    ALL_OPTIONAL_COMPONENTS="KEY=${PRODUCT_KEY}#OPTIONAL=${OPTIONAL_COMPONENTS}"
                else
                    ALL_OPTIONAL_COMPONENTS="${ALL_OPTIONAL_COMPONENTS}@KEY=${PRODUCT_KEY}#OPTIONAL=${OPTIONAL_COMPONENTS}"
                fi
            fi            
            [ -n "${PATCHES}" ] && SOURCE_LIST=`addAttributesToProduct "${SOURCE_LIST}" "$PRODUCT_KEY" "ALL_PATCHES=${PATCHES}"`                      
         fi
         unsetInstallationInfoInstallationProperties
         echologverbose ''
    done
 
    # Check for SunMC 2.X addon products
    
    dir="${SRC_DIR}/Addons/SunMC2.X/Solaris_${OSVERS}"

    common_dir="${SRC_DIR}/Addons/SunMC2.X/Common"
  
    [ ! -d "$dir" -a ! -d "$common_dir" ] && return
    getLastCD
    for product in `$CMD_LS $dir` ; do       
        package_list=""
        
        put_var_in_cfgfile "${PROGRESS_FILE}" "NAME" "$product" "="
        
        for package in `$CMD_LS "${dir}/$product"` ; do
            [ "$package" = "locale" ] && continue # Skip locale directory            
            if [ -z "$package_list" ] ; then
                package_list="$package"
            else
                package_list="${package_list},$package"
            fi
        done
       
        if [ -n "$package_list" ] ; then            
            if [ -z "$INIT_COMP_DETAILS" ] ; then
                INIT_COMP_DETAILS="KEY=${product}"
            else       
                INIT_COMP_DETAILS="${INIT_COMP_DETAILS}@KEY=${product}"
            fi
            
            if [ -z "$SOURCE_LIST" ] ; then
                SOURCE_LIST="KEY=${product}"
            else       
                SOURCE_LIST="${SOURCE_LIST}@KEY=${product}"
            fi
            
            value="NAME=${product}#SOURCE_DIR=${product}#VERSION=2X"
            
            SOURCE_LIST=`addAttributesToProduct "$SOURCE_LIST" "$product" "${value}"` 
            
            INIT_COMP_DETAILS=`addAttributesToProduct "$INIT_COMP_DETAILS" "$product" "COMPONENT_LIST=DEFAULT"`      
            INIT_COMP_DETAILS=`addAttributesToProduct "$INIT_COMP_DETAILS" "$product" "COMP_DETAILS=DEFAULT:${package_list}:${LAST_CD}"`      
        fi
   done   
}




# Shows BCL for server layer server 
#      - If server being installed/already installed/partially installed.
#      - will collect BCL text file from "${LOCALE_DIRECTORY}/${LANG}/LC_MESSAGES
#      - Exit if user does not agrees.   
#   
showLicenseAgreementForServer () {

   # Server layer BCL
   #
   checkString "$INSTALL_LAYERS" "LAYER.SERVER"
   if [ $? -eq 0 ]; then
      
      $CMD_PKGINFO $RELOC_PARAM -qi SUNWessrv 
      [ $? -eq 0 ] && return # Base Server package is already installed so do not show BCL 
      
      if [ $DE_INSTALL -eq 0 ] ; then
          BASE_BCL_FILE="${LOCALE_DIRECTORY}/${LANG}/LC_MESSAGES/BCL_TEXT_SERVER"
          [ ! -f "$BASE_BCL_FILE" ] && BASE_BCL_FILE="${LOCALE_DIRECTORY}/C/LC_MESSAGES/BCL_TEXT_SERVER"
      else
          BASE_BCL_FILE="${LOCALE_DIRECTORY}/${LANG}/LC_MESSAGES/BCL_TEXT_DE"
          [ ! -f "$BASE_BCL_FILE" ] && BASE_BCL_FILE="${LOCALE_DIRECTORY}/C/LC_MESSAGES/BCL_TEXT_DE"
      fi
      
      if [ -r "$BASE_BCL_FILE" ] ; then
         $CMD_CLEAR
         if [ -z "$AUTOCONFIG_RUNFILE" ] ; then
            $CMD_NROFF -e "$BASE_BCL_FILE" | $CMD_MORE -s             
         else
            $CMD_NROFF -e "$BASE_BCL_FILE" | $CMD_CAT
         fi                     
        
         READ_RESPONSE_ONCE=0            
         echolog ''
         echolog 'You must agree to the above license agreement to proceed with installation.'
         fetch_response_yes_no "TAG=SERVER_LICENSE_AGREEMENT" "Do you agree "
         saveAutoConfig  "SERVER_LICENSE_AGREEMENT" "$answer"
         [ "$answer" != "1" ] && exit_SunMC "$LICENSE_AGREEMENT_ERROR"         
         echolog ''
      else
         echolog 'License agreement file could not be located.'
         exit_SunMC "$LICENSE_AGREEMENT_ERROR"
      fi
   fi
}
   

# Sows BCL for SunMC addons 
# For now, will exit if user does not agree to BCL.
# Design-wise it should continue for remaining products.  
#
#
showLicenseAgreementForAddons () {
    
   # If DE is already installed skip Addon BCL
   #
   tmp_component=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=${BASE_PRODUCT_KEY}" "component" "key" 2>/dev/null`
   checkString "$tmp_component" "COMPONENT.SDK"
   [ $? -eq 0 ] && DE_INSTALL=1 

   [ $DE_INSTALL -eq 1 ] && return
   
   [ -z "$SELECTED_KEYS" ] && return

   ADDON_BCL_REQUIRED=0
   
   LOGLINE=""
   for PRODUCT_KEY in `$CMD_ECHO "$SELECTED_KEYS"` ; do
       checkString "$ALREADY_INSTALLED_COMPONENTS" "$PRODUCT_KEY:COMPONENT.SERVER"
       [ $? -eq 0 ] && continue

       tmp_comonent_list="`getProductAttr "$LICENSE_AGREEMENTS_LIST" "$PRODUCT_KEY" COMP_DETAILS`"
       [ -z "$tmp_comonent_list" ] && continue

       checkString "${tmp_comonent_list}" ":1"
       [ $? -eq 0 ] && ADDON_BCL_REQUIRED=1
        
       for each_comp in `$CMD_ECHO "$tmp_comonent_list"`
       do
           tmp_bcl=`$CMD_ECHO "$each_comp" | $CMD_AWK -F ':' '{ print $2 }'`
           if [ "$tmp_bcl" = "1" ]; then
               # Add name in LOGLINE
               #
               tmp_name=`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" "NAME"`            
               LOGLINE="${LOGLINE}\n${tmp_name}"
               break
            fi
        done 
   done  


   if [ "$ADDON_BCL_REQUIRED" = "1" ] ; then
        ADDON_BCL_FILE="${LOCALE_DIRECTORY}/${LANG}/LC_MESSAGES/BCL_TEXT_ADDON"
        [ ! -f "$ADDON_BCL_FILE" ] && ADDON_BCL_FILE="${LOCALE_DIRECTORY}/C/LC_MESSAGES/BCL_TEXT_ADDON"
        
        if [ -r "$ADDON_BCL_FILE" ] ; then
    
            if [ -z "$AUTOCONFIG_RUNFILE" ] ; then
               $CMD_NROFF -e "$ADDON_BCL_FILE" | $CMD_MORE -s 
            else
               $CMD_NROFF -e "$ADDON_BCL_FILE" | $CMD_CAT
            fi 
            
            
            
            if [ -n "$LOGLINE" ] ; then
               echolog ''
               echolog ''
               echolog 'The following Add-On products are covered under license agreement:' 
               $CMD_ECHO "$LOGLINE"
            fi
            READ_RESPONSE_ONCE=0            
            echolog ''
            echolog 'You must agree to the above license agreement to proceed with installation.'
            fetch_response_yes_no "TAG=ADDONS_LICENSE_AGREEMENT" "Do you agree "
            saveAutoConfig  "ADDONS_LICENSE_AGREEMENT" "$answer"
            [ "$answer" != "1" ]  && exit_SunMC "$LICENSE_AGREEMENT_ERROR"
        else
           echolog 'License agreement file could not be located.'
           exit_SunMC "$LICENSE_AGREEMENT_ERROR"
        fi
   fi
}



#
# this function sets a list called SOURCE_LIST containing basic info about all 
# products under the source directory
#
scanSourceForAllProducts() {    
    [ "$SOURCE_IMAGE" = "PATCH_ONLY" ] && return
        
    if [ "$PROGNAME" = "archive-tool" ]; then
        echolog ''
        echolog 'Checking for Available products. Please wait...'
        echolog ''
    else
        time=2
        checkString "$INSTALL_LAYERS" "LAYER.SERVER"
        [ $? -eq 0 ] && time=3
        echolog 'Reading Add-On products from image. Please wait...'
        echolog 'This can take approximately $2 minutes to complete.' "$time"
        echolog ''
    fi
    
    setupProgressFile
    
    readProductInfo
    
    time=1    
    checkString "$INSTALL_LAYERS" "LAYER.SERVER"
    [ $? -eq 0 ] && time=2
    echolog ''
    echolog 'Checking for applicable products. Please wait...'
    if [ $time != 1 ]; then
    echolog 'This can take approximately $2 minutes to complete.' "$time"
    else
    echolog 'This can take approximately $2 minute to complete.' "$time"
    fi
    echolog ''    
    
    put_var_in_cfgfile "${PROGRESS_FILE}" "PROCESS" "Filtering" "="
    i=1
    for PRODUCT_KEY in `getKeys "$SOURCE_LIST"` ; do   
        PRODUCT_NAME=`getProductAttr "${SOURCE_LIST}" "${PRODUCT_KEY}" "NAME"`
        put_var_in_cfgfile "${PROGRESS_FILE}" "NAME" "$PRODUCT_NAME" "="
        put_var_in_cfgfile "${PROGRESS_FILE}" "PROD_NUMBER" "$i" "="
        i=`$CMD_EXPR $i + 1` 
        isProductInstallable             
    done
    echolog ''

    $CMD_RM -f "${PROGRESS_FILE}" "${PROGRESS_FILE}.old"

    echolog ''      
}

setupProgressFile() {
    [ -z "$PROGRESS_FILE" ] && return
    [ -f "${PROGRESS_FILE}" ] && $CMD_RM -f ${PROGRESS_FILE}
    
    temp_dirname=`$CMD_DIRNAME $PROGRESS_FILE`
    [ "$temp_dirname" = "." ] && temp_dirname=`$CMD_PWD`
    temp_filename=`$CMD_BASENAME ${PROGRESS_FILE}`
    PROGRESS_FILE=${temp_dirname}/${temp_filename}
    
    $CMD_TOUCH ${PROGRESS_FILE}
    export PROGRESS_FILE
}

# input - SELECTED_KEYS
# updates  SOURCE_LIST with a new Arrtibute - INSTALL_COMPONENTS
# This is the final list with only selected optional components, and only 
# as yet uninstalled component. Also, this attribute format is identical for 3X and 2X
# addons
#
prepareForInstall() {

   [ "$SOURCE_IMAGE" = "PATCH_ONLY" ] && return
   [ -z "$SELECTED_KEYS" ] && return 

   
   INSTALL_KEYS=""
   PATCHES=""
   
   for PRODUCT_KEY in `$CMD_ECHO "$SELECTED_KEYS"`
   do
        version=`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" "VERSION"`
        #
        # do the lengthy parsing now, only for the products to be installed.
        #
        if [ "$OPTIMIZE_FOR_ES_INST" = "1" ] ; then
            inst_base_dir=`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" "TARGET_DIR"` 
            [ -z "$inst_base_dir" ] && inst_base_dir=" "
        fi
        
        INSTALL_COMPONENTS=""
        tmp_auto_components=""
        
        if [ "$PRODUCT_KEY" = "${BASE_PRODUCT_KEY}" ] ; then
            INSTALL_TYPE="BASE"        
        else 
            INSTALL_TYPE="ADDON"         
        fi
              
        ALL_COMPONENT_LIST=`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" "ALL_COMPONENTS"`                
        
        #process components
        for component_string in `$CMD_ECHO "$ALL_COMPONENT_LIST"`
        do
            
            COMPONENT_KEY=`$CMD_ECHO "$component_string" | $CMD_AWK -F ':' '{ print $1 }'`            
            t_packages=`$CMD_ECHO "$component_string" | $CMD_AWK -F ':' '{ print $2 }'`                
                 
            already_installed=0 
                
            # Check if the packages for the component have already been installed
            checkString "$ALREADY_INSTALLED_COMPONENTS" "${PRODUCT_KEY}:${COMPONENT_KEY}"        
            
            if [ $? -eq 0 ] ; then # component is installed already
                if [ "$version" = "3X" ] ; then                    
                    MSG=`getProductAttr "$COMP_NAMES" "$PRODUCT_KEY" "$COMPONENT_KEY"`
                    $CMD_ECHO "    \c"
                    echolog '    Component: $2 is already installed.' "$MSG"                
                else
                    $CMD_ECHO "    \c"
                    echolog '    Product: $2 is already installed.' "$PRODUCT_KEY"
                fi
                $CMD_ECHO "    \c"
                echolog '    The corresponding packages are $2 ' "${t_packages}"                 
                    
                already_installed=1
            fi             
                
            if [ $already_installed -eq 0 ] ; then
                
                if [ "$version" = "3X" ] ; then                    
                    #check if not to be installed
                    checkString "$COMPONENTS_NOT_TO_BE_INSTALLED" "${PRODUCT_KEY}:${COMPONENT_KEY}"
                    if [ $? -eq 0 ] ; then                        
                        MSG=`getProductAttr "$COMP_NAMES" "$PRODUCT_KEY" "$COMPONENT_KEY"`
                        echologverbose 'skipping component $2' "$MSG"
                        continue
                    fi
        
                    #check if optional and not selected                     
                    optional_components=`getProductAttr "$ALL_OPTIONAL_COMPONENTS" "${PRODUCT_KEY}" "OPTIONAL"`
                    checkString "$optional_components" "$COMPONENT_KEY"                    
                    if [ $? -eq 0 ] ; then          
                        checkString "${ALL_SELECTED_OPTIONALS}" "${PRODUCT_KEY}:${COMPONENT_KEY}"
                        if [ $? -ne 0 ] ; then
                            MSG=`getProductAttr "$COMP_NAMES" "$PRODUCT_KEY" "$COMPONENT_KEY"`
                            echolog 'skipping optional component: $2' "$MSG"
                            echolog 'It was not selected'
                            continue
                        fi
                    fi 
                fi
                
                #remove any unselected optional packages
                #
                add_packages=""
                for pkg in `$CMD_ECHO "$t_packages" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
                do
                    checkString "$REJECT_PACKAGE_LIST" "$pkg"
                    [ $? -eq 0 ] && continue
                    if [ -z "$add_packages" ] ; then
                        add_packages="$pkg"
                    else
                        add_packages="${add_packages},$pkg"
                    fi
                    
                    # do the lengthy parsing now, only for the products to be installed.
                    #
                
                    if [ "$OPTIMIZE_FOR_ES_INST" = "1" -a "$inst_base_dir" = " " ] ; then
                        getPackageDirectory $pkg
                        
                        # this takes very long, and depends on how the Add-on has laid out their pkgmap file
                        #
                        [ "${PRODUCT_KEY}" != "${BASE_PRODUCT_KEY}" ] && inst_base_dir=`getInstBaseDir "$PACKAGE_DIR"`
                    fi
                done                   
                
                tmp_cd=`$CMD_ECHO "$component_string" | $CMD_AWK -F ':' '{ print $3 }'`    
            
                #component must be aded to INSTALL_COMPONENTS 
                          
                if [ -z "$INSTALL_COMPONENTS" ] ; then
                    INSTALL_COMPONENTS="${COMPONENT_KEY}:${add_packages}:${tmp_cd}"
                else
                    INSTALL_COMPONENTS="${INSTALL_COMPONENTS} ${COMPONENT_KEY}:${add_packages}:${tmp_cd}"
                fi
                patches=`getProductAttr "$INIT_COMP_DETAILS" "$PRODUCT_KEY" "PATCHES_${COMPONENT_KEY}"`
                [ -z "$patches" ] && continue
                
                if [ -z "$PATCHES" ] ; then
                    PATCHES="$patches"
                else
                    PATCHES="${PATCHES},${patches}"
                fi                                              
            fi
        done
        
        
        #got here, so must be installed
        [ "$OPTIMIZE_FOR_ES_INST" = "1" ] && SOURCE_LIST=`addAttributesToProduct "$SOURCE_LIST" "$PRODUCT_KEY" "TARGET_DIR=${inst_base_dir}"`
        
        [ -n "${PATCHES}" ] && SOURCE_LIST=`addAttributesToProduct "${SOURCE_LIST}" "$PRODUCT_KEY" "PATCHES=${PATCHES}"`                      
            
        checkString "$ALREADY_INSTALLED_LIST" "$PRODUCT_KEY"
        [ $? -ne 0 ] && [ -n "$INSTALL_COMPONENTS" ] && INSTALL_KEYS="${INSTALL_KEYS} $PRODUCT_KEY"
        SOURCE_LIST=`addAttributesToProduct "$SOURCE_LIST" "$PRODUCT_KEY" "INSTALL_COMPONENTS=${INSTALL_COMPONENTS}"`        
done


}




# << BEGIN addon related functions<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #





#
# $1 - full path to package directory
# echo - subdir under SUNWsymon/addons in pkgmap file if found
getInstBaseDir() {    
    FOUND=`$CMD_CAT $1/pkgmap | $CMD_CUT -f4 -d" " | $CMD_GREP "SUNWsymon/addons" 2> /dev/null `
    [ $? -gt 0 ] && $CMD_ECHO " " && return 0
    for line in `$CMD_ECHO "$FOUND"` ; do                            
        checkString "$line" "SUNWsymon/addons"
        [ $? -ne 0 ] && continue
        path=`$CMD_ECHO "${line}" | $CMD_CUT -d" " -f4`                            
        DIR=`$CMD_ECHO "$path" | $CMD_SED "s/SUNWsymon//" | $CMD_SED "s/\/addons//" | $CMD_SED "s/\///g"`
        [ -n "$DIR" ] && $CMD_ECHO "$DIR" && break
    done    
}


displayAllProducts() {
    
    if [ $BASE_AVAILABLE -eq 1 -a $BASE_FULLY_INSTALLED -eq 0 ] ; then
        PRODUCT_KEY=${BASE_PRODUCT_KEY}
        INSTALL_TYPE=BASE

        if [ "$ARCHIVE_PRODUCT_SELECTION" != "DONE" ]; then      # Archive-Tool smart-update   
            checkString "${ALREADY_INSTALLED_COMPONENTS}" "${BASE_PRODUCT_KEY}:"
            if [ $? -ne 0 ] ; then # fresh base installation
                echolog ''
                echolog 'The Sun Management Center Base Product will be installed.' 
                echolog ''
            fi
        fi						    # Archive-Tool smart-update
        askOptionalComponents
        askOptionalPackages  
    fi

    if [ "$ARCHIVE_PRODUCT_SELECTION" != "DONE" ]; then      # Archive-Tool smart-update
      if [ "$ARCHIVE_ADDON_FLAG" != "0" ]; then    # Both the conditions will 
                                                   # be true with es-inst
        echologverbose '$2' "$LOG_LINE"   
        echolog 'The following Add-On Products are applicable for installation.'    
      fi
    fi						   # Archive-Tool smart-update

 
for PRODUCT_KEY in `$CMD_ECHO "$AVAILABLE_KEYS"`
do
    [ "$PRODUCT_KEY" = "${BASE_PRODUCT_KEY}" ] && continue

    if [ "$PROGNAME" = "archive-tool" -a "$ARCHIVE_PRODUCT_SELECTION" != "DONE" ] ; then
	resetOSforProduct "$PRODUCT_KEY"
    fi
    
    mismatched=0
    partially=0
    patch_required=0
        
        checkString "${ALREADY_INSTALLED_LIST}" "$PRODUCT_KEY"
        [ $? -eq 0 ] && continue
        
        checkString "${ALREADY_INSTALLED_COMPONENTS}" "${PRODUCT_KEY}:"
        [ $? -eq 0 ] && partially=1
        
        checkString "${MISMATCH_LIST}" "KEY=${PRODUCT_KEY}"
        [ $? -eq 0 ] && mismatched=1
        
        PATCH_LIST=`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" "ALL_PATCHES"`
        [ -n "$PATCH_LIST" ] && patch_required=1       
        
        name=`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" "NAME"`                  
        if [ "$ARCHIVE_PRODUCT_SELECTION" != "DONE" ]; then      # Archive-Tool smart-update
        	$CMD_ECHO "    \c"
        	echolog '$2' "$name"
	fi 							 # Archive-Tool smart-update
                
        
            #dep=`getProductAttr "$SOURCE_LIST" $PRODUCT_KEY "DEPENDS_ON"`
            dep=""
            if [ -n "$dep" ] ; then
                echolog 'Requires installation of:'
                dep=`$CMD_ECHO $dep | $CMD_SED "s/,/ /g"`
                for each_dep_prod_key in $dep
                do
                    dep_prod_name=`getProductAttr "$SOURCE_LIST" $each_dep_prod_key "NAME"`
                    echolog '"\r\t"$2' "$dep_prod_name"
                done
            fi        
        
        if [ $mismatched -eq 1 ] ; then
            $CMD_ECHO "    \c"
            echolog 'It appears that an earlier version of this product is installed on your system.'
            SV=`getProductAttr "$MISMATCH_LIST" "$PRODUCT_KEY" "SV"`
            IV=`getProductAttr "$MISMATCH_LIST" "$PRODUCT_KEY" "IV"`
            $CMD_ECHO "    \c"
            echolog 'You have the following version installed : $2' "$IV"
            $CMD_ECHO "    \c"
            echolog 'You may upgrade to version : $2' "$SV"
            $CMD_ECHO "    \c"
            echolog 'To install this product, the installed version will have to be removed.'
            continue
        fi
        
        if [ $partially -eq 1 ] ; then
            $CMD_ECHO "    \c"
            echolog 'One or more components of this product are already installed on your system.'
            $CMD_ECHO "    \c"
            echolog 'All remaining components will be installed.'
            continue
        fi 
        
        if [ "$PROGNAME" != "archive-tool" -a $patch_required -eq 1 ] ; then
            $CMD_ECHO "    \c" 
            echolog 'This product requires some or all of the following patches:'
            $CMD_ECHO "    \c"
            echolog '$PATCH_LIST'
            $CMD_ECHO "    \c"
            echolog 'If you select to install it, the required patches will be installed.'            
        fi     
    done
    echolog ''
}

selectAddonsInteractively() {
    SELECTED_KEYS=""
    ADDON_COMPONENTS_NOT_TO_BE_INSTALLED=""
    UNINST_KEYS=""     
    if [ "$ARCHIVE_PRODUCT_SELECTION" != "DONE" ] ; then        
      if [ "$ARCHIVE_ADDON_FLAG" != "0" ]; then   # Both the conditions will be
                                                  # true with es-inst
        echolog 'Select the products you want to install:'
      fi
    fi    
    for PRODUCT_KEY in `$CMD_ECHO "$AVAILABLE_KEYS"`
    do   
        if [ "$PROGNAME" = "archive-tool" -a "$ARCHIVE_PRODUCT_SELECTION" != "DONE" ] ; then
	    resetOSforProduct "$PRODUCT_KEY"
        fi
        mismatch=0
        partially=0     
                 
        
        checkString "$ALREADY_INSTALLED_LIST" "$PRODUCT_KEY"
        [ $? -eq 0 ] && continue        
   
        if [ "$PRODUCT_KEY" = "${BASE_PRODUCT_KEY}" ] ; then
            INSTALL_TYPE="BASE"            
        else   
            INSTALL_TYPE="ADDON"       
        fi    
        
        if [ "$INSTALL_TYPE" = "ADDON" ] ; then
            checkString "${ALREADY_INSTALLED_COMPONENTS}" "${PRODUCT_KEY}:"
            [ $? -eq 0 ] && partially=1
               
            checkString "$SELECTED_KEYS" "${PRODUCT_KEY}"
            [ $? -eq 0 ] && continue
            
            checkString "$MISMATCH_LIST" "KEY=${PRODUCT_KEY}"
            [ $? -eq 0 ] && mismatch=1
            
            name=`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" "NAME"`
            if [ $partially -eq 0 ] ; then
                READ_RESPONSE_ONCE=0 
                $CMD_ECHO "    \c"           
                fetch_response_yes_no "TAG=$PRODUCT_KEY" '$name '
                [ -z "$answer" ] && answer=0 
            else
                echolog 'Selecting product: $2' "$name"
                answer=1                
            fi           
            if [ "$PROGNAME" = "archive-tool" ] ; then # agent-update
                saveAutoConfig "$PRODUCT_KEY" "$answer"
            fi 
        fi
       
        if [ "$answer" = "1" -o "$INSTALL_TYPE" = "BASE" ] ; then 
    
            SELECTED_KEYS="${SELECTED_KEYS} ${PRODUCT_KEY}"
            
            [ $mismatch -eq 1 ] && UNINST_KEYS="$UNINST_KEYS ${PRODUCT_KEY}" 
            
            if [ "$INSTALL_TYPE" = "ADDON" ] ; then
                askOptionalComponents            
                askOptionalPackages
            fi
        fi  
    done
}


# Verify that the package can be installed
# $1 = package name
# $2 = file name
# Return: 0 = confirmed (install)
confirmPackage() {
    ES_ADDON_PLATFORM_MATCH=""
    PLATFORMLIST=`$CMD_PKGPARAM -f "$2" ES_ADDON_PLATFORM`
    if [ "$PLATFORMLIST" != "" ] ; then
        OLDIFS=$IFS
        IFS=:
        for each_platform in $PLATFORMLIST
        do
            checkString "$PRTOUT" "$each_platform"
            if [ $? -eq 0 ] ; then
                ES_ADDON_PLATFORM_MATCH="$each_platform"
                break
            fi
        done
        IFS="$OLDIFS"
    fi

    PLATFORM_FILE="${VAROPTDIR}/platform/platform.prop"
    PLATFORM_DIR=`$CMD_DIRNAME $PLATFORM_FILE`
    [ ! -d $PLATFORM_DIR ] && $CMD_MKDIR -p $PLATFORM_DIR

    FAMILY=`$CMD_PKGPARAM -f $2 ES_ADDON_FAMILY`

    # Check if the platform file exists, and check to see if it matches
    # the package we are working with.
    if [ -n "$ES_ADDON_PLATFORM_MATCH" ] && [ -n "$FAMILY" ] && \
    [ -n "$PLATFORM_FILE" ] && [ -f "$PLATFORM_FILE" ] ; then
        file_plat=`$CMD_GREP '^name' "$PLATFORM_FILE" | $CMD_CUT -f2 -d=`
        file_family=`$CMD_GREP '^family' "$PLATFORM_FILE" | $CMD_CUT -f2 -d=`
        [ "$file_plat" = "$ES_ADDON_PLATFORM_MATCH" ] && [ "$file_family" = "$FAMILY" ] && return 0
        return 1
    fi

    #  Either the platform file does not exist, or it does not
    #  match, so ask the user what he wants to do!
    if [ "$ARCHIVE_PRODUCT_SELECTION" != "DONE" ]; then	# Archive-tool 
        echolog ''
        echolog 'Verify the platform for package: $2' "$1"
        echolog ''
        $CMD_ECHO "    \c"
        echolog 'Found: $2' "$PRTOUT"
    fi							# Archive-tool

    # Test to make sure the platform list was specified in the pkginfo file.
    if [ -n "$ES_ADDON_PLATFORM_MATCH" ] ; then
    $CMD_ECHO "    \c"
    if [ -n "$FAMILY" ] ; then
        echolog 'Supports: $2 - $3' "$ES_ADDON_PLATFORM_MATCH" "$FAMILY"
    else
        echolog 'Supports: $2' "$ES_ADDON_PLATFORM_MATCH"
    fi
    fi

    if [ "$ARCHIVE_PRODUCT_SELECTION" != "DONE" ]; then	# Archive-tool 
        name=`$CMD_PKGPARAM -f $2 NAME`
        $CMD_ECHO "    \c"
        echolog 'Name: $2' "$name"
        desc=`$CMD_PKGPARAM -f $2 DESC`
        $CMD_ECHO "    \c"
        echolog 'Description: $2' "$desc"
        echolog ''
    fi							# Archive-tool

    READ_RESPONSE_ONCE=0
    $CMD_ECHO "  \c"
    fetch_response_yes_no "TAG=OPTIONAL_PACKAGE:${PRODUCT_KEY}:${COMPONENT_KEY}:${1}"  "Do you want to install this package "
    [ -z "$answer" ] && answer=0
    
    saveAutoConfig  "OPTIONAL_PACKAGE:${PRODUCT_KEY}:${COMPONENT_KEY}:${1}" "$answer"
    
    if [ $answer -eq 0 ] ; then
        $CMD_ECHO "    \c"
        echolog 'Skipping package $2' "$1"
        echolog ""
        return 1
    fi

    # Save the platform/family information for others to use later
    if [ -n "$ES_ADDON_PLATFORM_MATCH" ] && [ -n "$FAMILY" ] ; then
        $CMD_ECHO "name=$ES_ADDON_PLATFORM_MATCH" > "$PLATFORM_FILE"
        $CMD_ECHO "family=$FAMILY" >> "$PLATFORM_FILE"
    fi
    ALL_SELECTED_OPTIONAL_PACKAGES="${ALL_SELECTED_OPTIONAL_PACKAGES} ${PRODUCT_KEY}:${COMPONENT_KEY}:${1}"
    return 0
}


#reads   : PRODUCT_KEY
#sets REJECT_PACKAGE_LIST for all the optional packages that were not selected
#
askOptionalPackages() {
        comp_list=`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" "ALL_COMPONENTS"`
        
        for each_comp in `$CMD_ECHO "$comp_list"`
        do
            
            COMPONENT_KEY=`$CMD_ECHO "$each_comp" | $CMD_AWK -F ':' '{ print $1 }'`
            
            #first check if it is optional and was not selected TODO
            checkString "$ALL_OPTIONAL_COMPONENTS" "KEY=${PRODUCT_KEY}"
            if [ $? -eq 0 ] ; then #was optional
                checkString "$ALL_SELECTED_OPTIONALS" "$PRODUCT_KEY:$COMPONENT_KEY"    
                [ $? -ne 0 ] && continue #optional component, not selected
            fi            
            
            tmp_ask_packages=`$CMD_ECHO "$each_comp" | $CMD_AWK -F ':' '{ print $4 }'`
            
            for each_pkg in `$CMD_ECHO "$tmp_ask_packages" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
            do
                getPackageDirectory "$each_pkg"
                if [ $? -eq 1 ] ; then                       
                    pkginfo="${PACKAGE_DIR}/pkginfo"
                else
                    echolog 'Cannot find pkginfo file for package: $2' "${each_pkg}"
                    exit_SunMC "$PACKAGE_DIR_NOT_FOUND"
                fi
            
                confirmPackage "$each_pkg" "$pkginfo"
                [ $? -eq 0 ]  && continue
                    
                #got here so package must be skipped
                if [ -z "$REJECT_PACKAGE_LIST" ] ; then
                    REJECT_PACKAGE_LIST="${each_pkg}"
                else
                    REJECT_PACKAGE_LIST="${REJECT_PACKAGE_LIST},${each_pkg}"
                fi
            done                    
        done          
}

# reads   : PRODUCT_KEY
# sets $SELECTED_OPTIONALS to selected optional components of that product.
askOptionalComponents() {
    
    #version=`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" "VERSION"`
    #[ "$version" = "2X" ] && return
    
    checkString "$ALL_OPTIONAL_COMPONENTS" "KEY=${PRODUCT_KEY}"
    [ $? -ne 0 ] && return
    
    if [ "$ARCHIVE_PRODUCT_SELECTION" != "DONE" ]; then	# Archive-tool 
        $CMD_ECHO "    \c"
        echolog 'This product has the following optional components:'
    fi							# Archive-tool
    
    optional_components=`getProductAttr "$ALL_OPTIONAL_COMPONENTS" "$PRODUCT_KEY" "OPTIONAL"`
    
    for COMPONENT_KEY in `$CMD_ECHO "$optional_components"` ; do
        
        MSG=`getProductAttr "$COMP_NAMES" "$PRODUCT_KEY" "$COMPONENT_KEY"`
        	
	checkString "$ALREADY_INSTALLED_COMPONENTS" "${PRODUCT_KEY}:${COMPONENT_KEY}"        
        [ $? -eq 0 ] && echologverbose 'skipping component $2' "$MSG" && continue
    
        checkString "$ADDON_COMPONENTS_NOT_TO_BE_INSTALLED" "${PRODUCT_KEY}:${COMPONENT_KEY}"
        [ $? -eq 0 ] && echologverbose 'skipping component $2' "$MSG" && continue
    	
    	if [ "$ARCHIVE_PRODUCT_SELECTION" != "DONE" ]; then	# Archive-tool 
            $CMD_ECHO "    \c"
            echolog "$MSG"
	fi	                                                # Archive-tool
		
        READ_RESPONSE_ONCE=0
        $CMD_ECHO "    \c"
        fetch_response_yes_no "TAG=OPTIONAL_COMPONENT:${PRODUCT_KEY}:${COMPONENT_KEY}" "Select for install "
        [ -z "$answer" ] && answer=0
        
        if [ $answer -eq 1 ] ; then            
            echologverbose 'Selecting component: $2' "$MSG"
            ALL_SELECTED_OPTIONALS="${ALL_SELECTED_OPTIONALS} ${PRODUCT_KEY}:${COMPONENT_KEY}"        
        else #check if it was selected earlier
            ALL_SELECTED_OPTIONALS=`$CMD_ECHO "${ALL_SELECTED_OPTIONALS}" | $CMD_SED "s/${PRODUCT_KEY}:${COMPONENT_KEY}//g" 2> /dev/null`
            
            if [ -z "$ADDON_COMPONENTS_NOT_TO_BE_INSTALLED" ] ; then
                ADDON_COMPONENTS_NOT_TO_BE_INSTALLED="$PRODUCT_KEY:$COMPONENT_KEY"
            else
                ADDON_COMPONENTS_NOT_TO_BE_INSTALLED="$ADDON_COMPONENTS_NOT_TO_BE_INSTALLED,$PRODUCT_KEY:$COMPONENT_KEY"
            fi
        fi
        if [ "$PROGNAME" = "archive-tool" ] ; then # agent-update
            saveAutoConfig "OPTIONAL_COMPONENT:${PRODUCT_KEY}:${COMPONENT_KEY}" "$answer"
        fi 
    done 
    echolog ''      
}

#input AVAILABLE_ADDON_LIST
#returns SELECTED_ADDON_LIST
#
#
processProducts() { 
    [ "$SOURCE_IMAGE" = "PATCH_ONLY" ] && return
    BASE_AVAILABLE=0
    BASE_FULLY_INSTALLED=0   
    
    checkString "$AVAILABLE_KEYS" "${BASE_PRODUCT_KEY}"
    [ $? -eq 0 ] && BASE_AVAILABLE=1    

    checkString "${ALREADY_INSTALLED_LIST}" "${BASE_PRODUCT_KEY}"
    [ $? -eq 0 ] && BASE_FULLY_INSTALLED=1     

    if [ -z "$AVAILABLE_KEYS" ] ; then
        echolog 'No Add-On products are available for installation'
        return
    fi

   
    if [ -n "$ALREADY_INSTALLED_LIST" ] ; then
        echolog 'The following products are already completely installed on your system:'
        echologverbose '$2' "$LOG_LINE"
        echolog ''
    
        for installed in `$CMD_ECHO "$ALREADY_INSTALLED_LIST"` ; do
            name=`getProductAttr "$SOURCE_LIST" "$installed" "NAME"`
            echolog '    $2' "$name"            
        done
        echolog ''
        echolog ''
    fi
  
    t_answer=0 #ask_user calls inside

while [ $t_answer -eq 0 ] ; do
     
    #first display all
    displayAllProducts
    
    #Now select interactively
    selectAddonsInteractively #returns $SELECTED_KEYS and $UNINST_KEYS
    
    
    if [ "$ARCHIVE_PRODUCT_SELECTION" != "DONE" ]; then         # Archive-Tool smart-update             
        if [ "$SELECTED_KEYS" = " ${BASE_PRODUCT_KEY}" -o -z "$SELECTED_KEYS" ] ; then
            echolog ''
            echolog 'No Add-On Products have been selected for installation.' 
        else                
            echologverbose '$2' "$LOG_LINE"
            echolog ''
            if [ "$PROGNAME" != "archive-tool" ] ; then # Not rqrd for imagetool
                echolog 'The following Add-On Products will be installed:'
                for each_selected in `$CMD_ECHO "$SELECTED_KEYS"`
                do
                    [ "$each_selected" = "${BASE_PRODUCT_KEY}" ] && continue
                    name=`getProductAttr "$SOURCE_LIST" $each_selected "NAME"`
                    echolog '$2' "$name"
                done
            fi
        
            if [ -n "$UNINST_KEYS" ] ; then
                echologverbose '$2' "$LOG_LINE"
                echolog ''
                echolog 'Installed versions of following Add-On Products will be upgraded:' 
                echolog ''
                for each_uninst in `$CMD_ECHO "$UNINST_KEYS"`
                do
                    name=`getProductAttr "$SOURCE_LIST" $each_uninst "NAME"`
                    echolog '$2' "$name"                    
                done
            fi
        fi   
    else                          # Archive-tool smart-update
        break                     # Archive-tool smart-update
    fi 
    if [ -z "$AUTOCONFIG_RUNFILE" ] ; then
        echolog ''
        ask_user 'Do you want to proceed '
        t_answer=$answer
    else
        t_answer=1
    fi                           # Archive-tool smart-update
    
done

if [ ! -z "$ADDON_COMPONENTS_NOT_TO_BE_INSTALLED" ]
then
    if [ ! -z "$COMPONENTS_NOT_TO_BE_INSTALLED" ]
    then
        COMPONENTS_NOT_TO_BE_INSTALLED="$COMPONENTS_NOT_TO_BE_INSTALLED,$ADDON_COMPONENTS_NOT_TO_BE_INSTALLED"
    else
        COMPONENTS_NOT_TO_BE_INSTALLED="$ADDON_COMPONENTS_NOT_TO_BE_INSTALLED"
    fi
fi

echologverbose '$2' "$LOG_LINE"
echolog ''  
 
    if [ "$AUTOCONFIG_SAVEFILE" != "" ] ; then    
        for each_key in `$CMD_ECHO "$AVAILABLE_KEYS"`
        do 
            [ "$each_key" = "${BASE_PRODUCT_KEY}" ] && continue
            checkString "$SELECTED_KEYS" "$each_key"  
            if [ $? -eq 0 ] ; then
                saveAutoConfig "$each_key" "1"
            else
                saveAutoConfig "$each_key" "0"
            fi
        done
                
        for each_key in `getKeys "$ALL_OPTIONAL_COMPONENTS"`
        do 
            optional=`getProductAttr "$ALL_OPTIONAL_COMPONENTS" "$each_key" "OPTIONAL"`
            for opt_comp_key in `$CMD_ECHO "$optional"` ; do
                checkString "$ALL_SELECTED_OPTIONALS" "${each_key}:${opt_comp_key}"
                if [ $? -eq 0 ] ; then
                    saveAutoConfig "OPTIONAL_COMPONENT:${each_key}:${opt_comp_key}" "1"
                else
                    saveAutoConfig "OPTIONAL_COMPONENT:${each_key}:${opt_comp_key}" "0"
                fi
            done        
        done        
    fi
    
} 

removeOldAddons() {
    tmp_basedir=`$CMD_PKGPARAM SUNWescom BASEDIR`
    uninst_cmd="$tmp_basedir/SUNWsymon/sbin/es-uninst"
    [ ! -f "$uninst_cmd" ] && uninst_cmd="${SCRIPT_DIR}/es-uninst"
    [ ! -f "$uninst_cmd" ] && exit_SunMC "$UNINST_ERROR"

    Keep_Data=1
    export Keep_Data
    for PRODUCT_KEY in `$CMD_ECHO "$UNINST_KEYS"`
    do
        name=`getProductAttr "$SOURCE_LIST" $PRODUCT_KEY "NAME"`
        echolog 'Removing installed Add-On: $2' "$name"
        $uninst_cmd -r $PRODUCT_KEY
        if [ $? -ne 0 ] ; then
            if [ -z "$FAIL_LIST" ] ; then
                    FAIL_LIST="KEY=${PRODUCT_KEY}#BECAUSE=uninst"
            else
                    FAIL_LIST="${FAIL_LIST}@KEY=${PRODUCT_KEY}#BECAUSE=uninst" 
            fi
        fi
    done
}



sortByCD() {

[ -z "$SELECTED_KEYS" ] && return 

#first, make product list into component list

ALL_COMPONENTS_LIST=""
SORTED_INSTALL_COMPONENTS_LIST=""

[ -z "$INSTALL_KEYS" ] && return

for PRODUCT_KEY in `$CMD_ECHO "$INSTALL_KEYS"`
do
    
    component_list="`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" INSTALL_COMPONENTS`"
    [ -z "$component_list" ] && continue
    
    COMPONENTS_LIST=""
    SORTED_COMPONENTS_WITH_LAST=""
    for each_component in `$CMD_ECHO "$component_list"` ; do
        each_component="${each_component}:${PRODUCT_KEY}"
        if [ -z "$COMPONENTS_LIST" ] ; then
            COMPONENTS_LIST="${each_component}"
        else
            COMPONENTS_LIST="${COMPONENTS_LIST} ${each_component}"
        fi
    done
    
    SORTED_COMPONENTS=`$CMD_ECHO "${COMPONENTS_LIST}" | $CMD_AWK 'BEGIN{RS=" "} {print}' | $CMD_SORT -n -t : -k 3 | $CMD_AWK 'BEGIN{ORS=" "} {print}'`
    
    SORTED_COMPONENTS_WITH_LAST=`$CMD_ECHO "${SORTED_COMPONENTS}" | $CMD_AWK -F' ' 'BEGIN{ORS=" "} {for (i = 1; i <= NF; i++) if (i == NF) print $i ":LAST"; else print $i }'`

    if [ -z "$ALL_COMPONENTS_LIST" ] ; then
        ALL_COMPONENTS_LIST="${SORTED_COMPONENTS_WITH_LAST}"
    else
        ALL_COMPONENTS_LIST="${ALL_COMPONENTS_LIST} ${SORTED_COMPONENTS_WITH_LAST}"
    fi
    
done

#now, sort in CD order. The CD number is the fourth field

SORTED_INSTALL_COMPONENTS_LIST=`$CMD_ECHO "${ALL_COMPONENTS_LIST}" | $CMD_AWK 'BEGIN{RS=" "} {print}' | $CMD_SORT -n -t : -k 3 | $CMD_AWK 'BEGIN{ORS=" "} {print}'`


}



 
# input:  SOURCE_LIST
# return:  AVAILABLE_KEYS 
# 
listAllAvailableProducts() { 

    [ "$SOURCE_IMAGE" = "PATCH_ONLY" ] && return 
    incremental_install=0
    AVAILABLE_KEYS=""
    FILTERED_KEYS=""
    FILTERED_LIST=""
    
    #first seperate only filtered products
    for key in `getKeys "$SOURCE_LIST"`
    do
        filtered=`getProductAttr "$SOURCE_LIST" "$key" "ALL_COMPONENTS"`
        [ -z "$filtered" ] && continue
        FILTERED_KEYS="${FILTERED_KEYS} ${key}"
        FILTERED_LIST=`copyProduct "$key" "$SOURCE_LIST" "$FILTERED_LIST"`
    done 
    
  
    for PRODUCT_KEY in `$CMD_ECHO "$FILTERED_KEYS"`
    do
     #first check if already fully installed
        checkString "$ALREADY_INSTALLED_LIST" "$PRODUCT_KEY"        
        [ $? -eq 0 ] && continue
        AVAILABLE_KEYS="${AVAILABLE_KEYS} $PRODUCT_KEY"
    done   
    
}


# requires SOURCE_LIST and scans through all products in it
# ignores product if any available package is not yet installed (product installable)
# adds key to ALREADY_INSTALLED_LIST if all installable packages are already installed
# adds key, source version and installed version to MISMATCH_LIST if a single package
# of a single component is mismatched.
#
#
setAllInstalledOrMismatched() {

[ "$SOURCE_IMAGE" = "PATCH_ONLY" ] && return

MISMATCH_LIST=""
ALREADY_INSTALLED_LIST=""
ALREADY_INSTALLED_COMPONENTS=""

#
# first check if this is a fresh install
#
$CMD_PKGINFO $RELOC_PARAM -qic "symon"
[ $? -eq 1 ] && return

for PRODUCT_KEY in `getKeys "$SOURCE_LIST"`
do
    install_product=0              
    product_mismatched=0    
    ALL_COMPONENT_LIST=`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" "ALL_COMPONENTS"`
    [ -z "$ALL_COMPONENT_LIST" ] && continue

    for component_string in `$CMD_ECHO "$ALL_COMPONENT_LIST"`
    do 
        COMPONENT_KEY=`$CMD_ECHO "$component_string" | $CMD_AWK -F ':' '{ print $1 }'`
        tmp_packages=`$CMD_ECHO "$component_string" | $CMD_AWK -F ':' '{ print $2 }'`
        
        # Check if the packages for the component have already been installed    
        packagesExist "$tmp_packages"        
        ret=$?       
            
        if [ $ret -eq 1 ] ; then 
            #
            # this component is completely installed
            #
            ALREADY_INSTALLED_COMPONENTS="${ALREADY_INSTALLED_COMPONENTS} ${PRODUCT_KEY}:${COMPONENT_KEY}"
            continue #to next component            
        elif [ $ret -eq 2 ] ; then 
            #
            # some package is mismatched  
            #          
            if [ -z "$MISMATCH_LIST" ] ; then
                MISMATCH_LIST="KEY=${PRODUCT_KEY}#SV=${spkg}#IV=${ipkg}"
            else
                MISMATCH_LIST="${MISMATCH_LIST}@KEY=${PRODUCT_KEY}#SV=${spkg}#IV=${ipkg}"
            fi
            product_mismatched=1            
            break #dont check more components
        else 
            #
            # all or some packages dont exist
            #            
            install_product=1
        fi
        
    done
    
    if [ $install_product -eq 0 -a $product_mismatched -eq 0 ] ; then  #already installed fully
        ALREADY_INSTALLED_LIST="${ALREADY_INSTALLED_LIST} ${PRODUCT_KEY}"
        $API_SET_ATTRIBUTE "$REGISTRY" "category=SunMC" "product=$PRODUCT_KEY" "install-status=1" >/dev/null 2>&1
    fi
done
}

#  reads    : PRODUCT_KEY COMPONENT_KEY COMPONENT_FILTERS_LIST
#  checks   : LAYER, LANG, SCRIPT   
#  returns  : skip_component, skip_product  
# 
filterComponent() {
    skip_component=0
    skip_product=0      

    COMPONENT_INFO=`getProductAttr "$COMPONENT_FILTERS_LIST" "$PRODUCT_KEY" "$COMPONENT_KEY.SCRIPT"`
    [ -z "$COMPONENT_INFO" ] && return    
    
    
    # Execute the specified component script          
    SUBDIR=`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" "SUBDIR"`            
    getCorrectDirectory "$SUBDIR"       
    if [ $? -eq 1 -a -f "${CORRECT_DIR}/$COMPONENT_INFO" ] ; then # Component script found
        #Added the paranthesis to call the component scripts in 
        #sub-shell for bug  4394793
        echologverbose 'Component script found: $2' "$COMPONENT_INFO"
        COMPONENT_SCRIPT_FILE="${CORRECT_DIR}/$COMPONENT_INFO"
            
        if [ "$PROGNAME" = "archive-tool" ] ; then # smart-update
            COMPONENT_SCRIPT_FILE=`$CMD_BASENAME $COMPONENT_SCRIPT_FILE`
            COMPONENT_SCRIPT_LIST="$COMPONENT_SCRIPT_LIST $PRODUCT_KEY:$OSVERS:$COMPONENT_SCRIPT_FILE"     #smart-update
            return
        fi  # smart-update
            
        (. $COMPONENT_SCRIPT_FILE                    
        runComponentScript )
        comp_script_retcode=$?
        echologverbose 'Running: $2' "$COMPONENT_SCRIPT_FILE"
        echologverbose 'Return value: $2' "$comp_script_retcode"              
        if [ $comp_script_retcode -eq 2 ] ; then
            #
            #Script returned 2, means skip this component.
            #
            echologverbose 'Script returned 2. Skipping this component.'
            if [ -z "$COMPONENTS_NOT_TO_BE_INSTALLED" ] ; then
                COMPONENTS_NOT_TO_BE_INSTALLED="$PRODUCT_KEY:$COMPONENT_KEY"
            else
                COMPONENTS_NOT_TO_BE_INSTALLED="$COMPONENTS_NOT_TO_BE_INSTALLED,$PRODUCT_KEY:$COMPONENT_KEY"
            fi                        
            skip_component=1
            return
        elif [ $comp_script_retcode -ne 1 ] ; then
                #
                #Script returned either 0 or something unknown. Dont install this product
                #
                echologverbose 'Script returned either 0 or something unknown. Skipping this product.'
                skip_product=1
                return                
        fi 
        #
        #Script returned 1, So proceed with normal processing.
    fi                    
 
}       
        
# Checks whether a product is valid, ie filtered for installation
# reads  : PRODUCT_KEY
# Return: 1 if valid; 0 otherwise
# function called originally only by installAddons in es-inst
# Returns : OPTIONAL_COMPONENTS="COMPONENTKEY:COMPONENTNAME:INSTALLED,COMPONENTKEY:COMPONENTNAME:INSTALLED,COMPONENTKEY:COMPONENTNAME:INSTALLED"
#

isProductInstallable() {

    product_installable=0    
    ALL_COMPONENT_LIST="" 
    
    if [ "$PRODUCT_KEY" = "${BASE_PRODUCT_KEY}" ] ; then
        INSTALL_TYPE="BASE"      
    else
        INSTALL_TYPE="ADDON"
    fi
    
    inst_base_dir=`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" "TARGET_DIR"`
    
    # " " indicates not found yet
    #
    [ -z "$inst_base_dir" ] && inst_base_dir=" " 
        
    version=`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" "VERSION"` 
    PRODVERS=""
    
    COMPONENT_LIST=`getProductAttr "$INIT_COMP_DETAILS" "$PRODUCT_KEY" "COMPONENT_LIST"` 
    
    tmp_comp_list=`getProductAttr "$INIT_COMP_DETAILS" "$PRODUCT_KEY" "COMP_DETAILS"` 
    
    for COMPONENT_KEY in `$CMD_ECHO "$COMPONENT_LIST" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
    do
        component_installable=0       
        #the following are skipped for 2.X
        
        if [ "$version" = "3X" ] ; then
            filterComponent
            [ $skip_product -eq 1 ] && return 0
            [ $skip_component -eq 1 ] && continue
        fi   
        
        for tmp_comp in `$CMD_ECHO "$tmp_comp_list"`
        do
            EACH_COMP=`$CMD_ECHO "$tmp_comp" | $CMD_AWK -F ':' '{ print $1 }'`
            [ "$EACH_COMP" != "${COMPONENT_KEY}" ] && continue
            TMP_PACKAGE_LIST=`$CMD_ECHO "$tmp_comp" | $CMD_AWK -F ':' '{ print $2 }'`
            TMP_CD=`$CMD_ECHO "$tmp_comp" | $CMD_AWK -F ':' '{ print $3 }'`
            #we now have the correct value for EACH_COMP, TMP_CD and TMP_PACKAGE_LIST
            break        
        done
        
        CONFIRM_PACKAGES=""
        FILTERED_PACKAGES=""
        
        for EACH_PACKAGE in `$CMD_ECHO "$TMP_PACKAGE_LIST" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
        do
            filterPackage "$EACH_PACKAGE"                      
            if [ $? -eq 1 ] ; then 
                
                component_installable=1 #if even one package is installable / archivable
                if [ "$OPTIMIZE_FOR_ES_INST" = "0" -a "$inst_base_dir" = " "  ] ; then
                    [ "${PRODUCT_KEY}" != "${BASE_PRODUCT_KEY}" ] && inst_base_dir=`getInstBaseDir "$PACKAGE_DIR"`
                fi
                if [ "$FILTERED_PACKAGES" = "" ] ; then
                    FILTERED_PACKAGES="$EACH_PACKAGE"
                else
                    FILTERED_PACKAGES="${FILTERED_PACKAGES},$EACH_PACKAGE"
                fi
                
                if [ "$CONFIRM" = "1" ] ; then
                    if [ -z "$CONFIRM_PACKAGES" ] ; then
                        CONFIRM_PACKAGES="${EACH_PACKAGE}"
                    else
                        CONFIRM_PACKAGES="${CONFIRM_PACKAGES},${EACH_PACKAGE}"
                    fi
                fi
            fi
        done
        
        if [ $component_installable -eq 0 ] ; then
            if [ -z "$COMPONENTS_NOT_TO_BE_INSTALLED" ] ; then
                COMPONENTS_NOT_TO_BE_INSTALLED="$PRODUCT_KEY:$COMPONENT_KEY"
            else
                COMPONENTS_NOT_TO_BE_INSTALLED="$COMPONENTS_NOT_TO_BE_INSTALLED,$PRODUCT_KEY:$COMPONENT_KEY"
            fi
        else
            product_installable=1            
            if [ -z "$ALL_COMPONENT_LIST" ] ; then
                ALL_COMPONENT_LIST="${EACH_COMP}:${FILTERED_PACKAGES}:${TMP_CD}:${CONFIRM_PACKAGES}"
            else
                ALL_COMPONENT_LIST="${ALL_COMPONENT_LIST} ${EACH_COMP}:${FILTERED_PACKAGES}:${TMP_CD}:${CONFIRM_PACKAGES}"
            fi                            
        fi                         
    done
    
    if [ $product_installable -eq 1 ] ; then
        getPackageVersion "${PACKAGE_DIR}" #last package seen, as SUNWPRODVERS is going to be the same for all
        SOURCE_LIST=`addAttributesToProduct "$SOURCE_LIST" "$PRODUCT_KEY" "PRODVERS=${PACKAGE_VERSION}"`
        if [ "$OPTIMIZE_FOR_ES_INST" = "0" -o "${inst_base_dir}" != " " ] ; then
            SOURCE_LIST=`addAttributesToProduct "$SOURCE_LIST" "$PRODUCT_KEY" "TARGET_DIR=${inst_base_dir}"`        
        fi
        SOURCE_LIST=`addAttributesToProduct "$SOURCE_LIST" "$PRODUCT_KEY" "ALL_COMPONENTS=${ALL_COMPONENT_LIST}"` 
        return 1
    fi
    return 0

}

# Checks whether an addon package can be installed
# $1 - full pathname of package directory
# Return: 1 if it is installable; 0 otherwise sets flag CONFIRM
filterPackage() {
    # to be depricated ES_ADDON_VERSION
    #                  ES_ADDON_COMPONENT
    #                  ES_ADDON_PACKAGE_DEPENDENCY
    #                  ES_ADDON_DIRECTORY_DEPENDENCY
    #      
    
    getPackageDirectory "$1"
    [ $? -eq 0 ] && return 0 
    pkginfo="$TMP_DIR/pkginfo.$$"

    $CMD_CP -f ${PACKAGE_DIR}/pkginfo $pkginfo 
    
    # Make sure the CATEGORY of this package includes symon
    category_value=`$CMD_PKGPARAM -f $pkginfo CATEGORY`
    $CMD_ECHO ${category_value} | $CMD_GREP -i symon > /dev/null 2>&1
    [ $? -ne 0 ] && return 0
        
    CONFIRM=0
    confirm_value=`$CMD_PKGPARAM -f $pkginfo ES_ADDON_CONFIRM`
    if [ -n "$confirm_value" ] ; then
        confirm_value=`$CMD_ECHO "$confirm_value" | $CMD_TR [A-Z] [a-z]`
        [ "$confirm_value" = "true" ] && CONFIRM=1        
    fi
    
    # Skip if the package is not on the selected layers
    addon_comp=`$CMD_PKGPARAM -f $pkginfo ES_ADDON_COMPONENT`
    if [ "$addon_comp" != "" ] ; then
        case $addon_comp in
            console) TEST=`$CMD_ECHO $INSTALL_LAYERS | $CMD_GREP "LAYER.CONSOLE"`
                [ "$TEST" = "" ] && return 0
                ;;
            server)  TEST=`$CMD_ECHO $INSTALL_LAYERS | $CMD_GREP "LAYER.SERVER"`
                [ "$TEST" = "" ] && return 0
                ;;
            agent)   TEST=`$CMD_ECHO $INSTALL_LAYERS | $CMD_GREP "LAYER.AGENT"`
                [ "$TEST" = "" ] && return 0
                ;;
        esac
    fi    
   
    # archive-tool does not need to make any further checks
    #     
    [ "$PROGNAME" = "archive-tool" ] && return 1
      
    # If this value is blank or matches the current platform, display
    # addon for user selection, otherwise skip it.
    PLATFORMLIST=`$CMD_PKGPARAM -f $pkginfo ES_ADDON_PLATFORM`
    if [ "$PLATFORMLIST" != "" ] ; then
        tmp_platform_match=""
        OLDIFS=$IFS 
        IFS=: 
        for each_platform in $PLATFORMLIST
        do
            checkString "$PRTOUT" "$each_platform"
            if [ $? -eq 0 ] ; then
                tmp_platform_match="$each_platform"
                break
            fi
        done
        IFS="$OLDIFS"
        [ "$tmp_platform_match" = "" ] && return 0
    fi
        
    # If any of the packages are not present on the host, skip installation of this package.
    PKGDEP=`$CMD_PKGPARAM -f $pkginfo ES_ADDON_PACKAGE_DEPENDENCY`
    for pkg in $PKGDEP
    do
        $CMD_PKGINFO $RELOC_PARAM -qi "$pkg"
        [ $? -ne 0 ] && return 0        
    done
    
    # If any of the directories are not present on the host, skip installation of this package.
    PKGDIRDEP=`$CMD_PKGPARAM -f $pkginfo ES_ADDON_DIRECTORY_DEPENDENCY`
    skip=0
    for dir in $PKGDIRDEP
    do
        [ $skip -eq 1 ] && break # File not found
        [ ! -d "${RELOCATED_ROOT}/$dir" ] && skip=1 && break # Dir not found

        # If any of the files are not present on the host, skip installation of this package.
        PKGFILEDEP=`$CMD_PKGPARAM -f $pkginfo ES_ADDON_FILE_DEPENDENCY`
        for file in $PKGFILEDEP
        do
            [ ! -f "${RELOCATED_ROOT}/${dir}/$file" ] && skip=1 && break
        done
    done
    [ $skip -eq 1 ] && return 0
    
    SYMVER=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "version" 2>/dev/null` 

    if [ -n "$SYMVER" ] ; then
         checkString  "$SYMVER" "_" # Check to see if it has an underscore
         [ $? -eq 0 ] && SYMVER=`$CMD_EXPR "$SYMVER" : '\(.*\)_'` # Remove all after the underscore
    else
        SYMVER=$SRC_PKGVER #Base not installed yet.
    fi  

    PKGVER=`$CMD_PKGPARAM -f $pkginfo ES_ADDON_VERSION`
    if [ "$PKGVER" != "" ] ; then
        if [ "$PKGVER" != "$SYMVER" ] ; then # If the versions match then we are OK
            compareVersions "$PKGVER" "$SYMVER"
            [ $? -ne 0 ] && return 0
        fi
    fi
    
    return 1 
}


# Compare package version (for SunMC 2.1 addon packages)
# $1 - minimum version number of the package
# $2 - the version number of the current install
# Return: 0 = compare successful
compareVersions() {
    # We need to compare the minimum version (PKGVER) with the actual version (SYMVER).
    # This is a little tricky. We have to make some assumptions about the form of the
    # Symon version number. Assume it is of the form X.X[.X].
    # We already know that the versions are not equal

    #  Break up the version number into major version (X.X) and anything after that
    pkg_maj=`$CMD_EXPR "$1" : '\(...\).*'`
    sym_maj=`$CMD_EXPR "$2" : '\(...\).*'`
    if [ "$pkg_maj" != "$sym_maj" ] ; then
    first_maj=`echo "$pkg_maj\n$sym_maj" | $CMD_SORT | $CMD_HEAD -1`
    [ "$first_maj" = "$pkg_maj" ] && return 0
    return 1
    fi

    # The major numbers must be equal
    pkg_min=`$CMD_EXPR "$1" : '....\(.\)'`
    sym_min=`$CMD_EXPR "$2" : '....\(.\)'`
    [ -z "$pkg_min" ] && [ -n "$sym_min" ] && return 0
    [ -n "$pkg_min" ] && [ -z "$sym_min" ] && return 1
    if [ -n "$pkg_min" ] && [ -n "$sym_min" ] ; then
        first_min=`echo "$pkg_min\n$sym_min" | $CMD_SORT | $CMD_HEAD -1`
    [ "$first_min" = "$pkg_min" ] && return 0
    return 1
    fi

    return 1
}

# << END addon related functions<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #

# Adds product specific info to the registry if not present  
registerAllProducts() {

[ "$SOURCE_IMAGE" = "PATCH_ONLY" ] && return

[ -z "$SELECTED_KEYS" ] && return

    $API_SET_ATTRIBUTE "$REGISTRY" "category=Installation" "config_dir=${VAROPTDIR}" > /dev/null 2>&1
    if [ $HA_INSTALL -eq 1 ] ; then
        $API_SET_ATTRIBUTE "$REGISTRY" "category=Installation" "global_config_dir=${GLOBAL_DIR}" > /dev/null 2>&1
    fi      
    layers_in_registry=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "layer" "key" 2>/dev/null`
    #[ $? -gt 0 ] && EXIT_FLAG=$REGISTRY_READ_ERROR && exit_SunMC
        
    for layer in `$CMD_ECHO "$INSTALL_LAYERS" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
    do
        checkString "$layers_in_registry" "$layer"
        [ $? -ne 0 ] && $API_INSERT_TAG "$REGISTRY" "category=Installation" "layer=${layer}" > /dev/null 2>&1
        t_setup=""
        t_setup=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "layer=${layer}" "setup-status" 2>/dev/null`
        [ "$t_setup" != "1" ] && $API_SET_ATTRIBUTE "$REGISTRY" "category=Installation" "layer=${layer}" "setup-status=0" > /dev/null 2>&1
    done
        
    locales_in_registry=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "locale" "key" 2>/dev/null`
    #[ $? -gt 0 ] && EXIT_FLAG=$REGISTRY_READ_ERROR && exit_SunMC
        
    for locale in `$CMD_ECHO "$INSTALL_LOCALES" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
    do
        checkString "$locales_in_registry," "$locale,"
        [ $? -ne 0 ] && $API_INSERT_TAG "$REGISTRY" "category=Installation" "locale=${locale}" > /dev/null 2>&1
    done   

for PRODUCT_KEY in `$CMD_ECHO "$SELECTED_KEYS"` ; do
    if [ "$PRODUCT_KEY" != "${BASE_PRODUCT_KEY}" ] ; then        
        checkString "$INSTALL_KEYS" "$PRODUCT_KEY"    
        [ $? -ne 0 ] && continue
    fi 
    
    products_in_registry=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product" "key" 2>/dev/null`
    #[ $? -gt 0 ] && EXIT_FLAG=$REGISTRY_READ_ERROR && exit_SunMC
    
    checkString "$products_in_registry" "$PRODUCT_KEY"
    [ $? -ne 0 ] && $API_INSERT_TAG "$REGISTRY" "category=SunMC" "product=${PRODUCT_KEY}" > /dev/null 2>&1
    
    name=`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" "NAME"`
    sdir=`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" "TARGET_DIR"`
    prodvers=`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" "PRODVERS"`
    
    
    $API_SET_ATTRIBUTE "$REGISTRY" "category=SunMC" "product=${PRODUCT_KEY}" "name=${name}" > /dev/null 2>&1     
    
    if [ "$PRODUCT_KEY" != "${BASE_PRODUCT_KEY}" ] ; then
        $API_SET_ATTRIBUTE "$REGISTRY" "category=SunMC" "product=${PRODUCT_KEY}" "version=${prodvers}" > /dev/null 2>&1
        $API_SET_ATTRIBUTE "$REGISTRY" "category=SunMC" "product=${PRODUCT_KEY}" "target_subdir=${sdir}" > /dev/null 2>&1
    else
        $API_SET_ATTRIBUTE "$REGISTRY" "category=SunMC" "product=${PRODUCT_KEY}" "version=${SRC_PKGVER}" > /dev/null 2>&1
        $API_SET_ATTRIBUTE "$REGISTRY" "category=SunMC" "product=${PRODUCT_KEY}" "target_subdir=${TARGET_DIR}" > /dev/null 2>&1
    fi
    
    $API_SET_ATTRIBUTE "$REGISTRY" "category=SunMC" "product=${PRODUCT_KEY}" "install-status=0" > /dev/null 2>&1
    
    $API_SET_ATTRIBUTE "$REGISTRY" "category=SunMC" "product=${PRODUCT_KEY}" "setup-status=0" > /dev/null 2>&1

    depends_on=`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" "DEPENDS_ON"`
    $API_SET_ATTRIBUTE "$REGISTRY" "category=SunMC" "product=${PRODUCT_KEY}" "depends-on=${depends_on}" > /dev/null 2>&1
done

}

manageFailedProducts() {

[ "$SOURCE_IMAGE" = "PATCH_ONLY" ] && return
 
[ -z "$FAIL_LIST" ] && return
    
    echolog 'Installation of the following products was unsuccessful'
    echologverbose '$2' $LOG_LINE
    echolog ''
    
    for each_key in `getKeys "$FAIL_LIST"`
    do 
        prod_name=`getProductAttr "$SOURCE_LIST" "${each_key}" "NAME"`
        because=`getProductAttr "$FAIL_LIST" "${each_key}" "BECAUSE"`
        
        echolog 'Product: $2' "$prod_name"
    
        if [ "$because" = "uninst" ] ; then
            echolog 'ERROR: Product upgrade failed.'
        elif [ "$because" = "packages" ] ; then
            echolog 'WARNING: One or more packages were not successfully added.'
        fi
        f_packages=`$API_QUERY_REGISTRY "$REGISTRY" "product=${each_key}" "package" "key" WHERE "status=0" 2>/dev/null`            
        #[ $? -gt 0 ] && EXIT_FLAG=$REGISTRY_READ_ERROR && exit_SunMC
        
        if [ -n "$f_packages" ] ; then
            echolog 'The following packages were not properly installed: ' 
            echolog '   $2' "$f_packages" 
            echologverbose '$2' $LOG_LINE
            echolog '' 
        fi    
    done
}



# << BEGIN space checking functions<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #

performSpaceChecks() {
    [ -z "$SELECTED_KEYS" ] && return 
    [ -z "$INSTALL_KEYS" ] && return
    initializeSpaceVars
    getAllFixedInfo
    while [ 1 -eq 1 ] ; do    
        getAllRelocatableInfo
        checkDiskSpace
        [ $TARGET_OK -eq 1 ] && [ $DB_TABLES_OK -eq 1 ] && break
        [ $TARGET_OK -eq 0 ] && relocate $TARGET_DIR $AVAILABLE_SPACE_TARGET_DIR $REQUIRED_SPACE_TARGET_DIR && continue
        [ $DB_TABLES_OK -eq 0 ] && relocate $DB_TABLES_DIR $AVAILABLE_SPACE_DB_TABLES $REQUIRED_SPACE_DB_TABLES && continue
    done 
}

#
#  Working parameter initializations
#
initializeSpaceVars() {
 
    quit_program=0 #To remove

    FS_TARGET_DIR=""
    FS_DB_TABLES=""
    FS_ROOT=""
    
    REQUIRED_SPACE_TARGET_DIR=0
    AVAILABLE_SPACE_TARGET_DIR=0
    REQUIRED_SPACE_SUNMC_PRODUCTS=0
    REQUIRED_SPACE_DB_SOFTWARE=0    
    DB_DIR="${SRC_DIR}/db"
    
    REQUIRED_SPACE_DB_TABLES=0
    AVAILABLE_SPACE_DB_TABLES=0
    #DB_TABLES_DIR="${VAROPTDIR}"
    DB_TABLES_DIR="/var/opt/SUNWsymon"
    
    REQUIRED_SPACE_ROOT=0
    AVAILABLE_SPACE_ROOT=0 
    
    #REQUIRED_SPACE_WBSVR is set already
    
    BASE_PRODUCT_SERVER_INSTALL=0
    checkString "${INSTALL_KEYS}" "${BASE_PRODUCT_KEY}"
    if [ $? -eq 0 ] ; then #no PE
        checkString "${INSTALL_LAYERS}" "LAYER.SERVER"
        [ $? -eq 0 ] && BASE_PRODUCT_SERVER_INSTALL=1 
    fi
    
    #
    #  If the directories don't already exist, create them
    #
    [ -n "$TARGET_DIR" -a ! -d "$TARGET_DIR" ] && $CMD_MKDIR -p "$TARGET_DIR"
    
    [ -n "$DB_TABLES_DIR" -a ! -d "$DB_TABLES_DIR" ] && $CMD_MKDIR -p "$DB_TABLES_DIR"   
    
}


#$1 full package directory
# reads PRODUCT_KEY

# returns 1 if map file for package isnt found - cant get space data
getPackageSize() {

package=`$CMD_BASENAME $1`

MAPFILE="${1}/pkgmap"

if [ ! -f "$MAPFILE" ] ; then
    echolog 'Warning - Could not find the pkgmap file for $2' "$package"
    echolog "  Space calculations will be wrong."
    return 1
fi

pkg_size=`$CMD_HEAD -10 "$MAPFILE" | $CMD_GREP '^:' | $CMD_AWK '{ print $3 }'`
pkg_size=`$CMD_EXPR $pkg_size`

$CMD_ECHO $pkg_size
}


# Calculate the required disk space
# $1 - the BASEDIR directory
getRequiredSpaceForBasedir() {
    REQUIRED_SPACE=0
    
    for each_pkglist in `$CMD_ECHO "${SORTED_INSTALL_COMPONENTS_LIST}"` ; do

    
        PRODUCT_KEY=`$CMD_ECHO "$each_pkglist" | $CMD_AWK -F ':' '{ print $4 }'`
        each_pkglist=`$CMD_ECHO "$each_pkglist" | $CMD_AWK -F ':' '{ print $2 }'`
        for each_pkg in `$CMD_ECHO "$each_pkglist" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'` ; do             
            getPackageDirectory "$each_pkg"
       
            required_space=`getPackageSize "${PACKAGE_DIR}"` 
       
            pkg_base=`$CMD_PKGPARAM -f "${PACKAGE_DIR}/pkginfo" BASEDIR`
            if [ "$pkg_base" != "$1" ] ; then
                continue
            fi
                      
            required_space=`$CMD_EXPR $required_space` 
           
            REQUIRED_SPACE=`$CMD_EXPR $required_space + $REQUIRED_SPACE`
       
       
        done
    
    done
}


# Check disk space for SUNWesora and for SUNWestbl, if not yet installed
# Return: $REQUIRED_SPACE_DB_SOFTWARE - SUNWesora
# Return: $REQUIRED_SPACE_DB_TABLES - SUNWestbl
getDatabaseRequiredSpace() {
    
    REQUIRED_SPACE_DB_SOFTWARE=`getPackageSize "$DB_DIR/SUNWesora"`
    retcode=$?
    
    [ $retcode -eq 1 ] && return 1
    REQUIRED_SPACE_DB_SOFTWARE=`$CMD_EXPR $REQUIRED_SPACE_DB_SOFTWARE`
    
    $CMD_PKGINFO $RELOC_PARAM -q SUNWestbl
    retcode=$?
    
    if [ $retcode -gt 0 ] ; then     
      REQUIRED_SPACE_DB_TABLES=`getPackageSize $DB_DIR/SUNWestbl`
      REQUIRED_SPACE_DB_TABLES=`$CMD_EXPR $REQUIRED_SPACE_DB_TABLES + 200 \* 1024 \* 2`
    fi
    
    return 0
}


# returns: REQUIRED_SPACE_TARGET_DIR (products + database software)
#          REQUIRED_SPACE_ROOT
#          AVAILABLE_SPACE_ROOT
#          REQUIRED_SPACE_DB_TABLES (0 if NA)
#          FS_ROOT
#
getAllFixedInfo() {
    
    if [ -n "$RELOCATED_ROOT" -a "$RELOCATED_ROOT" != "/" ] ; then
        getRequiredSpaceForBasedir "$RELOCATED_ROOT"
    else   
        getRequiredSpaceForBasedir "/" 
    fi
    REQUIRED_SPACE_ROOT=$REQUIRED_SPACE
    
    if [ $INSTALL_WEBSERVER -eq 1 ] ; then
        REQUIRED_SPACE_ROOT=`$CMD_EXPR $REQUIRED_SPACE_ROOT + $REQUIRED_SPACE_WBSVR`    
    fi
    
    getAvailableSpace "$RELOCATED_ROOT/$ROOT"    
    AVAILABLE_SPACE_ROOT=$AVAILABLE_SPACE
    
    getFileSystem "$RELOCATED_ROOT/$ROOT"
    FS_ROOT=$FILESYSTEM_NAME
     
    
    if [ $AVAILABLE_SPACE_ROOT -lt $REQUIRED_SPACE_ROOT ] ; then
        echolog 'Insufficient disk space on the root partition'
        echolog 'Space required is: $2 Blocks' "$REQUIRED_SPACE_ROOT"
        echolog 'Space currently available is: $2 Blocks' "$AVAILABLE_SPACE_ROOT"
        echolog 'You must ensure that $2 Blocks are available on the root partition' "$REQUIRED_SPACE_ROOT"
        exit_SunMC "$BAD_TARGET_DIR"    
    fi
 
    # If no space in root partition then exit. Otherwise package add will fail.
    if [ $AVAILABLE_SPACE_ROOT -eq 0 ] ; then
        echolog 'Insufficient disk space on the root partition'
        echolog 'Space currently available is: $2 Blocks' "$AVAILABLE_SPACE_ROOT"
        exit_SunMC "$BAD_TARGET_DIR"
    fi

    # SunMC/Addon disk space requirement
    getRequiredSpaceForBasedir "/opt"    
    REQUIRED_SPACE_SUNMC_PRODUCTS=$REQUIRED_SPACE
        
    # Oracle disk space requirement
    # This  should be done only if base product, server is to be installed.

    [ $BASE_PRODUCT_SERVER_INSTALL -eq 1 ] && getDatabaseRequiredSpace

    REQUIRED_SPACE_TARGET_DIR=`$CMD_EXPR $REQUIRED_SPACE_SUNMC_PRODUCTS + $REQUIRED_SPACE_DB_SOFTWARE`
   
}


# reads: TARGET_DIR, DB_TABLES_DIR, JAVA_DIR
#        
# returns: FS_TARGET_DIR
#          AVAILABLE_SPACE_TARGET_DIR
#          FS_DB_TABLES
#          AVAILABLE_SPACE_DB_TABLES
#
getAllRelocatableInfo() {
    # SunMC/Addon disk space requirement
    #new version of getAvailableSpace and getFileSystem used here
    
    getFileSystem "$TARGET_DIR"
    FS_TARGET_DIR=$FILESYSTEM_NAME         
             
    getAvailableSpace "$TARGET_DIR"     
    AVAILABLE_SPACE_TARGET_DIR=$AVAILABLE_SPACE
     
       
    if [ $BASE_PRODUCT_SERVER_INSTALL -eq 1 ] ; then
    
        getFileSystem "${RELOCATED_ROOT}${DB_TABLES_DIR}"
        FS_DB_TABLES=$FILESYSTEM_NAME 
                         
        getAvailableSpace "${RELOCATED_ROOT}${DB_TABLES_DIR}"
        AVAILABLE_SPACE_DB_TABLES=$AVAILABLE_SPACE             
    fi
    
}


# $1 - some space requirement
# $2 - some space available
# 
# This function sets the values of 8 variables to 0 or 1, so that the appropriate one can be used 
# based on the caller's context. These variables are:
#
# OK            1 if $1 < $2
# OK_wt_DB        1 if $1+$REQUIRED_SPACE_DB_TABLES < $2 
# OK_wt_ROOT         1 if $1+$REQUIRED_SPACE_ROOT < $2
# OK_wt_TARGET        1 if $1+$REQUIRED_SPACE_TARGET_DIR < $2
# OK_wt_DB_ROOT        1 if $1+$REQUIRED_SPACE_DB_TABLES+$REQUIRED_SPACE_ROOT < $2
# OK_wt_DB_TARGET    1 if $1+$REQUIRED_SPACE_DB_TABLES+$REQUIRED_SPACE_TARGET_DIR < $2
# OK_wt_ROOT_TARGET    1 if $1+$REQUIRED_SPACE_ROOT+$REQUIRED_SPACE_TARGET_DIR < $2
# OK_wt_DB_ROOT_TARGET    1 if $1+$REQUIRED_SPACE_DB_TABLES+$REQUIRED_SPACE_ROOT+$REQUIRED_SPACE_TARGET_DIR < $2
#

checkForSpace() {
req=$1
avail=$2

OK=0
OK_wt_DB=0
OK_wt_ROOT=0 
OK_wt_TARGET=0
OK_wt_DB_ROOT=0
OK_wt_DB_TARGET=0
OK_wt_ROOT_TARGET=0
OK_wt_DB_ROOT_TARGET=0

[ $req -lt $avail ] && OK=1

t_req=`$CMD_EXPR $req + $REQUIRED_SPACE_DB_TABLES`
[ $t_req -lt $avail ] && OK_wt_DB=1

t_req=`$CMD_EXPR $req + $REQUIRED_SPACE_ROOT`
[ $t_req -lt $avail ] && OK_wt_ROOT=1
  
t_req=`$CMD_EXPR $req + $REQUIRED_SPACE_TARGET_DIR`
[ $t_req -lt $avail ] && OK_wt_TARGET=1

t_req=`$CMD_EXPR $req + $REQUIRED_SPACE_DB_TABLES + $REQUIRED_SPACE_ROOT`
[ $t_req -lt $avail ] && OK_wt_DB_ROOT=1

t_req=`$CMD_EXPR $req + $REQUIRED_SPACE_DB_TABLES + $REQUIRED_SPACE_TARGET_DIR`
[ $t_req -lt $avail ] && OK_wt_DB_TARGET=1

t_req=`$CMD_EXPR $req + $REQUIRED_SPACE_ROOT + $REQUIRED_SPACE_TARGET_DIR`
[ $t_req -lt $avail ] && OK_wt_ROOT_TARGET=1

t_req=`$CMD_EXPR $req + $REQUIRED_SPACE_DB_TABLES + $REQUIRED_SPACE_ROOT + $REQUIRED_SPACE_TARGET_DIR`
[ $t_req -lt $avail ] && OK_wt_DB_ROOT_TARGET=1


}


# $1 - directory
# echo's the above directory with a trailslash
addTrailSlashSUNWsymon() {
dir=$1
trailslash=`$CMD_ECHO "$dir" | $CMD_GREP -i '/$' | $CMD_WC -l`
if [ $trailslash = 0 ] ; then
    dir="${dir}/SUNWsymon"
else
    dir="${dir}SUNWsymon"
fi
$CMD_ECHO "$dir"

}


# Get the available disk space
# $1 - the directory
#  
getAvailableSpace() {
    dir=$1
    if [ -d $dir ] ; then

        tmp_var_path=`addTrailSlashSUNWsymon "$dir"`    
        [ -d "$tmp_var_path" ] && dir="$tmp_var_path"        
    
        df_line=`$CMD_DF -k "$dir" | $CMD_TAIL -1`
        AVAILABLE_SPACE=`$CMD_ECHO "$df_line" | $CMD_AWK '{ print $4 }'`
        # Double the number reported by df -k to get 512-byte blocks to get
        # the same units as pkgmap
        
        AVAILABLE_SPACE=`$CMD_EXPR $AVAILABLE_SPACE \* 2`
    else
        AVAILABLE_SPACE=0
    fi
}


# Get the filesystem associated with a directory
# $1 - the directory
getFileSystem() {
    dir=$1
    if [ -d $dir ] ; then
    
        tmp_var_path=`addTrailSlashSUNWsymon "$dir"`
        [ -d "$tmp_var_path" ] && dir="$tmp_var_path"
        
        FILESYSTEM_NAME=`$CMD_DF -k $dir | $CMD_TAIL -1 | $CMD_AWK '{ print $1 }'`
    else
        FILESYSTEM_NAME="unknown"
    fi

   return 0
}



#sets the values of the following : JAVA_OK TARGET_OK DB_TABLES_OK to 1 or 0
#expects:
#
#
# pl. review
#
#
checkDiskSpace() {
   TARGET_OK=0
   DB_TABLES_OK=0

    #if [ "$AUTOCONFIG_RUNFILE" != "" ] ; then
    #   JAVA_OK=1 && TARGET_OK=1 && DB_TABLES_OK=1
    #    echolog 'No space checking for Automatic Installation' 
    #    return
    #fi
    
    #First check for SunMC packages space + SUNWesora space
    echolog ''
    echolog 'Disk Space Checking....'
    
    checkForSpace "$REQUIRED_SPACE_TARGET_DIR" "$AVAILABLE_SPACE_TARGET_DIR"
    # check if target directory is on the same partition as /
    if [ "$FS_TARGET_DIR" = "$FS_ROOT" ] ; then
        [ $OK_wt_ROOT -eq 1 ] && TARGET_OK=1            
    else
        [ $OK -eq 1 ] && TARGET_OK=1            
    fi

    #  Now check for SUNWestbl package space
    #
    #  Determine if the SUNWestbl package already exists on the system, if 
    #  so then don't try to add it again. This logic is to accomadate the
    #  keep existing data option of es-uninst.
    #
    
if [ $BASE_PRODUCT_SERVER_INSTALL -eq 1 ] ; then
    $CMD_PKGINFO $RELOC_PARAM -q SUNWestbl
         
    if [ $? -gt 0 ] ; then
            
        checkForSpace "$REQUIRED_SPACE_DB_TABLES" "$AVAILABLE_SPACE_DB_TABLES"        
    
        if [ "$FS_DB_TABLES" = "$FS_TARGET_DIR" ] ; then
            if [ "$FS_DB_TABLES" = "$FS_ROOT" ] ; then
                [ $OK_wt_ROOT_TARGET -eq 1 ] && DB_TABLES_OK=1
            else
                [ $OK_wt_TARGET -eq 1 ] && DB_TABLES_OK=1   
            fi            
        else
         # check if it is also on the same partition as / 
        if [ "$FS_DB_TABLES" = "$FS_ROOT" ] ; then
                [ $OK_wt_ROOT -eq 1 ] && DB_TABLES_OK=1
        else
            [ $OK -eq 1 ] && DB_TABLES_OK=1   
        fi
    fi
    else
        # Since the tbl package already exists, just obtain relevant details
        # from pkginfo 
        DB_TABLES_DIR=`$CMD_PKGINFO $RELOC_PARAM -r SUNWestbl`
        DB_TABLES_OK=1   
    fi  
    
else
    DB_TABLES_OK=1
fi 
}

# $1 - Directory to relocate
# $2 - Space available on current partition
# $3 - Space required
#
relocate() {

reloc_dir=$1
avail_space=$2
req_space=$3
allow_reloc=1

if [ "$reloc_dir" = "$TARGET_DIR" ] ; then 
    flash_message="Sun Management Center Software"
    $CMD_PKGINFO $RELOC_PARAM -qi SUNWescom 2> /dev/null
    [ $? -eq 0 ] && allow_reloc=0 # avoid reloc in incremental
elif [ "$reloc_dir" = "$DB_TABLES_DIR" ] ; then
    flash_message="Sun Management Center Datafiles"
fi
    
    echolog ''
    echolog 'Insufficient disk space to install $2' "$flash_message"
    echolog '$2 requires: $3 Blocks' "$flash_message" "$req_space"
    if [ -d "$reloc_dir/SUNWsymon" ] ; then
        echolog 'The installation directory \\\"$2\\\" has: $3 Blocks' "$reloc_dir/SUNWsymon" "$avail_space"
    else
        echolog 'The installation directory \\\"$2\\\" has: $3 Blocks' "$reloc_dir" "$avail_space"
    fi
    if [ $allow_reloc -eq 1 ] ; then
        echolog 'Enter a directory where $2 Blocks are available' "$req_space"
        echolog ''
        while [ 1 ] ; do        
            #fetch_response_text "TAG=TARGET_DIRECTORY" 'Sun Management Center 3.5 Update 1 will be installed in: [ $3 ]' "$temp_dir"
            #[ "$?" = "$SUMMARY_READ_ERROR" ] && EXIT_FLAG=$BAD_TARGET_DIR && exit_SunMC            
            get_input_from_user 'Enter another directory: '
            orig_relocated_dir="$answer"
            relocated_dir=`getPathName "$answer"`
            checkInstallDirectory $relocated_dir        
            [ $? -eq 0 ] && break                     
        done
    else
        echolog 'To install additional software, make sure that $2 Blocks are available.' "$req_space"
        exit_SunMC "$BAD_TARGET_DIR"
    fi
if [ "$reloc_dir" = "$TARGET_DIR" ] ; then 
    TARGET_DIR=`getPathName $relocated_dir`
    TARGET_DIR_WITHOUT_RELOC=`getPathName $relocated_dir`
elif [ "$reloc_dir" = "$DB_TABLES_DIR" ] ; then
    DB_TABLES_DIR=$relocated_dir
fi

}



# << END space checking functions<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #


# Uninstall
# Ask about old SunMC installation.

removeOldSunMC() {

if [ $TRIED_UNINST -eq 0 ] ; then
    TRIED_UNINST=1
    echolog 'A previous version of Sun Management Center exists on this system.'
    echolog ''
    if [ -n "$RELOCATED_ROOT" -a "$RELOCATED_ROOT" != "/" ]; then
	echolog 'You must uninstall it locally in \\\"$2\\\".' "$RELOCATED_ROOT"
	exit_SunMC "$NO_ERROR"
    fi
    
    READ_RESPONSE_ONCE=0   
    fetch_response_yes_no "TAG=UNINSTALL_OLD" "Would you like to uninstall it now to proceed with the upgrade "
    [ -z "$answer" ] && answer=0
    saveAutoConfig "UNINSTALL_OLD" "$answer"
else    
    echolog ''    
    echolog 'Removal of the installed version was unsuccessful'
    if [ -z "$AUTOCONFIG_RUNFILE" ] ; then
        ask_user 'Do you wish to try again '
    else
        echolog 'Unable to continue with automated installation'
        answer=0
    fi
fi
    
if [ $answer -ne 1 ] ; then
   exit_SunMC
fi

    #
    # Process any old SunMC data - either 3.0 or 2.x
    #
    processOldData

    # Uninstall
    #
    tmp_basedir=`$CMD_PKGPARAM SUNWescom BASEDIR`
    uninst_cmd="$tmp_basedir/SUNWsymon/sbin/es-uninst"
   
    if [ ! -f "$uninst_cmd" ] ; then
        EXIT_FLAG=$PREV_UNINST_ERROR   
        echolog 'Cannot find $2' "$uninst_cmd"

        if [ "$AUTOCONFIG_RUNFILE" = "" ] ; then
             userConfirmation
        fi
        exit_SunMC
    fi

    checkString "$INSTALLED_PKGVER" "2."   
    if [ $? -eq 0 ] ; then
        # Only for 2X 
        TMP_RESPFILE="${LOGDIR}/respfile.$TIMESTAMP.$$" 
        $CMD_CAT << !EOF > "$TMP_RESPFILE"
y
y
!EOF
        $CMD_CAT "$TMP_RESPFILE" | $uninst_cmd
        $CMD_RM $TMP_RESPFILE  
    else
        #
        # If upgrading from 3.0, by now any 3.0 data would already have been
        # exported. So move this data to a safe temporary place, and call
        # es-uninst with -f so that it won't ask redundant questions about
        # preserving existing data.
        #
        # We also backup */2x because on agent-only installations, we can't
        # tell the difference between 2.x and 3.0 cfg directories, and so
        # 3.0 agent-only cfg directories will get backed up to */2x.
        #
        checkString "$INSTALLED_PKGVER" "3.0"
        if [ $? -eq 0 ] ; then
            $CMD_MKDIR -p ${VAROPTDIR}.bak
            if [ -d ${VAROPTDIR}/2x ] ; then
                $CMD_MV -f ${VAROPTDIR}/2x                   ${VAROPTDIR}.bak/
            fi
            if [ -d ${VAROPTDIR}/upgrade ] ; then
                $CMD_MV -f ${VAROPTDIR}/upgrade              ${VAROPTDIR}.bak/
            fi
            if [ -d ${VAROPTDIR}/SunMCDB02.backup ] ; then
                $CMD_MV -f ${VAROPTDIR}/SunMCDB02.backup     ${VAROPTDIR}.bak/
            fi
            if [ -d ${VAROPTDIR}/install ] ; then
                $CMD_MV -f ${VAROPTDIR}/install              ${VAROPTDIR}.bak/
            fi
            if [ -d ${VAROPTDIR}/bin ] ; then
                $CMD_MV -f ${VAROPTDIR}/bin              ${VAROPTDIR}.bak/
            fi
            
            $uninst_cmd -f 2>/dev/null

            $CMD_MKDIR -p ${VAROPTDIR}
            if [ -d ${VAROPTDIR}.bak/2x ] ; then
                $CMD_MV -f ${VAROPTDIR}.bak/2x               ${VAROPTDIR}/
            fi
            if [ -d ${VAROPTDIR}.bak/upgrade ] ; then
                $CMD_MV -f ${VAROPTDIR}.bak/upgrade          ${VAROPTDIR}/
            fi
            if [ -d ${VAROPTDIR}.bak/SunMCDB02.backup ] ; then
                $CMD_MV -f ${VAROPTDIR}.bak/SunMCDB02.backup ${VAROPTDIR}/
            fi
            if [ -d ${VAROPTDIR}.bak/install ] ; then
                $CMD_MV -f ${VAROPTDIR}.bak/install          ${VAROPTDIR}/
            fi
            if [ -d ${VAROPTDIR}.bak/bin ] ; then
                $CMD_MV -f ${VAROPTDIR}.bak/bin          ${VAROPTDIR}/
            fi
            $CMD_RMDIR ${VAROPTDIR}.bak
        else

            /usr/bin/rm -rf ${TMP_DIR}.bak
            /usr/bin/mv ${TMP_DIR} ${TMP_DIR}.bak
	    
            $uninst_cmd 2> /dev/null

            /usr/bin/rm -rf ${TMP_DIR}
            /usr/bin/mv ${TMP_DIR}.bak ${TMP_DIR}

            cd $TMP_DIR

           # In case there has been upgrade from 3.5 up, then
           # installation.properties and installation.info
           # files need to be re-created.

           initializeTempDirectory
           setInstallationInfoInstallationProperties

        fi
    fi
}


#
# ProcessOldData - includes 3.0 and 2.x data processing.
#

processOldData () {

return_code=0

# Do not attempt to process data again once "$keepData"
# flag is set, which means it already been done.

if [ -z "$keepData" ]; then

   checkOld30DataOnlyExists
   if [ $? -eq 1 ]; then
      processOld30Data
      return_code=1
   else
      checkOld2XDataOnlyExists
      code="$?"
      if [ "$code" -ne 0 ]; then
         processOld2XData "$code"
         return_code=1
      fi
   fi
fi

return $return_code

}

#
# ProcessOld2XData
#
# Takes return code from checkOld2XDataOnlyExists as a parameter.
# 2 - raw, non-exported 2.1.1 data only exists, prompt user to execute export utility
# if data needs to be saved and migrated over.
# 3 - exported data exists, proceed with upgrade, inform user that exported data
# has been detected and will be brought over.
# 4 - only config files exist, copy them over

processOld2XData () {

if [ "$1" -eq 3 ]; then
   # Do nothing. Data is already exported. Inform user that it will be migrated.
   echolog ''
   echolog 'Existing Sun Management Center Exported Data detected.'
   echolog ''
   echolog "This data will be migrated to the new release."
   keepData="true"


elif [ "$1" -eq 2 ]; then
   # Aks about existing data. Give user approproate information.
   # Set DATA_VERSION flag.
   echolog ''
   echolog 'Existing Sun Management Center Data detected.'

   DATA_VERSION="2.x"
   askAboutOldData  

elif [ "$1" -eq 4 ]; then
   # Copy the cfg directory over.
   smc2x_cfg_data="${VAROPTDIR}/cfg"
   smc2x_bin="${VAROPTDIR}/bin"
   smc30_prm_agt_dir="${VAROPTDIR}/PRM/agent"
   smc30_prm_hist_file="${VAROPTDIR}/log/history.log"
   smc30_prm_bak_dir="${VAROPTDIR}/upgrade/addons/PRM"

   if [ -d "$smc2x_cfg_data" ]; then
       # This detects 2.1.1 or 3.0 agent only configuration data.
       # Equates to an agent-only migration case.
       echolog ''
       echolog 'Existing Sun Management Center Configuration Data detected.'
      
      askAboutOldData
      if [ "$keepData" = "true" ]; then
         /usr/bin/mkdir ${VAROPTDIR}/2x > /dev/null 2>&1 
         /usr/bin/cp -fR "$smc2x_cfg_data" ${VAROPTDIR}/2x
         if [ $? -ne 0 ]; then
	    echolog "Error occured while preserving the configuration files."
	 else
	    /usr/bin/rm -rf "$smc2x_cfg_data"  > /dev/null 2>&1
	    # Set agent_only data migration flag
            agent_only_data="YES"
         fi

         if [ -d "$smc2x_bin" ] ; then
           /usr/bin/cp -fpR "$smc2x_bin" ${VAROPTDIR}/2x/bin
           if [ $? -ne 0 ] ; then
             echolog "Error occurred while preserving the configuration files."
           else
             /usr/bin/rm -rf "$smc2x_bin"
           fi
         fi

	 # Copy over PRM related agent configuration data.
 	 if [ -d "$smc30_prm_agt_dir" -a "$smc30_prm_hist_file" ]; then

   	    [ ! -d "$smc30_prm_bak_dir" ] && /usr/bin/mkdir -p ${smc30_prm_bak_dir} > /dev/null 2>&1
   	    [ -d "$smc30_prm_agt_dir" ] && /usr/bin/cp -rf $smc30_prm_agt_dir ${smc30_prm_bak_dir} 
	    retcode_1="$?"

   	    [ -f "$smc30_prm_hist_file" ] && /usr/bin/cp -f $smc30_prm_hist_file ${smc30_prm_bak_dir} 
	    retcode_2="$?"

		if [ "$retcode_1" -eq 0 -a "$retcode_2" -eq 0 ]; then
		   /usr/bin/rm -rf "$smc30_prm_agt_dir" > /dev/null 2>&1
		   /usr/bin/rm -rf "$smc30_prm_hist_file" > /dev/null 2>&1
		fi
 	 fi

      fi
   fi
fi

}

# Fix permissions and ownership of home directory of $SMCORAU.
fix_smcorau_homedir () {
    smcorau_dir="${VAROPTDIR}/smcorau"

    if [ -d "$smcorau_dir" ] ; then
        $CMD_CHOWN smcorau:smcorag $smcorau_dir
        $CMD_CHMOD 755 $smcorau_dir
    fi
}
   
#
# ProcessOld30Data
#
processOld30Data() {

echolog ''
echolog 'Existing Sun Management Center Data detected.'

# init some working vars

   smc30_ora_data="${VAROPTDIR}/SunMCDB02"
   smc_cfg_dir="${VAROPTDIR}/cfg"
   smc_bin="${VAROPTDIR}/bin"
   smc_mcp_dir="${VAROPTDIR}/mcp"
   smc30_bak_dir="${VAROPTDIR}/upgrade"

   smc30_rep_dir="${VAROPTDIR}/reports"
   smc30_prm_agt_dir="${VAROPTDIR}/PRM/agent"
   smc30_prm_srvc_dir="${VAROPTDIR}/PRM/service"
   smc30_prm_log_dir="${VAROPTDIR}/PRM/log"
   smc30_prm_mod_file="${VAROPTDIR}/PRM/modules.info"
   smc30_prm_hist_file="${VAROPTDIR}/log/history.log"
   smc30_prm_bak_dir="${smc30_bak_dir}/addons/PRM"

[ ! -d "$smc30_bak_dir" ] && $CMD_MKDIR -p "$smc30_bak_dir"

checkString "$INSTALLED_PKGVER" "3.0"

# If sunMC 3.0 was uninstalled and package version number is not available,
# then check if data directory persisted, having been saved by es-uninst of 3.0

if [ $? -eq 0 -o -d "$smc30_ora_data" -o -h "$smc30_ora_data" ] ; then


    # ask user if they wish to proceed. Tackles response summary
    #


    askAboutOldData #this will set keepData="true" or "false"

    #
    # Perform the es-dbexp if the SunMC30 db subdir exists
    # and relevent data files are present
    #
    # Ensure that the oracle db directories are present and at least
    # one data file (sunmc.dat) is also present
    #
    if [ "$keepData" = "true" ] ; then
        fix_smcorau_homedir

        if [ \( -d "$smc30_ora_data" -o -h "$smc30_ora_data" \) -a -d "$smc30_ora_data/oradata" -a -f "$smc30_ora_data/oradata/SunMC30/sunmc.dat" ] ; then

            #
            # Make sure backup directories are available and have correct
            # permissions.
            #
            if [ ! -d "$smc30_bak_dir/db" ] ; then
                $CMD_MKDIR -p $smc30_bak_dir/db
                if [ $? -ne 0 ] ; then
                    echolog 'Unable to create backup directory $smc30_bak_dir/db'
                    if [ "$AUTOCONFIG_RUNFILE" = "" ] ; then
                        userConfirmation
                    fi
                    exit_SunMC
                fi
            fi
            $CMD_CHMOD -Rf 777 $smc30_bak_dir


            # Check if SunMC 3.0 is still installed. If it is, export the data
            # directly from the existing Oracle server; otherwise, move the
            # database tables to a safe place and wait until Oracle 8.1.7 is
            # installed and configured so that we can use it to do the export.

            db_pkgs=`$CMD_PKGINFO | $CMD_GREP SUNWesora\|SUNWesdb`
            if [ $? -eq 0 ] ; then
                #
                # SunMC 3.0 Oracle 8.1.6 is still available: export now.
                #


                db_export_cmd="${TOOLS_DIR}/es-dbexp"
                if [ ! -f "$db_export_cmd" ] ; then
                    EXIT_FLAG=$DB_EXPORT_ERROR
                    echolog 'Cannot find $2' "$db_export_cmd"
                    if [ "$AUTOCONFIG_RUNFILE" = "" ] ; then
                        userConfirmation
                    fi
                    exit_SunMC
                fi

                # Invoke export script
                # NOTE: unlike the previous version, the new export script
                # will be responsible for exporting *all* database users it
                # finds in the old SunMC installation.
                export LOGFILE
                $db_export_cmd use816
                if [ $? -ne 0 ] ; then
                    EXIT_FLAG=$DB_EXPORT_ERROR
                    echolog "Error occurred during Sun Management Center data export"
                    if [ "$AUTOCONFIG_RUNFILE" = "" ] ; then
                        userConfirmation
                    fi
                    exit_SunMC
                fi
                echolog ''

            else

                # SunMC 3.0 is no longer available -- backup database tables
                # and export them later after 8.1.7 is ready.
                # Also remove old SUNWestbl so that new SUNWestbl will
                # install correctly.

                if [ -d ${smc30_ora_data}.backup ] ; then
                    echolog 'Backup directory: ${smc30_ora_data}.backup already exists. Remove it or move it aside and try again.'
                    if [ "$AUTOCONFIG_RUNFILE" = "" ] ; then
                        userConfirmation
                    fi
                    exit_SunMC
                fi

                # If SunMCDB02 is a symlink, we need to rename the target of
                # the link as well (we can't move it, since the reason it's a
                # a link is because of insufficient space in /var/opt/.)
                if [ -h "$smc30_ora_data" ] ; then
                    realpath=`/usr/bin/ls -ld $smc30_ora_data | /usr/bin/sed -e 's/^.*-> //' `
                    $CMD_MV $realpath $realpath.backup
                    $CMD_LN -s $realpath.backup ${smc30_ora_data}.backup
                    $CMD_RM $smc30_ora_data
                else
                    # Not a symlink; just rename the directory
                    $CMD_MV $smc30_ora_data ${smc30_ora_data}.backup
                fi
                /usr/sbin/pkgrm -n SUNWestbl
                if [ $? -ne 0 ] ; then
                    echolog "Warning: SUNWestbl not removed cleanly"
                fi
            fi
        else
            echolog "Old data is incomplete -- some directories are missing, NOT exporting"
        fi
    fi
fi

# If cfg dir exists, move it to upgrade/db/cfg
if [ -d "$smc_cfg_dir" ] ; then
    if [ -d "$smc30_bak_dir/cfg" ] ; then
        $CMD_RM -rf $smc30_bak_dir/cfg > /dev/null 2>&1
    fi

    $CMD_CP -pr $smc_cfg_dir $smc30_bak_dir/ > /dev/null 2>&1
    if [ $? -ne 0 ] ; then
        echolog "Error occurred while backing up old configuration files"
        if [ "$AUTOCONFIG_RUNFILE" = "" ] ; then
            userConfirmation
        fi
        exit_SunMC
    fi

    $CMD_RM -rf "$smc_cfg_dir"
fi

# If mcp dir exists, move it to upgrade/mcp
if [ -d "$smc_mcp_dir" ]; then
    if [ -d "$smc30_bak_dir/mcp" ]; then
        $CMD_RM -rf $smc30_bak_dir/mcp > /dev/null 2>&1
    fi

    $CMD_CP -pr $smc_mcp_dir $smc30_bak_dir/ > /dev/null 2>&1
    if [ $? -ne 0 ] ; then
        echolog "Error occurred while backing up old configuration files"
        if [ "$AUTOCONFIG_RUNFILE" = "" ] ; then
            userConfirmation
        fi
        exit_SunMC
    fi

    $CMD_RM -rf "$smc_mcp_dir"
fi

# Migrate $ESDIR/bin as well
# (Be extra careful that $smc30_bak_dir is defined; otherwise we could be
# deleting /bin by accident)
if [ -d "$smc_bin" -a -d "$smc30_bak_dir" ] ; then
    if [ -d "$smc30_bak_dir/bin" ] ; then
        $CMD_RM -rf "$smc30_bak_dir/bin"
    fi
    $CMD_CP -pr $smc_bin $smc30_bak_dir/bin
    if [ $? -ne 0 ] ; then
        echolog "Error occurred while backing up old configuration files"
        if [ "$AUTOCONFIG_RUNFILE" = "" ] ; then
            userConfirmation
        fi
        exit_SunMC
    fi
    $CMD_RM -rf $smc_bin
fi

# This is been done to save the PRM data
# If the ../PRM/agent (directory) or ../reports (directory) or ../log/history.log (file)
# exist they will be saved into the corresponding upgrade/addons/PRM/ directory.
ret1=0
ret2=0
ret3=0
ret4=0
ret5=0
ret6=0

if [ "$keepData" = "true" ] ; then

 if [ -d "$smc30_rep_dir" -o -d "$smc30_prm_agt_dir" -o -d "$smc30_prm_srvc_dir" ]; then

   [ ! -d "$smc30_prm_bak_dir" ] && /usr/bin/mkdir -p ${smc30_prm_bak_dir} > /dev/null 2>&1

   if [ -d "$smc30_rep_dir" ]; then
      /usr/bin/cp -rf $smc30_rep_dir ${smc30_prm_bak_dir}  > /dev/null 2>&1
      ret1="$?"
   fi
   if [ -d "$smc30_prm_agt_dir" ]; then 
      /usr/bin/cp -rf $smc30_prm_agt_dir ${smc30_prm_bak_dir} > /dev/null 2>&1 
      ret2="$?"
   fi
   if [ -f "$smc30_prm_hist_file" ]; then
      /usr/bin/cp -f $smc30_prm_hist_file ${smc30_prm_bak_dir} > /dev/null 2>&1 
      ret3="$?"
   fi
   if [ -d "$smc30_prm_srvc_dir" ]; then
      /usr/bin/cp -rf $smc30_prm_srvc_dir ${smc30_prm_bak_dir} > /dev/null 2>&1
      ret4="$?"
   fi
   if [ -d "$smc30_prm_log_dir" ]; then 
      /usr/bin/cp -rf $smc30_prm_log_dir ${smc30_prm_bak_dir} > /dev/null 2>&1
      ret5="$?"
   fi
   if [ -f "$smc30_prm_mod_file" ]; then
      /usr/bin/cp -f $smc30_prm_mod_file ${smc30_prm_bak_dir} > /dev/null 2>&1
      ret6="$?"
   fi

   if [ "$ret1" -eq 0 -a "$ret2" -eq 0 -a "$ret3" -eq 0 -a "$ret4" -eq 0 -a "$ret5" -eq 0 -a "$ret6" -eq 0 ]; then
        $CMD_RM -rf "$smc30_rep_dir" > /dev/null 2>&1
        $CMD_RM -rf "$smc30_prm_agt_dir" > /dev/null 2>&1
        $CMD_RM -f "$smc30_prm_hist_file" > /dev/null 2>&1
        $CMD_RM -f "$smc30_prm_mod_file" > /dev/null 2>&1
        $CMD_RM -rf "$smc30_prm_log_dir" > /dev/null 2>&1
        $CMD_RM -rf "$smc30_prm_srvc_dir" > /dev/null 2>&1
   else
        echolog "Error occurred while backing up old configuration files"
        if [ "$AUTOCONFIG_RUNFILE" = "" ] ; then
            userConfirmation
        fi
        exit_SunMC
   fi
 fi

fi

#checkString "$PROGNAME" "gui-db-export.sh"
#if [ $? -eq 1 ] ; then
#    checkOldUninstallSuccessful
#fi
}


askAboutOldData() {
    keepData="false"
    preserve_data_answered=0
    READ_RESPONSE_ONCE=0

    while [ $preserve_data_answered -eq 0 ] ; do
        $CMD_ECHO ""
        fetch_response_yes_no "TAG=PRESERVE_OLD_DATA" "Would you like to migrate your previous data "
	do_it=$answer

        if [ $do_it -eq 1 ] ; then
            $CMD_ECHO ""
            preserve_data_answered=1
            keepData="true"
            
	    # In case this is a raw 2.1.1 data (based on the DATA_VERSION flag) tell user how to migrate it.
	    if [ ! -z "$DATA_VERSION" ]; then
		echolog ""
   		multiline_echolog 'You must download the data export utility available at\nhttp://www.sun.com/sunmanagementcenter to export your existing data.\nFollow the instructions to complete the data export and re-run the installation.'
                if [ "$AUTOCONFIG_RUNFILE" = "" ] ; then
                    userConfirmation
                fi
                exit_SunMC
  	    fi
        else
            $CMD_ECHO ""
        echolog 'This will remove all files under $2.' "${VAROPTDIR}"
        echolog "If you have any custom scripts under this directory, move them to an alternate location before proceeding."
            $CMD_ECHO ""
            
            if [ -z "$AUTOCONFIG_RUNFILE" ] ; then
                ask_user "Do you wish to continue with the removal of the existing data"
                remove_it=$answer
            else
                remove_it=1 #no confirmation in auto install
            fi

            if [ $remove_it -eq 0 ] ; then
                preserve_data_answered=0
            else
                preserve_data_answered=1
        	keepData="false"
		
		# Make sure that ${VAROPTDIR}/install is not deleted as part 
		# of this clean up.

                if [ -h "${VAROPTDIR}" -o -d "${VAROPTDIR}" ] ; then
		    remove_dirs=`/usr/bin/find "${VAROPTDIR}"/* -type d | /usr/bin/egrep -v install`
		    for dir in $remove_dirs
		    do
                    	$CMD_RM -rf "$dir" > /dev/null 2>&1
		    done
                fi

                $CMD_ECHO ""                
            fi
        fi
    done
 
	saveAutoConfig "PRESERVE_OLD_DATA" "$do_it"
}


# << BEGIN installation.info related functions<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #

# Set the installation.info and installation.properties files
# Reads   : PRODUCT_KEY
# Returns : 1 for success; 0 for invalid entry
# Sets    : INSTALLATION_PROPERTY, INSTALLATION_INFO
# $1 - product_dir , if present
#
setInstallationInfoInstallationProperties() {

    if [ "$PROGNAME" != "archive-tool" ]; then
        if [ "$OSVERS_BITS" = "" ]; then
            OSVERS_CURRENT=`$CMD_UNAME -r`
            if [ "$OSVERS_CURRENT" = "5.10" ]; then
                OSVERS="10"
            fi
        else
            if [ "$OSVERS_BITS" = "10" ]; then
                OSVERS="10"
            fi
        fi
    fi

    [ -n "$1" ] && product_dir=$1
        
    if [ "$INSTALL_TYPE" = "BASE" ] ; then  
	[ $OSVERS -eq 10 -a ! -d "${SRC_DIR}/${BASE_PRODUCT_DIR}/Solaris_${OSVERS}" ] && OSVERS=9
        tmp_dir="${SRC_DIR}/${BASE_PRODUCT_DIR}/Solaris_${OSVERS}"
    else   
        if [ -z "$product_dir" ] ; then
            product_dir=`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" "SOURCE_DIR"`
        fi        
	[ $OSVERS -eq 10 -a ! -d "${SRC_DIR}/Addons/${product_dir}/Solaris_${OSVERS}" ] && OSVERS=9
        tmp_dir="${SRC_DIR}/Addons/${product_dir}/Solaris_${OSVERS}"        
    fi   
    
    INSTALLATION_INFO=${TMP_DIR}/installation.info.$$
    INSTALLATION_PROPERTY=${TMP_DIR}/installation.properties.$$
    
    $CMD_RM -f $INSTALLATION_INFO > /dev/null 2>&1
    $CMD_RM -f $INSTALLATION_PROPERTY > /dev/null 2>&1
    
    if [ -s "${tmp_dir}/installation.info" -a -s "${tmp_dir}/installation.properties" ] ; then    
        $CMD_CAT "${tmp_dir}/installation.info" | $CMD_GREP -v "\s*#" > $INSTALLATION_INFO
        $CMD_CAT `getI18NPropertyFile "${tmp_dir}"` | $CMD_GREP -v "\s*#" > $INSTALLATION_PROPERTY
    fi 
     
    if [ ! -f "$INSTALLATION_INFO" -o ! -f "$INSTALLATION_PROPERTY" ] ; then
        [ "$INSTALL_TYPE" = "BASE" ] && exit_SunMC $INSTALLATION_FILES_NOT_FOUND
        return 0
    fi
    return 1
}

unsetInstallationInfoInstallationProperties() {
    $CMD_RM -f $INSTALLATION_INFO > /dev/null 2>&1
    $CMD_RM -f $INSTALLATION_PROPERTY > /dev/null 2>&1
}



# Get the internationalized value of a key.
# Parameter: $1 = the key
# Return: $MSG
getI18NMessage() {
    MSG=""
    key=$1
    if [ -f "$INSTALLATION_PROPERTY" ] ; then    
        MSG=`$CMD_AWK -F= '/'$key'/ {print $2}' $INSTALLATION_PROPERTY`
    fi
    [ -z "$MSG" ] && MSG="$1"
    return
}


# Return: $PRODUCT_KEY
#         $PRODUCT_NAME
#         $PRODUCT_DEPENDENCIES - blank if none
#         $INSTALL_SUBDIR  - blank if none
#         $PACKAGES_SUBDIR
#         $PACK_SUBDIR
#         $PRODUCT_PREINSTALL_SCRIPT - blank if none
#         $PRODUCT_POSTINSTALL_SCRIPT - blank if none

getProductInfoFromFile() {
    
    PRODUCT_KEY=`$CMD_AWK -F= '/PRODUCT_KEY/ {print $2}' $INSTALLATION_INFO`    
    getI18NMessage "$PRODUCT_KEY"        
    PRODUCT_NAME=$MSG
   
    INSTALL_SUBDIR=`$CMD_AWK -F= '/INSTALL_SUBDIR/ {print $2}' $INSTALLATION_INFO`
    
    PACKAGES_SUBDIR=""
    PACK_SUBDIR=""
        
    PACKAGES_SUBDIR=`$CMD_AWK -F= '/PACKAGES_SUBDIR/ {print $2}' $INSTALLATION_INFO`
    
    PACK_SUBDIR=`$CMD_AWK -F= '/PACK_SUBDIR/ {print $2}' $INSTALLATION_INFO`
    
    PACK_CD=`$CMD_AWK -F= '/PACK_CD/ {print $2}' $INSTALLATION_INFO`
    
    PRODUCT_PREINSTALL_SCRIPT=""   
    PRODUCT_POSTINSTALL_SCRIPT=""
    
    if [ -z "$PACKAGES_SUBDIR" -a -z "$PACK_SUBDIR" ] ; then
         echolog 'Subdirectory for packages is not defined in the installation configuration file.'
         echolog '' 
         exit_SunMC 1
    elif [ -n "$PACKAGES_SUBDIR" -a -n "$PACK_SUBDIR" ] ; then
         echolog 'PACKAGES_SUBDIR and PACK_SUBDIR cannot be used together in the installation configuration file.'
         echolog '' 
         exit_SunMC 1
    fi
}


# Get the list of component keys.
# The function checks whether user has selected to install docs or not
# If not, it does not include the component in the list.
# Hardcoding component name in order to fix RFE: 4826819
# Return: $COMPONENT_LIST
# 
getComponentListFromFile() {
         
    COMPONENT_LIST=""        
    for COMPONENT_KEY in `$CMD_CAT $INSTALLATION_INFO | $CMD_AWK -F= '/COMPONENT_KEY/ {print $2}'`
    do       
        supports_layer=0
        supports_locale=0

        # Check if documentation was selected for installation.
        if [ "$COMPONENT_KEY" = "COMPONENT.DOCS" ]; then
            if [ "$INSTALL_DOCS" != "TRUE" ]; then
                # just go to the next component.
                continue
            fi
        fi
                
        getComponentInfo "LAYER"
        [ -z "$COMPONENT_INFO" ] && supports_layer=1
        
        if [ $supports_layer -eq 0 ] ; then
            for each_layer in `$CMD_ECHO "$INSTALL_LAYERS" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
            do
                checkString "$COMPONENT_INFO" "$each_layer"
                if [ $? -eq 0 ] ; then
                    supports_layer=1                
                    break
                fi            
            done
        fi
        
        if [ "$PROGNAME" = "archive-tool" -a "$SOURCE_IMAGE" != "DEFAULT" ] ; then
            supports_locale=1
        else
            getComponentInfo "LANG"
            [ -z "$COMPONENT_INFO" ] && supports_locale=1
        fi 
        
        if [ $supports_locale -eq 0 ] ; then
            for each_locale in `$CMD_ECHO "$INSTALL_LOCALES" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
            do        
                for supported_locale in `$CMD_ECHO "$COMPONENT_INFO" | $CMD_AWK -F ', ' '{ for (i = 1; i <= NF; i++) print $i }'`
                do
                    if [ "$each_locale" = "$supported_locale" ] ; then
                        supports_locale=1
                        break
                    fi
                done
                [ $supports_locale -eq 1 ] && break                
            done         
        fi
        
        if [ $supports_locale -eq 1 -a $supports_layer -eq 1 ] ; then
            if [ -z "$COMPONENT_LIST" ] ; then
                COMPONENT_LIST="$COMPONENT_KEY"
            else
                COMPONENT_LIST="$COMPONENT_LIST,$COMPONENT_KEY"
            fi
        fi    
    done    
}

# Get a particular info of a component in a pack.
# Parameters: $1 = a component info key; $2 = locale code (optional)
# Reads: $COMPONENT_KEY and $INSTALLATION_INFO
# Return: $COMPONENT_INFO
getComponentInfo() {
       
    COMPONENT_INFO=""
    COMPONENT_INFO=`$CMD_SED -n '\#^.*COMPONENT_KEY='$COMPONENT_KEY'$#,\#</COMPONENT>#s/^.*'$1'=//p' $INSTALLATION_INFO`

    if [ -n "$2" ] ; then
        PATTERN='${LOCALE_CODE}'
        if [ "$1" = "PACKAGES" ] ; then
            case "$2" in
                zh_TW) HELP_CODE=h  ;;
                zh)    HELP_CODE=c  ;;
                C)     HELP_CODE=en ;;
                *)     HELP_CODE="$2" ;;
            esac
        fi
        COMPONENT_INFO=`$CMD_ECHO $COMPONENT_INFO | $CMD_SED -e "s/$PATTERN/$HELP_CODE/"`    
    fi
}


# reads  : $PRODUCT_KEY
# Get the right source directory for a package
# Assumes only one pack / product
# $1 - package name
# Return: $PACKAGE_DIR
getPackageDirectory() {
    if [ "$PRODUCT_KEY" = "${BASE_PRODUCT_KEY}" ] ; then
        INSTALL_TYPE="BASE"
    else
        INSTALL_TYPE="ADDON"
    fi 

    package=$1   
    vers=`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" "VERSION"`   
    
    if [ "$vers" = "2X" ] ; then
        PACKAGE_DIR="${SRC_DIR}/Addons/SunMC2.X/Solaris_${OSVERS}/${PRODUCT_KEY}/$package"
        [ -f "${PACKAGE_DIR}/pkginfo" ] && return 1
        PACKAGE_DIR="${SRC_DIR}/Addons/SunMC2.X/Common/${PRODUCT_KEY}/$package"        
    else
        SUBDIR=`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" "SUBDIR"`        
        getCorrectDirectory "${SUBDIR}/${package}"
        PACKAGE_DIR=$CORRECT_DIR   
    fi
    
    [ -f ${PACKAGE_DIR}/pkginfo ] && return 1
    
    echologverbose 'Unable to find package directory for $2' "$package"    
    EXIT_FLAG=$PACKAGE_DIR_NOT_FOUND
    return 0
}

# Gets the internationalized version of installation.properties, if any
# $1 = the directory containing the property file
# Return: <$1>/installation[_<locale>].properties
getI18NPropertyFile() {
    tmp_l10n="$L10N_CODE"
    [ "$tmp_l10n" = "C" ] && tmp_l10n="en"
    tmp="${1}/installation_${tmp_l10n}.properties"
    if [ -f "$tmp" ] ; then
    $CMD_ECHO "$tmp"
    return
    else
    tmp="${1}/installation.properties"
    $CMD_ECHO "$tmp"
    return
    fi
}


# << END installation.info related functions<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #


# Run
setupSunMC() {

    [ -z "$INSTALL_KEYS" ] && return
   
    if [ -n "$RELOCATED_ROOT" -a "$RELOCATED_ROOT" != "/" ] ; then
        echolog 'You must run setup locally in \\\"$2\\\".' "$RELOCATED_ROOT"
	echolog ''
        return
    fi
    SETUP_PARAM=""
    [ -n "$AUTOCONFIG_RUNFILE" ] && SETUP_PARAM="-A $AUTOCONFIG_RUNFILE"
    $CMD_PKGINFO $RELOC_PARAM -qi SUNWescom
    [ $? -ne 0 ] && return # base product does not exist
    
    [ -z "$ESROOT" ] && set_basedir
    if [ -z "$ESROOT" ] ; then
        echolog ''
        echolog 'ESROOT is not set.'
        exit_SunMC
    fi
    
    echolog ''
    echolog 'You must perform setup before using Sun Management Center 3.5 Update 1.'
    
    if [ $HA_INSTALL -eq 1 ] ; then
        echolog 'The Sun Management Center Highly Available Server is installed on this node'
        echolog 'Ensure that installation is complete on the backup node, and then perform setup.'
        answer=0
    else
        READ_RESPONSE_ONCE=0
        fetch_response_yes_no "TAG=SETUP_NOW" "Do you want to run setup now "
        saveAutoConfig "SETUP_NOW" "$answer"
    fi
    
    if [ $answer -eq 0 -o $answer -eq 2 ] ; then
    
        echolog 'To perform setup later, invoke our setup script using:' 
        echolog '"\r\"$2' "$ESROOT/sbin/es-setup"
        return 0
    fi
    echolog ''
    if [ $VERBOSE = "ON" ] ; then
         ( $ESROOT/sbin/es-setup -v $SETUP_PARAM )
    else
         ( $ESROOT/sbin/es-setup $SETUP_PARAM )
    fi
    
}


validateDatabaseInRegistry() {    

    DB_SRC_DIR="${SRC_DIR}/db" 
    if [ -d $DB_SRC_DIR ] ; then
        DB_PKGLIST=`$CMD_LS $DB_SRC_DIR` 
    else
        DB_PKGLIST="SUNWesora SUNWestbl" # Hardcoded in case Add-On Only image.
    fi
    DB_PKGLIST=`$CMD_ECHO "$DB_PKGLIST" | $CMD_SED "s/\\n/ /g"`
    DB_PKGLIST_TO_INSTALL=""
    INSTALL_DB=0
    
    db_packages_in_registry=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "database_package" "key" 2>/dev/null`
    
      
    #first check if any packages are missing
    for DB_PKG in `$CMD_ECHO "$DB_PKGLIST"`
    do        
        $CMD_PKGINFO $RELOC_PARAM -qi "$DB_PKG"    
        if [ $? -eq 0 ] ; then
            checkString "$db_packages_in_registry" "$DB_PKG"
            [ $? -ne 0 ] && $API_INSERT_TAG "$REGISTRY" "category=Installation" "database_package=$DB_PKG" >/dev/null 2>&1
            $API_SET_ATTRIBUTE "$REGISTRY" "category=Installation" "database_package=$DB_PKG" "status=1" >/dev/null 2>&1
        else
            if [ -z "$DB_PKGLIST_TO_INSTALL" ] ; then
                DB_PKGLIST_TO_INSTALL="$DB_PKG"
            else   
                DB_PKGLIST_TO_INSTALL="${DB_PKGLIST_TO_INSTALL},$DB_PKG"
            fi
            INSTALL_DB=1
        fi        
    done
}

# << END post install functions<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #

#>> BEGIN Smart-update Functions>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> #

checkPatchOnlyDirectory()
{
    ret_val=0
    patch_dir="$SRC_DIR"
    [ -d "$SRC_DIR/Essential" ] && patch_dir="$SRC_DIR/Essential"
    for os_dir in 2.6 7 8 9 10
    do
	if [ -d $patch_dir/Solaris_${os_dir} ]; then
	    ret_val=1				# An OS dir is found
	    all_patches=`$CMD_LS -1 $patch_dir/Solaris_${os_dir}`
	    for each_patch_dir in $all_patches
	    do
         	patch_number=`echo $each_patch_dir | $CMD_CUT -d- -f1`
         	patch_version=`echo $each_patch_dir | $CMD_CUT -d- -f2`
		len1=`$CMD_ECHO "$patch_number" | $CMD_AWK '{ print length }'`
		len2=`$CMD_ECHO "$patch_version" | $CMD_AWK '{ print length }'`

		[ $len1 -ne 6 -o $len2 -ne 2 ] && ret_val=0
		# All directories are not patch directories
	    done
	fi
    done

    if [ -d $patch_dir/Common ]; then
        ret_val=1                           # Common dir is found
        all_patches=`$CMD_LS -1 $patch_dir/Common`
        for each_patch_dir in $all_patches
        do
            patch_number=`echo $each_patch_dir | $CMD_CUT -d- -f1`
            patch_version=`echo $each_patch_dir | $CMD_CUT -d- -f2`
	    len1=`$CMD_ECHO "$patch_number" | $CMD_AWK '{ print length }'`
	    len2=`$CMD_ECHO "$patch_version" | $CMD_AWK '{ print length }'`

            [ $len1 -ne 6 -o $len2 -ne 2 ] && ret_val=0
            # All directories are not patch directories
        done
    fi

    return $ret_val
}

findSmartUpdateCompatibleProducts()
{
    su_compatibles="PRODUCT.PE"

    if [ ! -f "$REGISTRY" ]; then
        echolog 'Cannot access registry information.'
        echolog 'Exiting...'
        exit 1
    fi

    addons_installed=`$API_QUERY_REGISTRY $REGISTRY product key 2>/dev/null`

    for each_addon in `$CMD_ECHO "$addons_installed" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
    do
	[ "$each_addon" = "PRODUCT.PE" ] && continue
	addon_srcdir=`$API_QUERY_REGISTRY $REGISTRY product=$each_addon target_subdir 2>/dev/null`
	product_basedir=`$CMD_PKGPARAM SUNWescom BASEDIR 2>/dev/null`

	complete_addon_srcdir="$product_basedir/SUNWsymon/addons/$addon_srcdir"
	if [ -f "$complete_addon_srcdir/sbin/setup-resp.sh" ]; then
	    su_compatibles="$su_compatibles,$each_addon"
	fi
    done

    SMARTUPDATE_COMPATIBLE_PRODUCTS="$su_compatibles"


}

# << END Smart Update functions<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #

# << BEGIN Patch install functions<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #

# reads $PRODUCT_KEY
# returns 2 if all necessary patches are available / already installed
#         1 if one or more patch is missing.
#         0 if no patches are required
checkPatches() {    
    
    MISSING_PATCHES=""
    PATCH_LIST=""
    t_patches=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=${PRODUCT_KEY}" "component" "patches-required" 2>/dev/null`
    
    #workaround for QueryXML bug
    #
    t_patches=`$CMD_ECHO "$t_patches" | $CMD_SED "s/,//g"`    
    [ -z "$t_patches" ] && return 0 # This product requires no patches
    
    COMPONENT_LIST=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=${PRODUCT_KEY}" "component" "key" 2>/dev/null`
     
    # Generate a PATCH_LIST for this product.   
    for COMPONENT_KEY in `$CMD_ECHO "$COMPONENT_LIST" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
    do
       t_patches=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=${PRODUCT_KEY}" "component=${COMPONENT_KEY}" "patches-required" 2>/dev/null`        
       [ -z "$t_patches" ] && continue
       if [ -z "$PATCH_LIST" ] ; then
           PATCH_LIST="${t_patches}"
       else
           PATCH_LIST="${PATCH_LIST},${t_patches}"
       fi
    done
    
    retval=2    
    
    for each_reqd_patch in `$CMD_ECHO "$PATCH_LIST" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
    do
        patch_installed=`echo $PATCHES_INSTALLED | $CMD_GREP -c $each_reqd_patch`
        [ $patch_installed -eq 1 ] && continue
        
        patch_available=`echo $PATCHES_AVAILABLE | $CMD_GREP -c $each_reqd_patch`
        [ $patch_available -eq 1 ] && continue
                 
        retval=1
        if [ -z "$MISSING_PATCHES" ] ; then
            MISSING_PATCHES="${each_reqd_patch}"
        else
            MISSING_PATCHES="${MISSING_PATCHES},${each_reqd_patch}"
        fi
    done
    
    
    return $retval

}

#This function has to be called before CD changes.
#
getAvailablePatches() {
    OLDOS=$OSVERS

    if [ "$SOURCE_IMAGE" = "PATCH_ONLY" ] ; then
        PATCH_DIR=${SRC_DIR}
    else
        PATCH_DIR="${SRC_DIR}/Patches"
    fi
    [ $OSVERS -eq 10 -a ! -d ${PATCH_DIR}/Solaris_10 ] && OSVERS=9
    OS_PATCH_DIRECTORY="${PATCH_DIR}/Solaris_${OSVERS}"
    ESSENTIAL_PATCH_DIRECTORY="${PATCH_DIR}/Essential"
    COMMON_PATCH_DIRECTORY="${PATCH_DIR}/Common"

    PATCHES_AVAILABLE=""
    [ -d "$OS_PATCH_DIRECTORY" ] && PATCHES_AVAILABLE=`$CMD_LS -1 ${OS_PATCH_DIRECTORY}`
    [ -d "$COMMON_PATCH_DIRECTORY" ] && PATCHES_AVAILABLE="${PATCHES_AVAILABLE} `$CMD_LS -1 ${COMMON_PATCH_DIRECTORY}`"
    
    [ -d "$ESSENTIAL_PATCH_DIRECTORY" ] && INSTALL_SUNMC_PATCHES=1
    [ -d "${ESSENTIAL_PATCH_DIRECTORY}/Common" ] && PATCHES_AVAILABLE="${PATCHES_AVAILABLE} `$CMD_LS -1 ${ESSENTIAL_PATCH_DIRECTORY}/Common`"
    [ -d "${ESSENTIAL_PATCH_DIRECTORY}/Solaris_${OSVERS}" ] && PATCHES_AVAILABLE="${PATCHES_AVAILABLE} `$CMD_LS -1 ${ESSENTIAL_PATCH_DIRECTORY}/Solaris_${OSVERS}`"
    
    PATCHES_INSTALLED=`${CMD_PATCHADD} $RELOC_PARAM -p | $CMD_AWK ' { print $2 }'`    

    OSVERS=$OLDOS
    export PATCHES_AVAILABLE PATCHES_INSTALLED

}



# function to check for required patches on the remote system
# for successful installation of SUNWesora
# patches required are: 
# Solaris 2.6 - 106292
# Solaris 2.7 - 107443
# Solaris 2.8 - 110934
# Solaris 2.9 - none (fix in FCS)
# Solaris 10 - none (fix in PU1 FCS)
#
# return 1 if patch to check is not installed.
# return 2 for any other error
# return 0 if installed.
#
#
checkSolarisPatchesForSUNWesora () {

    [ -z "$RELOCATED_ROOT" -o "$RELOCATED_ROOT" = "/" ] && return 0
    
    checkString "$INSTALL_LAYERS" "LAYER.SERVER" #check again if called by GUI
    [ $? -eq 1 ] && return 0    
   
    HOST=`$CMD_CAT /etc/mnttab | $CMD_GREP  $RELOCATED_ROOT | $CMD_GREP ":" | $CMD_CUT -d: -f1 | $CMD_HEAD -1`
    $CMD_PING $HOST > /dev/null 2> /dev/null
    [ $? -ne 0 ] && echolog 'WARNING: Host $2 not reachable' "$HOST"
    
    TMP_OSVERS=`$CMD_UNAME -r` # on local machine
    case $TMP_OSVERS in            
	    5.6*)   required_patch_for_SUNWesora=106292   ;;
	    2.6*)   required_patch_for_SUNWesora=106292   ;;
	    6)      required_patch_for_SUNWesora=106292   ;;
	    5.7*)   required_patch_for_SUNWesora=107443   ;;
	    2.7*)   required_patch_for_SUNWesora=107443   ;;
	    7)      required_patch_for_SUNWesora=107443   ;;
	    5.8*)   required_patch_for_SUNWesora=110934   ;;
	    2.8*)   required_patch_for_SUNWesora=110934   ;;
	    8)      required_patch_for_SUNWesora=110934   ;;
	    5.9*)   return 0   ;;
	    2.9*)   return 0   ;;
	    9)      return 0   ;;	    
	    5.10*)   return 0   ;;
	    2.10*)   return 0   ;;
	    10)      return 0   ;;	    
	    *)      echolog ''
		    echolog 'Unsupported OS version: $2' "$TMP_OSVERS"
	            return 2   ;;
    esac
   
    
    # temporary settings, to check on local machine.
    RELOC_PARAM=""     
    ORIG_PATCHES_INSTALLED="${PATCHES_INSTALLED}"
    PATCHES_INSTALLED=`${CMD_PATCHADD} -p | $CMD_AWK ' { print $2 }'`    
          
    is_patch_needed $required_patch_for_SUNWesora    	
    if [ $? -eq 1 ] ; then
        ret_val=1	    
    else
        ret_val=0
    fi 
    
    # restore settings before return. 
    PATCHES_INSTALLED=${ORIG_PATCHES_INSTALLED}
    RELOC_PARAM="-R $RELOCATED_ROOT"
    export RELOC_PARAM
    return $ret_val
}


#
#This function works on patches specified in variable $PATCH_NAME
#If any of the patches not available then it will return 1 else
#it will return 0. It puts patches not available in variable 
#reqrd_patch_not_avail.
#

checkInObsoletedPatch() {
    
    obsolete_patch=""
    obsolete_patch=`${CMD_PATCHADD} $RELOC_PARAM -p | $CMD_CUT -d : -f 3`
    for each_obsolete_patch in $obsolete_patch
    do
         if [ $each_obsolete_patch = "Requires" ] ; then
              continue              
         fi
         #echo $each_obsolete_patch
         obsolete_patch_number=`echo $each_obsolete_patch | $CMD_CUT -d- -f1`
         obsolete_patch_version=`echo $each_obsolete_patch | $CMD_CUT -d- -f2`
         obsolete_patch_version=`echo $obsolete_patch_version | $CMD_CUT -c1,2 `

         if [ $obsolete_patch_number -eq $1 ] ; then
                 if [ $obsolete_patch_version -ge $2 ] ; then
                      return 0
                 fi
         fi
    done
    return 1
}

checkInAvailPatch() {


        required_patch_number=$1
        required_patch_version=$2


        patch_number_found=`echo $PATCHES_INSTALLED | $CMD_GREP -c $required_patch_number`
        if [ $patch_number_found -eq 0 ] ; then
                return 1
        fi
        for avail_patch  in $PATCHES_INSTALLED ;
        do
                avail_patch_number=`echo $avail_patch | $CMD_CUT -d- -f1`
                avail_patch_version=`echo $avail_patch | $CMD_CUT -d- -f2`

                if [ $required_patch_number -eq $avail_patch_number ] ; then
                        if [ $required_patch_version -le $avail_patch_version ]; then
                                return 0
                        fi
                fi
        done
        return 1
}

check_postinstall_patch_dependency () {
    required_patchlist="$1"

    reqrd_patch_not_avail=""
    reqrd_patch_not_avail_flag=0

    required_patch_number=""
    required_patch_version=""  
    

    for each_required_in_patchlist in $required_patchlist
    do
        # check if the patch is present

        required_patch_number=`echo $each_required_in_patchlist | $CMD_CUT -d- -f1`
        required_patch_version=`echo $each_required_in_patchlist | $CMD_CUT -d- -f2`

        checkInAvailPatch  $required_patch_number  $required_patch_version
        ret=$?        
        if [ $ret -eq 1 ] ; then
            checkInObsoletedPatch $required_patch_number $required_patch_version
            if [ $? -eq 1 ] ; then
                reqrd_patch_not_avail="$reqrd_patch_not_avail $each_required_in_patchlist"
                reqrd_patch_not_avail_flag=1
            fi
        fi
    done

    if [ $reqrd_patch_not_avail_flag -eq 1 ] ; then
            return 1
    fi
    return 0
}

#
#It checks the version of package installed on the machine and version
#of one of the package in patch. If they match, it returns 0 else it 
#returns 1.
#

is_patch_version_correct ()
{
    patch_to_be_checked="$1"
    patch_directory="$2"
    packages_in_patch=`$CMD_LS -1 "$2/$1" | $CMD_GREP SUNW`
    for each_pkg in $packages_in_patch
    do
        $CMD_PKGINFO $RELOC_PARAM -qi $each_pkg > /dev/null 2>&1
        if [ $? -eq 0 ] ; then
            installed_version_string=`$CMD_PKGPARAM $RELOC_PARAM $each_pkg VERSION`
            patch_version_string=`$CMD_PKGPARAM $RELOC_PARAM -f $2/$1/$each_pkg/pkginfo VERSION`
            if [ "$installed_version_string" = "$patch_version_string" ] ; then
                return 0
            else
                return 1
            fi
        else
            continue
        fi
    done
    return 1
}

is_patch_needed ()
{
    #
    #Here we may want to see if we have some package installed 
    #for which the patch is not installed. System will say patch
    #is installed even if it was installed for only 2 packages
    # out of more then 2.
    #

    patch_name=$1
    check_postinstall_patch_dependency "$patch_name"
    if [ $? -eq 1 ] ; then
        return 1
    fi

    packages_patched=`${CMD_PATCHADD} $RELOC_PARAM -p | $CMD_GREP $patch_name | $CMD_CUT -d : -f 6`
    #
    # This is required because on some machines, packages are separated by commas.
    #
    packages_patched=`echo $packages_patched | $CMD_SED -e 's/,//g'`

    packages_in_patch=""
    packages_in_patch=`$CMD_LS -1 "$PATCH_DIRECTORY/$patch_name" | $CMD_GREP SUNW`

    for each_package in $packages_in_patch
    do
        #
        #See if the package is installed on the system, if yes then
        #if it is present in the patched packages. If no then install
        #the patch.
        #
        $CMD_PKGINFO -qi $RELOC_PARAM $each_package
        if [ $? -eq 0 ] ; then
            #
            #package is installed on the system, so now check for the 
            #version of installed package and package in the patch. If
            #they are not same then dont install patch.
            #

            installed_package_version=""
            patch_package_version=""
            installed_package_version=`$CMD_PKGPARAM $RELOC_PARAM $each_package SUNW_PRODVERS`
            patch_package_version=`$CMD_PKGPARAM -f ${PATCH_DIRECTORY}/${patch_name}/${each_package}/pkginfo SUNW_PRODVERS`
            if [ "$installed_package_version" = "$patch_package_version" ] ; then
		echo "$packages_patched" | $CMD_GREP $each_package >/dev/null 2>&1
		if [ $? -ne 0 ] ; then
		    #
		    #package is not patched yet, so lets patch it.
		    #
		    return 1
		fi
            fi
        fi
    done

    return 0
}


add_postinstall_patches () 
{
    PATCH_DIRECTORY=""  
    PATCH_PARAM=""
    if [ -z "$RELOCATED_ROOT" -o "$RELOCATED_ROOT" = "/" ]; then
	[ `${CMD_UNAME} -r` = "5.10" ] && PATCH_PARAM="-G"
    fi
    for each_patch in $1
    do
	if [ ! -d "${OS_PATCH_DIRECTORY}/${each_patch}" ] ; then
	    if [ ! -d "${COMMON_PATCH_DIRECTORY}/${each_patch}" ] ; then
		continue
	    else
		PATCH_DIRECTORY="${COMMON_PATCH_DIRECTORY}"
	    fi
	else
	    PATCH_DIRECTORY="${OS_PATCH_DIRECTORY}"
	fi
	echolog ''
	echolog 'Adding patch $2' "$each_patch"	
	${CMD_PATCHADD} ${PATCH_PARAM} $RELOC_PARAM $PATCH_DIRECTORY/$each_patch 2>&1 | $CMD_TEE -a $LOGFILE
	if [ $? -ne 0 ] ; then
            FAILED_PATCHES="$FAILED_PATCHES $each_patch"	
	fi
    done    
    if [ -z "$FAILED_PATCHES" ] ; then
        return 0
    fi    
    return 1
}


installPatches () 
{    
    [ "$SOURCE_IMAGE" = "PATCH_ONLY" ] && INSTALL_SUNMC_PATCHES=1
    
    #first check if any patches are required at all
    #if not, we dont need to go to the last CD
    
    INSTALLED_KEYS=`$API_QUERY_REGISTRY "$REGISTRY" "product" "key" 2>/dev/null` 
    PATCH_PRODUCTS=""
    for PRODUCT_KEY in `$CMD_ECHO "$INSTALLED_KEYS" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
    do        
        checkPatches
        ret=$?        
        [ $ret -eq 0 ] && continue        
        PATCH_PRODUCTS="${PATCH_PRODUCTS} ${PRODUCT_KEY}"        
    done
        
    [ -z "${PATCH_PRODUCTS}" -a $INSTALL_SUNMC_PATCHES -eq 0 ] && return 0
    echolog ''
    
    #now do the work
    echolog 'Adding required patches...'
    echolog ''
    
    getPatchDirectory    
    
    for PRODUCT_KEY in `$CMD_ECHO "$PATCH_PRODUCTS"`
    do    
        name=`$API_QUERY_REGISTRY "$REGISTRY" "product=${PRODUCT_KEY}" "name" 2>/dev/null`
        
        checkPatches
        ret=$?
        #echolog 'Patches required by $2 are :' "$name"
        #$CMD_ECHO "    \c"
        #echolog '$PATCH_LIST'
        
        if [ $ret -eq 1 ] ; then            
            $CMD_ECHO "    \c"
            echolog 'The following patches are neither available nor present on your system'
            $CMD_ECHO "    \c"
            echolog '$MISSING_PATCHES'  
            $CMD_ECHO "    \c"
            echolog 'You must install them later.'          
        fi
        installPatchesInList

        # condition added to reset OSVERS variable to "10"
        if [ "$PROGNAME" != "archive-tool" ]; then
            if [ "$OSVERS_BITS" = "" ]; then
                OSVERS_CURRENT=`$CMD_UNAME -r`
                if [ "$OSVERS_CURRENT" = "5.10" ]; then
	            OSVERS="10"
                fi
            else
                if [ "$OSVERS_BITS" = "10" ]; then
	            OSVERS="10"
                fi
	    fi
        fi

    done
  
    if [ $INSTALL_SUNMC_PATCHES -eq 1 ] ; then
        PATCH_DIR=${PATCH_DIR}/Essential        
        installPatchesInList "all"        
    fi
    
    if [ -n "$FAILED_PATCHES" ] ; then            
        echolog 'WARNING : The following patches could not get installed = $2' "$FAILED_PATCHES"
        return 1
    fi

} 


#reads: PATCH_DIR PATCH_LIST
# if $1 is "all", doesnt read PATCH_LIST but installs all patches in PATCH_DIR
#
installPatchesInList() {  
    
    # Special case for Solaris 10. If Solaris_10 not present, look for
    # Solaris_9 Only for a Patch only image. Otherwise, we assume that
    # OSVERS is set correctly before

    if [ "${OSVERS}" = "10" ]; then
	[ ! -d "${PATCH_DIR}/Solaris_${OSVERS}" -a \
	    -d "${PATCH_DIR}/Solaris_9" ] && OSVERS=9
    fi
    OS_PATCH_DIRECTORY="${PATCH_DIR}/Solaris_${OSVERS}"
    COMMON_PATCH_DIRECTORY="${PATCH_DIR}/Common"

    patches_tobe_installed=""
    
    if [ "$1" = "all" ] ; then
        PATCH_LIST=""
        [ -d "$OS_PATCH_DIRECTORY" ] && PATCH_LIST=`$CMD_LS -1 ${OS_PATCH_DIRECTORY}`
        [ -d "$COMMON_PATCH_DIRECTORY" ] && PATCH_LIST="${PATCH_LIST} `$CMD_LS -1 ${COMMON_PATCH_DIRECTORY}`"
    fi
    [ -z "${PATCH_LIST}" ] && return 0    
    
    for each_patch in `$CMD_ECHO "$PATCH_LIST" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
    do
        PATCH_NAME="$each_patch"
        PATCH_DIRECTORY=""
	if [ ! -d "${OS_PATCH_DIRECTORY}/${PATCH_NAME}" ] ; then
            if [ ! -d "${COMMON_PATCH_DIRECTORY}/${PATCH_NAME}" ] ; then
		continue
            else
                PATCH_DIRECTORY="${COMMON_PATCH_DIRECTORY}"
            fi
        else
	    PATCH_DIRECTORY="${OS_PATCH_DIRECTORY}"
	fi
	
        is_patch_version_correct "${PATCH_NAME}" "${PATCH_DIRECTORY}"
        ret=$?	
        if [ $ret -eq 1 ] ; then
            continue
        fi
	is_patch_needed $PATCH_NAME
	ret=$?	
	if [ $ret -eq 1 ] ; then
	    patches_tobe_installed="$patches_tobe_installed $PATCH_NAME"
	fi
    done
    if [ ! -z "$patches_tobe_installed" ] ; then    
	add_postinstall_patches "$patches_tobe_installed"
	return $?
    fi
}


getPatchDirectory() {

    getLastCD 
  
    getCurrentCD

    if [ "$LAST_CD" = "$CURRENT_CD" ] ; then
        if [ "$SOURCE_IMAGE" = "PATCH_ONLY" ] ; then
            PATCH_DIR="${SRC_DIR}"
        else
            PATCH_DIR="${SRC_DIR}/Patches"
        fi
        
        if [ ! -d ${PATCH_DIR} ] ; then
            $CMD_ECHO "  \c"
            echolog 'Unable to find $PATCH_DIR'            
        fi
        return         
    fi

    while [ 1 ] ; do
        
        [ "$SOURCE_IMAGE" = "PATCH_ONLY" ] && echolog 'Cant find Patch Directory' && break
        
        if [ -d "${SRC_DIR}/${DOTPREFIX}../../disk${LAST_CD}/${IMGPREFIX}/image" ] ; then # disk image 
            answer=`getPathName "${SRC_DIR}/${DOTPREFIX}../../disk${LAST_CD}/${IMGPREFIX}/image"`
        else
            cd /
            eject -q cd 2> /dev/null
            [ $? -eq 0 ] && eject cd 2> /dev/null
            tmp_auto="/cdrom/cdrom0/image"
            fetch_response_text "TAG=CORE_DISK${LAST_CD}" 'Insert the last CD or enter the source directory for disk $3 \\\[$4\\\]' "$LAST_CD" "$tmp_auto"
            [ -z "$answer" ] && answer=$tmp_auto        
        fi
    
        count=0
        while [ 1 ] ; do
            sleep 1
            if [ -d "$answer" ] ; then
                break
            fi
            count=`$CMD_EXPR $count + 1`
            if [ $count -ge 10 ] ; then
                echolog 'Invalid directory $2' "$answer"
                break
            fi
        done
        
        PATCH_DIR="$answer/Patches"
    
        if [ ! -d ${PATCH_DIR} ] ; then
            $CMD_ECHO "  \c"
            echolog 'Unable to find $PATCH_DIR'
        else
            echologverbose 'Patch directory: $2' "$PATCH_DIR"  
        fi
        break
    done
}

# Asks the user whether or not to install the documentation.
# Sets the variable INSTALL_DOCS="TRUE"
#
selectDocumentation () {

    [ "$SOURCE_IMAGE" = "PATCH_ONLY" ] && return
    
    checkString "$INSTALL_LAYERS" "LAYER.SERVER" 
    [ $? -eq 1 ] && return    

    $CMD_PKGINFO -qi SUNWpsmd
    [ $? -eq 0 ] && return       # Documentation is already installed.

    READ_RESPONSE_ONCE=0            
    echolog ''
    echolog 'You can install the product documentation.'
    echolog 'The documentation will get installed in the languages chosen previously.'
    fetch_response_yes_no "TAG=INSTALL_DOCS" "Install Product Documentation."
    saveAutoConfig  "INSTALL_DOCS" "$answer"
   
    [ -z "$answer" ] && answer=0
    
    if [ "$answer" = "1" ]; then
        echolog "Selecting Product Documentation for installation"
        echolog ''
        echolog ''
        INSTALL_DOCS="TRUE"
    else
        INSTALL_DOCS="FALSE"
    fi

}

# A function to check which all OS versions are available in the soruce dir.
# The function returns a comma separated list of supported os versions.
# e.g. "2.6,7,8,9,10"

find_available_os_versions () {
    l_source_image="$SOURCE_IMAGE"
    l_ref_osvers="2.6,7,8,9,10"
    l_supp_osvers=""
    l_addon_dirs=""
    l_src_dir="$SRC_DIR"

    case $l_source_image in
        DEFAULT)
            for l_os in `$CMD_ECHO "$l_ref_osvers" | $CMD_AWK -F ',' '{ for (i=1; i<=NF ; i++) print $i }'` 
            do
		l_osdir=$l_os
		# For S10, check whether Solaris_10 exists. Else check for
		# Solaris_9
		[ $l_os -eq 10 -a ! -d "${l_src_dir}/PE/Solaris_10" ] && l_osdir=9
                if [ -d "${l_src_dir}/PE/Solaris_${l_osdir}" ]; then
                    if [ -z "$l_supp_osvers" ]; then
                        l_supp_osvers="${l_os}"
                    else
                        l_supp_osvers="${l_supp_osvers},${l_os}"
                    fi
                fi 
            done
            ;;
        ADDON_ONLY)
            l_addon_dirs=`$CMD_LS "${l_src_dir}/Addons"`
            l_addon_dirs=`$CMD_ECHO "$l_addon_dirs" | $CMD_SED "s/\\n/ /g"`
            for l_os in `$CMD_ECHO "$l_ref_osvers" | $CMD_AWK -F ',' '{ for (i=1; i<=NF ; i++) print $i }'` 
            do
		l_osdir=$l_os
		# For S10, check whether Solaris_10 exists. Else check for
		# Solaris_9
		[ $l_os -eq 10 -a ! -d "${l_src_dir}/Addons/${l_addon}/Solaris_10" ] && l_osdir=9
                for l_addon in `$CMD_ECHO "$l_addon_dirs"` 
                do
                    if [ -d "${l_src_dir}/Addons/${l_addon}/Solaris_${l_osdir}" ]; then
                        if [ -z "$l_supp_osvers" ]; then
                            l_supp_osvers="${l_os}"
                            break
                        else
                            l_supp_osvers="${l_supp_osvers},${l_os}"
                            break
                        fi
                    fi
                done
            done
            ;;
        PATCH_ONLY) 
            for l_os in `$CMD_ECHO "$l_ref_osvers" | $CMD_AWK -F ',' '{ for (i=1; i<=NF ; i++) print $i }'` 
            do
		l_osdir=$l_os
		# For S10, check whether Solaris_10 exists. Else check for
		# Solaris_9
		[ $l_os -eq 10 -a ! -d "${l_src_dir}/Solaris_10" ] && l_osdir=9
                if [ -d "${l_src_dir}/Solaris_${l_osdir}" ]; then
                    if [ -z "$l_supp_osvers" ]; then
                        l_supp_osvers="${l_os}"
                    else
                        l_supp_osvers="${l_supp_osvers},${l_os}"
                    fi
                fi 
            done
            ;;
    esac

    $CMD_ECHO "$l_supp_osvers"
}

checkSourceDirArch () {
    REFARCH=$1
    CUR_DIR=`$CMD_PWD`
    cd $SRC_DIR/..
    PAR_DIR=`$CMD_BASENAME \`$CMD_PWD\``
    cd $CUR_DIR

    # if called from Install Client, dont validate
    [ "$SETUP_AGENTUPDATE_FLAG" != "" ] && return 0

    # if REFARCH not set, id the architecture based on the source dir
    if [ "$REFARCH" = "" ]; then
        TGTARCH=sparc
        [ "$PAR_DIR" = "x86" ] && TGTARCH="i386"
        export TGTARCH
	return 0
    fi

    # Validate the SRC_DIR against the architecture
    if [ "$REFARCH" = "i386" -a "$PAR_DIR" != "x86" ]; then
	echolog  'Invalid source path for architecture $2' "$REFARCH"
	return 1
    fi
    if [ "$REFARCH" = "sparc" -a "$PAR_DIR" = "x86" ]; then
	echolog  'Invalid source path for architecture $2' "$REFARCH"
	return 1
    fi
    return 0
}
