#!/bin/sh

# Copyright 05/31/05 Sun Microsystems, Inc. All Rights Reserved.
#pragma ident "@(#)archive-tool-functions.sh	1.96 05/05/31 Sun Microsystems"


###################################################### 
# Gloabal variables and functions
# The file is sourced by es-imagetool script
# and all Wizard backend scripts 
# 
###################################################### 

# Common commands not in es-common.sh

CMD_TAR=${COMMAND_ROOT}/usr/bin/tar
CMD_COMPRESS=${COMMAND_ROOT}/usr/bin/compress
CMD_SPLIT=${COMMAND_ROOT}/usr/bin/split
CMD_PKGMK=${COMMAND_ROOT}/usr/bin/pkgmk
CMD_DU=${COMMAND_ROOT}/usr/bin/du
CMD_FIND=${COMMAND_ROOT}/usr/bin/find



# Functions

# This function will print the usage report 
# in case an invalid option is used or -h option is used.

usage()
{
	echolog 'Usage: $2 [ -s k ] -h' "$IMAGETOOL_PROGNAME"
        echo '       \c'
	echolog '-s : Splits an image into pieces k*1024 bytes in size.'
        echo '       \c'
	echolog '-h : prints this usage report.'
}

# This function sets the variable for upgrade policy file.
# It also creates empty policy file xml document.

init_policy_file()
{
	UPGRADE_POLICY_FILE="$SMART_UPDATE_DIR/upgrade-policy.xml"
	UPGRADE_POLICY_FILE_NAME=`$CMD_BASENAME "$UPGRADE_POLICY_FILE"`
	$API_CREATE_DOC $UPGRADE_POLICY_FILE upgrade-policy 2>/dev/null
	$API_INSERT_TAG $UPGRADE_POLICY_FILE products=SunMC 2>/dev/null
	$API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE products="SunMC" selected-os="$SELECTED_OS" 2>/dev/null
	$API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE products="SunMC" image-arch="$IMAGETOOL_ARCH" 2>/dev/null
}

# The image tool should only be run if SunMC server is installed.
# This function checks for the availability of SUNWsusrv package

check_server()
{
	echolog 'Checking for Sun Management Center server'
	$CMD_PKGINFO -qi SUNWessrv
	if [ $? -eq 1 ] ; then
		echolog "Sun Management Center Server not installed." 
		echolog "Exiting..."
                releaseImageToolLock
		exit 1
	fi

	echolog 'Checking for web server'
	$CMD_PKGINFO -qi SUNWtcatu
	if [ $? -eq 1 ] ; then
                echolog 'Web Server not installed.' 
		echolog "Exiting..."
                releaseImageToolLock
		exit 1
        fi

	set_inst_base_dir # To set the BASEDIR variable

}


# This function sets the API dir variables for XML APIs
# This variable is also used to locate InstallClient binary 

setAPIDirs()
{
	API_OSVERS=`$CMD_UNAME -r`
	case $API_OSVERS in
            5.6*)   API_OSVERS=2.6   ;;
            5.7*)   API_OSVERS=2.7     ;;
            5.8*)   API_OSVERS=2.8     ;;
            5.9*)   API_OSVERS=2.9     ;;
            5.10*)   API_OSVERS=2.10     ;;
            *)      echolog ''
                echolog 'Unsupported OS version: $2' "$OSVERS"
                releaseImageToolLock
                exit 1           ;;
        esac
	API_ROOT=`$CMD_PKGINFO -r SUNWescom`/SUNWsymon
        if [ -z "$API_ROOT" ]; then
                echolog "Sun Management Center is not installed.."
		echolog "Cannot find XML Apis"
		echolog "Exiting..."
                releaseImageToolLock
                exit 1
        fi

	API_DIR=$API_ROOT/base/bin/sparc-sun-solaris${API_OSVERS}
	LIB_DIR=$API_ROOT/base/lib/sparc-sun-solaris${API_OSVERS}

	LD_LIBRARY_PATH=$LIB_DIR:$LD_LIBRARY_PATH
	export LD_LIBRARY_PATH
}


# This will set the variable INSTALL_RESPONSE_FILE, SETUP_RESPONSE_FILE
# This is called only 1 time by es-imagetool and one of
# the GUI backend scripts. This will redirect the output of
# tmpResponses.cfg which gets created to collect  few initial responses.

getBaseResponseFileNames()
{
        INSTALL_RESPONSE_FILE="install-response.cfg"
	if [ "$ARCHIVE_BASE_FLAG" = "1" ]; then
        	SETUP_RESPONSE_FILE="setup-response.cfg"
	fi

	$CMD_CAT $AUTOCONFIG_SAVEFILE > "$SMART_UPDATE_DIR/disk1/image/PE/$INSTALL_RESPONSE_FILE"
	$CMD_RM -f "$SMART_UPDATE_DIR/tmpResponses.cfg"
	AUTOCONFIG_SAVEFILE="$SMART_UPDATE_DIR/disk1/image/PE/$INSTALL_RESPONSE_FILE"
}


# This function collects user responses to base setup queries
# And puts them into setup response file.
# Only called if Base Agent is selected for upgrade operation. 

askBaseSetupQuestions()
{
        echo " "
        echo " "
        echo " "
	while [ "1" = "1" ]
	do
        multiline_echolog "Specify the Port Number to be used for configuring the agent.\n\nPress the ENTER key to use the existing or the default port.\nIf the agent is already configured, the existing port will be used.\nIf there is no previous agent installation and configuration,\nthe default [161] port will be used.\n\nYou can also enter a specific port number to be used for configuring\nthe agents on the destination host machines."
        $CMD_ECHO " "

	#echolog 'Press ENTER key to force default port.'
	get_input_from_user 'Enter the agent port number [Port Range: 1100 to 65535 ]:'
	if [ -z "$answer" ]; then
		AGENT_PORT="DEFAULT"          #  DEFAULT is taken as 161
	else
		validate_port "$answer"
		if [ $? -eq 0 ]; then
			AGENT_PORT="$answer"
		else
			continue
		fi
	fi

      if [ "$AGENT_PORT" = "DEFAULT" ]; then 

          echolog ''
          if [ ${is_s10_or_above_selected} -eq 0 -a ${is_s9_or_below_selected} -eq 1 ]; then
          	multiline_echolog "You have selected the default [161] port.\nPort 161 is used by the SNMP Daemon snmpdx by default,\nand may start automatically each time a machine is rebooted.\nThe SNMP Daemon snmpdx is not needed when running Sun Management Center."
		ask_user 'Do you want to Stop and Disable SNMP Daemon snmpdx'
		STOP_SNMPDX=$answer
	  elif [ ${is_s10_or_above_selected} -eq 1 ]; then
		multiline_echolog "WARNING: You have selected the SunMC agent to run on the default port 161,\nwhich is typically used by Solaris System Management Agent (SMA) on Solaris 10.\nIf you are running on Solaris 10, SMA automatically uses port 161.  The SMA\n(process snmpd) is based on the SNMPv3 protocol and it is *NOT* advisable\nto disable it.  We recommend that you run the  SunMC agent on a different port.\nIf the SMA is not disabled, the SunMC agent will *NOT* start after a reboot."
		$CMD_ECHO " "
		ask_user 'Do you want to select a different port?'
		PORT_CHANGE=$answer
		[ "$PORT_CHANGE" = "1" ] && continue
		if [ ${is_s9_or_below_selected} -eq 1 ]; then
			$CMD_ECHO " "
			multiline_echolog "Port 161 is used by the SNMP Daemon snmpdx by default on Solaris 9\nand below. It may start automatically each time a machine is rebooted.\nThe SNMP Daemon snmpdx is not needed when running Sun Management Center."
			$CMD_ECHO " "
			multiline_echolog "Do you want to Stop and Disable SNMP Daemon snmpdx on hosts running Solaris9\nand below and continue if SMA is using port 161 on hosts running Solaris 10?"
			ask_user ''
			STOP_SNMPDX=$answer 
			CONTINUE_IF_SMA_PRESENT=$STOP_SNMPDX
		else
			$CMD_ECHO " "
			ask_user 'Do you want to continue if SMA is using port 161 on hosts running Solaris 10?'
			CONTINUE_IF_SMA_PRESENT=$answer
			STOP_SNMPDX=$CONTINUE_IF_SMA_PRESENT
		fi
		$CMD_ECHO " "
		multiline_echolog "Note: To use the default port 161 for SunMC on Solaris 10, you will need to\ndisable the SMA SNMP Daemon snmpd running on port 161 before installing SunMC"
		sleep 4
          fi
	else
	  STOP_SNMPDX="0"
	fi
	   break
	done

	HOSTNAME=`$CMD_UNAME -n`       

        # This is running on server. This is going to be the response
        # to server query during the setup of agent
	
	$CMD_ECHO "SUNMC_SERVER=$HOSTNAME" >> $SMART_UPDATE_DIR/disk1/image/PE/$SETUP_RESPONSE_FILE
	$CMD_ECHO "agent_OPTIONAL_PORT=$AGENT_PORT" >> $SMART_UPDATE_DIR/disk1/image/PE/$SETUP_RESPONSE_FILE

    if [ "$AGENT_PORT" = "DEFAULT" -a ${is_s10_or_above_selected} -eq 1 -a "$CONTINUE_IF_SMA_PRESENT" = "1" ]; then
        $CMD_ECHO "CONTINUE_IF_SMA_PRESENT=1" >> $SMART_UPDATE_DIR/disk1/image/PE/$SETUP_RESPONSE_FILE
    elif [ "$AGENT_PORT" = "DEFAULT" -a ${is_s10_or_above_selected} -eq 1 -a "$CONTINUE_IF_SMA_PRESENT" = "0" ]; then
        $CMD_ECHO "CONTINUE_IF_SMA_PRESENT=0" >> $SMART_UPDATE_DIR/disk1/image/PE/$SETUP_RESPONSE_FILE
    fi

        # Now write all the required, default responses.
	updateSetupResponseForNoBase "$STOP_SNMPDX"
}


# This function sets all default required responses for agent setup
# These responses are necessary, no matter base is being setup or not.
# $1 : Response value to DISABLE_SNMPDX_DAEMON tag
#      Values 0 = No  1 = Yes

updateSetupResponseForNoBase()
{
	STOP_SNMPDX="$1"
        SETUP_RESPONSE_FILE="setup-response.cfg"
	$CMD_ECHO "START_SUNMC=0" >> $SMART_UPDATE_DIR/disk1/image/PE/$SETUP_RESPONSE_FILE
	$CMD_ECHO "DISABLE_SNMPDX_DAEMON=${STOP_SNMPDX}" >> $SMART_UPDATE_DIR/disk1/image/PE/$SETUP_RESPONSE_FILE
	$CMD_ECHO "STOP_SNMPDX=${STOP_SNMPDX}" >> $SMART_UPDATE_DIR/disk1/image/PE/$SETUP_RESPONSE_FILE
	$CMD_ECHO "LOGICAL_ADDRESS_MODE=ip" >> $SMART_UPDATE_DIR/disk1/image/PE/$SETUP_RESPONSE_FILE
	$CMD_ECHO "IMPORT_PREVIOUS_DATA=1" >> $SMART_UPDATE_DIR/disk1/image/PE/$SETUP_RESPONSE_FILE
        $CMD_ECHO "RESPONSES_FOR_AGENT_UPDATE=TRUE" >> $SMART_UPDATE_DIR/disk1/image/PE/$SETUP_RESPONSE_FILE
}


# Check the validity of the number entered for agent port
# Check if it's a numeric value
# Then check for the port range 
# $1 : Port Number input
# Returns 0 if valid. returns non zero otherwise

validate_port()
{
	port="$1"
	$CMD_EXPR $port + 1 1> /dev/null 2>&1
	retcode=$?
	if [ $retcode -ne 0 ] ; then
		echolog 'Port $2 is not a valid port number, Please try again.' "$port"
		return $retcode
	fi

      if [ $port -lt 1100 -o $port -gt 65535 ] ; then
         echolog 'Invalid port. Please try again.'
         retcode=1
      fi

	return $retcode
}


# This function updates the policy file just before starting the image creation
# It puts top level product element and it's attributes
# Sets some default values for attributes

updatePolicyForAddons()
{
    UNIQUE_SELECTED_KEYS=""     # This is IMP don't delete
    for OS in `$CMD_ECHO "$SELECTED_OS" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
    do
        resetSourceList $OS         
        resetSelectedKeys $OS       

        for addon_product_key in `$CMD_ECHO "$SELECTED_KEYS" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
        do
                # Base product keys are added by updatePolicyForBaseProduct
                # So no need to add again
                [ "$addon_product_key" = "PRODUCT.PE" ] && continue

                isSelectedKeyProcessed $addon_product_key
                [ $? -eq 0 ] && continue

                addon_product_name=`getProductAttr "$SOURCE_LIST" "$addon_product_key" "NAME"`
                addon_version=`getProductAttr "$SOURCE_LIST" "$addon_product_key" "PRODVERS"`
                RESPONSE_FILE_PATH=""
                $API_INSERT_TAG $UPGRADE_POLICY_FILE products=SunMC product=$addon_product_key 2>/dev/null
                $API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=$addon_product_key name="$addon_product_name" 2>/dev/null
                $API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=$addon_product_key type="Addon" 2>/dev/null
                $API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=$addon_product_key version="$addon_version" 2>/dev/null
                $API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=$addon_product_key archive-type="tar.Z" 2>/dev/null
                $API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=$addon_product_key do-setup=0 2>/dev/null

        done
    done
}


# This function goes through every selected addon
# Checks if server layer of this addon is installed  
# locates the Addon subdir and setup-resp.sh script
# creates an empty response file under target archive dir
# Calls setup-resp.sh and passed the path of this file
# 
# The function is also called by a script that runs in the
# terminal window opened by Wizard

askAddonSetupResponses()
{
    HOSTNAME=`$CMD_UNAME -n`
    REGISTRY_FILE="/var/opt/SUNWsymon/install/Registry_${HOSTNAME}.xml"
    UNIQUE_SELECTED_KEYS=""     # This is IMP don't delete

    echo ' '
    echo ' '

    for OS in `$CMD_ECHO "$SELECTED_OS" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
    do
        resetSourceList $OS         
        resetSelectedKeys $OS       

        for addon_product_key in `$CMD_ECHO "$SELECTED_KEYS" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
        do
            [ "$addon_product_key" = "PRODUCT.PE" ] && continue

            isSelectedKeyProcessed $addon_product_key
            [ $? -eq 0 ] && continue

            addon_product_name=`getProductAttr "$SOURCE_LIST" "$addon_product_key" "NAME"`
	    addon_version=`getProductAttr "$SOURCE_LIST" "$addon_product_key" "PRODVERS"`
	    RESPONSE_FILE_PATH=""

	    if [ ! -f "$REGISTRY_FILE" ]; then
		echologverbose 'Cannot access registry information for addon setup tool'
	        exit 1
	    fi

            # get a list of keys of installed addons

	    addons_installed=`$API_QUERY_XML $REGISTRY_FILE product key 2>/dev/null`
	    $CMD_ECHO "$addons_installed" | $CMD_GREP "$addon_product_key" 1>/dev/null 2>&1
	    if [ $? -ne 0 ]; then
		echologverbose 'Addon $2 not installed ...' "$addon_product_name"
	    	echologverbose 'Setup response tool not found for $2' "$addon_product_name"
    		echo ' '
    		echo ' '
    		echo ' '
		echolog '$2' "$addon_product_name"
	    	echo '---------------------------------------'
		echolog 'WARNING: Server layer of this Add-On is not installed.'
		echolog 'This Add-On will be installed on target agents but will not be setup'
		echolog 'Agent installation of this add-on may not work as expected'
		sleep 4    # The sleep is required for better usability
                           # when terminal window is invoked from GUI
	    	continue
	    fi

            # Get the Addon subdirectory to look for setup-resp.sh

	    addon_srcdir=`$API_QUERY_XML $REGISTRY_FILE product=$addon_product_key target_subdir 2>/dev/null`
	
	    PRODUCT_BASEDIR=`$CMD_PKGPARAM SUNWescom BASEDIR 2>/dev/null`
	    if [ $? -ne 0 ]; then
	        echolog 'Sun Management Center not installed properly'
	        exit 1
	    fi

	    addon_srcdir="$PRODUCT_BASEDIR/SUNWsymon/addons/$addon_srcdir"

	    if [ ! -f "$addon_srcdir/sbin/setup-resp.sh" ]; then
	    	echologverbose 'Setup response tool not found for $2' "$addon_product_name"
    		echo ' '
    		echo ' '
    		echo ' '
		echolog '$2' "$addon_product_name"
	    	echo '---------------------------------------'
		echolog 'WARNING: This Add-On is not agent-update compatible'
		echolog 'This Add-On will be installed but will not be setup'
		echolog 'Agent installation of this add-on may not work as expected'
		sleep 4    # The sleep is required for better usability
                           # when terminal window is invoked from GUI
	    	continue
	    fi

	    echo ' '
    	    echo ' '
    	    echo ' '
	    echolog '$2' "$addon_product_name"
	    echo '---------------------------------------'
	    echo ' '
	    RESPONSE_FILE_PATH="$TARGET_ARCHIVE_DIR/${addon_product_key}-setup-response.cfg"
	    $CMD_TOUCH $RESPONSE_FILE_PATH

            # export this variable so that addon setup-resp tool
            # will be able to find out what all optional components
            # have been selected

            export ALL_SELECTED_OPTIONALS
	    /usr/bin/sh $addon_srcdir/sbin/setup-resp.sh $RESPONSE_FILE_PATH
            ret_value=$?
	    if [ $ret_value -eq 0 ]; then       # Setup can be done safely
	        $API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=$addon_product_key do-setup=1 2>/dev/null
            elif [ $ret_value -eq 2 ]; then     # User requested to quit 
                $CMD_RM -rf $TARGET_ARCHIVE_DIR 
		sleep 2    # The sleep is required for better usability
                           # when terminal window is invoked from GUI

                releaseImageToolLock
                exit 2
	    fi
	    # Making a list in key:response-file path format separated by #
	    TMP_LIST="${RESPONSE_FILE_LIST}#${addon_product_key}:"
	    RESPONSE_FILE_LIST="${TMP_LIST}${RESPONSE_FILE_PATH}"
	    sleep 4        # The sleep is required for better usability
                           # when terminal window is invoked from GUI

	done
    done
    echo ' '
    echo ' '
    echo ' '
}

# This function updates the policy file just before starting the image creation
# It puts top level Bsae product element and it's attributes
# Sets some default values for attributes
# This is called no matter if base is selected or not

updatePolicyForBaseProduct()
{
	sunmc_version=`getProductAttr "$SOURCE_LIST" "PRODUCT.PE" "PRODVERS"`
	$API_INSERT_TAG $UPGRADE_POLICY_FILE products=SunMC product=PRODUCT.PE 2>/dev/null
	$API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=PRODUCT.PE type="Base" 2>/dev/null
	$API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=PRODUCT.PE name="Production Environment" 2>/dev/null
	$API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=PRODUCT.PE version="$sunmc_version" 2>/dev/null
	$API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=PRODUCT.PE archive-type="tar.Z" 2>/dev/null
	$API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=PRODUCT.PE install-response="$ARCHIVE_TARGET_DIRNAME/disk1/image/PE/$INSTALL_RESPONSE_FILE" 2>/dev/null
	if [ "$ARCHIVE_BASE_FLAG" = "1" ]; then
		$API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=PRODUCT.PE do-setup=1 2>/dev/null
	else
		$API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=PRODUCT.PE do-setup=0 2>/dev/null
	fi
	$API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=PRODUCT.PE setup-response=$ARCHIVE_TARGET_DIRNAME/disk1/image/PE/$SETUP_RESPONSE_FILE 2>/dev/null
}


# Top level function to 
# create tarball of base product agent packages & compress them

archiveBaseProduct()
{

#updatePolicyForBaseProduct

for ARCH_OSVERS in `$CMD_ECHO "$SELECTED_OS" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
do
        # This is for GUI 
	put_var_in_cfgfile "${ARCHIVE_PROGRESS_FILE}" "OSVERS" "$ARCH_OSVERS" "="
	put_var_in_cfgfile "${ARCHIVE_PROGRESS_FILE}" "PROCESS" "Archiving" "="

	resetSourceList $ARCH_OSVERS
	resetSortedComponentsList $ARCH_OSVERS

	for each_pkglist in `$CMD_ECHO "${SORTED_INSTALL_COMPONENTS_LIST}" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'` ; do
		PRODUCT_KEY=`$CMD_ECHO "$each_pkglist" | $CMD_AWK -F ':' '{ print $4 }'`
		[ "$PRODUCT_KEY" != "PRODUCT.PE" ] && continue
		tmp_component=`$CMD_ECHO "$each_pkglist" | $CMD_AWK -F ':' '{ print $1 }'`
		PKG_LIST=`$CMD_ECHO "$each_pkglist" | $CMD_AWK -F ':' '{ print $2 }'`
		#echo "Packages for Solaris_$OSVERS : $PKG_LIST"

		[ -z "$PKG_LIST" ] && continue
		makeArchive $PKG_LIST $ARCH_OSVERS "PE" "disk1" "PRODUCT.PE"
	done
done
	compressArchive "PE" "PRODUCT.PE" "disk1"
}

# Function that creates tar files of agent packages
# It also adds component scripts for products into OS archives
# It also updates the prototype file for runtime package creation
# $1=Package list; $2=OS Version; $3=Product dir; 
# $4=Disk number; $5=Product key

makeArchive()
{
        PACKAGE_LIST=$1
        OS_VERS=$2
        PRODUCT_SRCDIR="$3"
        DISK=$4
	PRODUCT_KEY=$5

	#PRODUCT_SRCDIR=`getProductAttr "$SOURCE_LIST" "$PRODUCT" "SOURCE_DIR"`
	UPDATE_PRODUCT_NAME=`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" "NAME"`

        PWD=`$CMD_PWD`
        cd "${SRC_DIR}/${PRODUCT_SRCDIR}"
	DOTCDFILE="${IMAGETOOL_PATHPREFIX}../../../.CD"
	[ "$PRODUCT_KEY" = "PRODUCT.PE" ] && DOTCDFILE="${IMAGETOOL_PATHPREFIX}../../.CD"

        for each_package in `$CMD_ECHO "$PACKAGE_LIST" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
        do
            echolog 'Adding $2' "$each_package"

            # This is for GUI
	    put_var_in_cfgfile "${PROGRESS_FILE}" "PACKAGE" "$each_package" "="
	    put_var_in_cfgfile "${PROGRESS_FILE}" "PRODUCT" "$UPDATE_PRODUCT_NAME" "="

            OSDIR="./Solaris_${OS_VERS}"
	    # If Solaris_10 dir doesnt exist, replacing with Solaris_9 to 
	    # prevent empty Solaris_10.tar.Z being created. This is a redundant
	    # but harmless operation since S9 components are always packaged
	    # when S10 is selected for image creation.

	    [ "${OS_VERS}" = "10" ] && [ ! -d "$OSDIR" ] && OS_VERS=9 && OSDIR="./Solaris_${OS_VERS}"

            #LOCATION=`$CMD_FIND ${OSDIR} -name $each_package`
            #if [ -z "$LOCATION" ]
            LOCATION="./${OSDIR}/Basic/$each_package"
            if [ ! -d "$LOCATION" ]
            then
                #LOCATION=`$CMD_FIND ./Common -name $each_package`
                LOCATION="./Common/Basic/$each_package"
                [ ! -d "$LOCATION" ] && LOCATION="./CommonForSolaris/Basic/$each_package"
                TARFILE="$TARGET_ARCHIVE_DIR/$DISK/image/${PRODUCT_SRCDIR}/Common.tar"
	        #TARFILE="$TARGET_ARCHIVE_DIR/${PRODUCT_SRCDIR}/Common.tar"
	        #echo "This is a common package"
            else
                    TARFILE="$TARGET_ARCHIVE_DIR/$DISK/image/${PRODUCT_SRCDIR}/Solaris_${OS_VERS}.tar"
		    #TARFILE="$TARGET_ARCHIVE_DIR/${PRODUCT_SRCDIR}/Solaris_${OS_VERS}.tar"
            fi

	    if [ ! -d "$LOCATION" ]; then
	        echolog "No packages for this OS"
	    else
                if [ -f $TARFILE ]
                then
                    $CMD_TAR -uvf $TARFILE $LOCATION
                else
		    #echolog "Tarfile does not exist"
                    $CMD_TAR -cvf $TARFILE $LOCATION
                    $CMD_TAR -uvf $TARFILE $DOTCDFILE
                fi
	    fi
        done

        # somtimes, there is no OS sepcific package
        # So forcefully create OS tarfile
        # since installation.info should always go to OS tarfile

        OSTARFILE="$TARGET_ARCHIVE_DIR/$DISK/image/${PRODUCT_SRCDIR}/Solaris_${OS_VERS}.tar"
	$CMD_TOUCH $OSTARFILE
	if [ -f $OSTARFILE ]; then
            $CMD_TAR -uvf $OSTARFILE ./Solaris_${OS_VERS}/installation.info
            $CMD_TAR -uvf $OSTARFILE ./Solaris_${OS_VERS}/installation.properties
	   if [ ! -z "$PRODUCT_KEY" ]; then 	
	       preinstall_script=`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" "PREINSTALL_SCRIPT"`
	       postistall_script=`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" "POSTINSTALL_SCRIPT"`
		# Not sure what to do with these scripts
                # These interface scripts are no more used by any addon


                # Now add unpackaged component scripts
	        componentScripts=`getComponentScripts "$PRODUCT_KEY" "$OS_VERS"`
		echolog 'Adding component scripts: $2' "$componentScripts"
		#read pause
	        for each_script in `$CMD_ECHO "$componentScripts" | $CMD_AWK -F ':' '{for (i=1; i<=NF; i++) print $i}'`
	        do
	 	   script_path="./Solaris_${OS_VERS}/Basic/$each_script"
		   [ ! -f "$script_path" ] && continue
		   [ "$RUNTIME_PKG" = "DONE" ] && continue

                   # Make sure there is no duplicate entry for this script
                   # in the proto file for runtime package
                   # otherwise the pkgmk fails

		   /usr/bin/grep "${PRODUCT_SRCDIR}/" $PROTO_FILE | /usr/bin/grep "$script_path" 1> /dev/null 2>&1
		   [ $? -eq 0 ] && continue
                   tmp_pkg_dir="$TARGET_ARCHIVE_DIR/tmp_pkgdir/"
                   tmp_pkg_reloc="$ARCHIVE_TARGET_DIRNAME/disk1/image/${PRODUCT_SRCDIR}/"
                   basic_dir=`$CMD_DIRNAME "$script_path"`
                   os_dir=`$CMD_DIRNAME "$basic_dir"`
                   final_dir="${tmp_pkg_dir}${tmp_pkg_reloc}${basic_dir}"
                   mkdir -p $final_dir
                   $CMD_CP "$script_path" $final_dir

                   # Make entries into proto file for runtime package

                   $CMD_ECHO "d none ${tmp_pkg_reloc}" >> $PROTO_FILE
                   $CMD_ECHO "d none ${tmp_pkg_reloc}/${os_dir}" >> $PROTO_FILE
		   $CMD_ECHO "f none ${tmp_pkg_reloc}/$script_path 0555 root sys" >> $PROTO_FILE
	        done
	   fi
	fi
        cd $PWD
}


# One of the install-functions makes a list of all unpackaged 
# component scripts for selected products
# This function parses that list and gets a list of component script names
# $1: Product Key  $2:OS version
# Component script list may change from OS to OS
# echos the list at the end.
# Function call : somevar=`getComponentScripts <KEY> <OS>

getComponentScripts()
{
	PRODUCT_KEY="$1"
	OS_VERS="$2"

	scripts=""

	for each_list in `$CMD_ECHO "$COMPONENT_SCRIPT_LIST" | $CMD_AWK -F ' ' '{for (i=1; i<=NF; i++) print $i}'`
	do
        	product=`$CMD_ECHO "$each_list" | $CMD_CUT -d: -f1`
        	[ "$product" != "$1" ] && continue

        	os=`$CMD_ECHO "$each_list" | $CMD_CUT -d: -f2`
        	[ "$os" != "$2" ] && continue

        	tmp_script=`$CMD_ECHO "$each_list" | $CMD_CUT -d: -f3`
        	scripts="$scripts:$tmp_script"
	done
	
	$CMD_ECHO $scripts
}

# Function to archive 2X products
# Not supported any more

makeSymonArchive()
{
        PACKAGE_LIST="$1"
        OSVERS="$2"
        PRODUCT="$3"
        DISK="$4"
	[ "$DISK" = "disk99" ] && DISK="disk$LAST_CD"
        PWD=`$CMD_PWD/`
        cd "${SRC_DIR}/Addons/SunMC2.X/"
	DOTCDFILE="${IMAGETOOL_PATHPREFIX}../../../.CD"
        for each_package in `$CMD_ECHO "$PACKAGE_LIST" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
	do
		echolog 'Adding $2' "$each_package"
                OSDIR="./Solaris_${OSVERS}"
                #LOCATION=`$CMD_FIND ${OSDIR} -name $each_package`
                LOCATION="./${OSDIR}/${PRODUCT}/$each_package"
                TARFILE="$TARGET_DIR/$DISK/image/Addons/SunMC2.X/${PRODUCT}_Solaris_${OSVERS}.tar"
                if [ -f $TARFILE ]
                then
                        $CMD_TAR -uvf $TARFILE $LOCATION
                else
                        $CMD_TAR -cvf $TARFILE $LOCATION
                        $CMD_TAR -uvf $TARFILE $DOTCDFILE
                fi
        done
        cd $PWD
}

# Function to compress 2X archive
# not supported anymore

compressSymonArchive()
{
        PRODUCT="$1"
        PRODKEY="$2"
        DISK="$3"
	[ "$DISK" = "disk99" ] && DISK="disk$LAST_CD"
        PWD=`$CMD_PWD/`
        cd "$TARGET_ARCHIVE_DIR/$DISK/image/${PRODUCT}/"
	#read pause
        ARCHIVE_KEYS=`$API_QUERY_XML $UPGRADE_POLICY_FILE product=$PRODKEY archive key 2>/dev/null`
        index=`$CMD_ECHO "$ARCHIVE_KEYS" | $CMD_AWK -F ',' '{ print NF }'`

        for OSDIRS in `$CMD_ECHO "$SELECTED_OS" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
        do
                if [ -f ./${PRODKEY}_Solaris_$OSDIRS.tar ]; then
                        index=`$CMD_EXPR $index + 1`
                        SIZE=`$CMD_DU -ks ${PRODKEY}_Solaris_$OSDIRS.tar`
                        ARCHSIZE=`$CMD_ECHO $SIZE | $CMD_CUT -d" " -f1`

                        $API_INSERT_TAG $UPGRADE_POLICY_FILE product=$PRODKEY archive=$index 2>/dev/null
			$API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=$PRODKEY archive=$index path="$ARCHIVE_TARGET_DIRNAME/$DISK/image/Addons/SunMC2.X/${PRODKEY}_Solaris_$OSDIRS.tar.Z" 2>/dev/null
                        #echo "$ARCHSIZE"
                        $API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=$PRODKEY archive=$index tarsize=$ARCHSIZE 2>/dev/null

                        $CMD_COMPRESS -f ./${PRODKEY}_Solaris_$OSDIRS.tar
                        SIZE=`$CMD_DU -ks ${PRODKEY}_Solaris_$OSDIRS.tar.Z`
                        ARCHSIZE=`$CMD_ECHO $SIZE | $CMD_CUT -d" " -f1`
                        #echo "$ARCHSIZE"
                        $API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=$PRODKEY archive=$index size=$ARCHSIZE 2>/dev/null
                fi
        done
	cd $PWD
	#read pause
	splitArchives $PRODUCT $PRODKEY $DISK
}


# Function to compress the tarballs of a product
# This also updates the policy file with archive sub element
# Calls split archive at the end
# $1: Product dir under target image directory
# $2: Product Key
# $3: The disk number to refer to during policy file update

compressArchive()
{
        PRODUCT_SRCDIR=$1
	PRODKEY=$2
        DISK=$3
	[ "$DISK" = "disk99" ] && DISK="disk$LAST_CD"
	
        PWD=`$CMD_PWD`
        cd "$TARGET_ARCHIVE_DIR/$DISK/image/${PRODUCT_SRCDIR}/"
	#read pausea

	echolog 'Compressing product images...'

        # First of all, get the archive element keys that are
        # already present in the policy file
        # and then get the last index number
        # this happens because product archive creation
        # is revisited after change of disk
	
	ARCHIVE_KEYS=`$API_QUERY_XML $UPGRADE_POLICY_FILE product=$PRODKEY archive key 2>/dev/null`
	index=`$CMD_ECHO "$ARCHIVE_KEYS" | $CMD_AWK -F ',' '{ print NF }'`

        # First look for OS independent tarball

	if [ -f ./Common.tar ]; then
		index=`$CMD_EXPR $index + 1`

                # First calculate and record size before compression
                # this is useful when InstallClient calculates required
                # space for download and extraction of archives
		
		SIZE=`$CMD_DU -ks Common.tar` 
		ARCHSIZE=`$CMD_ECHO $SIZE | $CMD_CUT -d" " -f1`

		$API_INSERT_TAG $UPGRADE_POLICY_FILE product=$PRODKEY archive=$index 2>/dev/null
		$API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=$PRODKEY archive=$index path="$ARCHIVE_TARGET_DIRNAME/$DISK/image/${PRODUCT_SRCDIR}/Common.tar.Z" 2>/dev/null
		$API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=$PRODKEY archive=$index tarsize=$ARCHSIZE 2>/dev/null

		$CMD_COMPRESS -f ./Common.tar
		SIZE=`$CMD_DU -ks Common.tar.Z` 
		ARCHSIZE=`$CMD_ECHO $SIZE | $CMD_CUT -d" " -f1`

                # Now record the size after compression

		$API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=$PRODKEY archive=$index size=$ARCHSIZE 2>/dev/null
	fi

        # Now look for OS specific tarball

	for OSDIRS in `$CMD_ECHO "$SELECTED_OS" | $CMD_AWK -F ',' '{ for (i = 1; i<= NF; i++) print $i }'`
	do
		if [ -f ./Solaris_$OSDIRS.tar ]; then
			index=`$CMD_EXPR $index + 1`

                        # First calculate and record size before compression
                        # this is useful when InstallClient calculates required
                        # space for download and extraction of archives
			
			SIZE=`$CMD_DU -ks Solaris_$OSDIRS.tar` 
			ARCHSIZE=`$CMD_ECHO $SIZE | $CMD_CUT -d" " -f1`

			$API_INSERT_TAG $UPGRADE_POLICY_FILE product=$PRODKEY archive=$index 2>/dev/null
			$API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=$PRODKEY archive=$index path="$ARCHIVE_TARGET_DIRNAME/$DISK/image/${PRODUCT_SRCDIR}/Solaris_$OSDIRS.tar.Z" 2>/dev/null
			#echo "$ARCHSIZE"
			$API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=$PRODKEY archive=$index tarsize=$ARCHSIZE 2>/dev/null

			$CMD_COMPRESS -f ./Solaris_$OSDIRS.tar
			SIZE=`$CMD_DU -ks Solaris_$OSDIRS.tar.Z` 
			ARCHSIZE=`$CMD_ECHO $SIZE | $CMD_CUT -d" " -f1`

                        # Now record the size after compression

			$API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=$PRODKEY archive=$index size=$ARCHSIZE 2>/dev/null
		fi
	done
	cd $PWD
	splitArchives $PRODUCT_SRCDIR $PRODKEY $DISK
}


# A function to check whether the split size given as an argument
# is valid number
# Then check whether it is within the range 0.5 MB to 10 MB
# Default is 1MB

check_split_size()
{

	$CMD_EXPR $SPLIT_SIZE + 1 1> /dev/null 2>&1
	retcode=$?
	if [ $retcode -ne 0 ] ; then
		echolog 'Split size is not a valid number, default will be used.'
		SPLIT_SIZE=$DEFAULT_SPLIT_SIZE
	fi

      	if [ $SPLIT_SIZE -lt 512 -o $SPLIT_SIZE -gt 10240 ] ; then
	 	echolog 'Split size is not within valid range, default will be used.'
	 	SPLIT_SIZE=$DEFAULT_SPLIT_SIZE
      	fi
}


# This function splits the compressed tarballs into 
# sub archives of size = $SPLIT_SIZE
# Also updates the sub-archive sub element of archive element
# Default is 1 MB
# $1: Product dir under target image dir
# $2: Product Key
# $3: Disk no reference for updating policy file

splitArchives()
{
        PRODUCT_SRCDIR=$1
        PRODKEY=$2
        DISK=$3

        PWD=`$CMD_PWD`
        cd "$TARGET_ARCHIVE_DIR/$DISK/image/${PRODUCT_SRCDIR}/"

	[ $SPLIT_SIZE -eq 0 ] && SPLIT_SIZE=$DEFAULT_SPLIT_SIZE
	# Command line option was not used.

        index=0

        # First of all, get the sub-archive element keys that are
        # already present in the policy file
        # and then get the last index number
        # this happens because product archive creation
        # is revisited after change of disk

        ARCHIVE_FILES=`$API_QUERY_XML $UPGRADE_POLICY_FILE product=$PRODKEY archive path 2>/dev/null`

	for each_path in `$CMD_ECHO "$ARCHIVE_FILES" | $CMD_AWK -F ',' '{ for(i = 1; i <= NF ; i++) print $i }'` 
	do
            index=`$CMD_EXPR $index + 1`
	    $CMD_ECHO $each_path | $CMD_GREP $DISK >/dev/null 2>&1
	    [ $? -eq 1 ] && continue

            ARCHIVE_FILE=`$CMD_BASENAME $each_path`
            if [ -f $ARCHIVE_FILE ]; then
                SIZE=`$CMD_DU -ks $ARCHIVE_FILE`
                ARCHSIZE=`$CMD_ECHO $SIZE | $CMD_CUT -d" " -f1`
                if [ $ARCHSIZE -lt 1024 ]; then
               	    $API_INSERT_TAG $UPGRADE_POLICY_FILE product=$PRODKEY archive=$index sub-archive=1 2>/dev/null
                    $API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=$PRODKEY archive=$index sub-archive=1 path="$ARCHIVE_TARGET_DIRNAME/$DISK/image/${PRODUCT_SRCDIR}/$ARCHIVE_FILE" 2>/dev/null
                    $API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=$PRODKEY archive=$index sub-archive=1 size=$ARCHSIZE 2>/dev/null

		    continue
		fi

		#echolog 'Splitting the image : $2' "$ARCHIVE_FILE"

                $CMD_SPLIT -b ${SPLIT_SIZE}k $ARCHIVE_FILE $ARCHIVE_FILE-
                $CMD_RM -rf $ARCHIVE_FILE
                SUB_ARCHIVES=`$CMD_LS -1 $ARCHIVE_FILE*`

                sub_index=0

                for each_subarchive in `$CMD_ECHO "$SUB_ARCHIVES" | $CMD_AWK -F ',' '{ for(i = 1; i <= NF ; i++) print $i }'`
                do
                    sub_index=`$CMD_EXPR $sub_index + 1`
                    SIZE=`$CMD_DU -ks $each_subarchive`
                    SUBARCHSIZE=`$CMD_ECHO $SIZE | $CMD_CUT -d" " -f1`
                    $API_INSERT_TAG $UPGRADE_POLICY_FILE product=$PRODKEY archive=$index sub-archive=$sub_index 2>/dev/null
                    $API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=$PRODKEY archive=$index sub-archive=$sub_index path="$ARCHIVE_TARGET_DIRNAME/$DISK/image/${PRODUCT_SRCDIR}/$each_subarchive" 2>/dev/null
                    $API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=$PRODKEY archive=$index sub-archive=$sub_index size=$SUBARCHSIZE 2>/dev/null
                done
	    fi
	done
	cd $PWD
}


# This makes the basic directory structure under target image dir
# $1: Product subdir name
# if dir has Addons, it creates under disk2 as well.

makeDirectories()
{
        PRODUCT=$1
        PROD_TYPE=`$CMD_EXPR $PRODUCT : '\(.....\).*'`

        mkdir -p "$TARGET_ARCHIVE_DIR/disk1/image/${PRODUCT}"
	mkdir -p "$TARGET_ARCHIVE_DIR/disk1/image/Addons/SunMC2.X"
        #echo "Creating $TARGET_ARCHIVE_DIR/disk1/image/${PRODUCT}"
	if [ "$PROD_TYPE" = "Addon" ]
        then
                mkdir -p "$TARGET_ARCHIVE_DIR/disk2/image/${PRODUCT}"
		mkdir -p "$TARGET_ARCHIVE_DIR/disk2/image/Addons/SunMC2.X"
        fi
}


# Makes a runtime package of all unpackaged files under source dir
# this includes the install scripts and support files
# all component scripts of the product
# this ensures that every archive contains Solaris package 
# This also includes InstallClient binary and libxml
# ensuring everything has checksums and leaves very less security holes
# 
# This makes a tarfile of this package with a fixed name sbin.tar
# Then compressed .Z file
# A decesion was taken not to split this archive
# A construct is kept not to go through the compression logic
# All this to avoid overheads for initial agent-update.bin
# Since this contains the Client itself, everything is kept straight and simple

make_runtime_package()
{
        PWD=`$CMD_PWD`
	cd $TARGET_ARCHIVE_DIR/tmp_pkgdir/
	PKGINFO_FILE="$TARGET_ARCHIVE_DIR/tmp_pkgdir/pkginfo"
	COPYRIGHT_FILE="$TARGET_ARCHIVE_DIR/tmp_pkgdir/copyright"
	$CMD_TOUCH $PKGINFO_FILE
	$CMD_TOUCH $COPYRIGHT_FILE
	YEAR=`$CMD_DATE +%Y`

	echolog 'Packaging installation interface scripts...'

        # this is for GUI
	put_var_in_cfgfile "${PROGRESS_FILE}" "PACKAGE" "Installation interface scripts" "="
	put_var_in_cfgfile "${PROGRESS_FILE}" "PRODUCT" "Packaging" "="

	$CMD_ECHO "Copyright $YEAR Sun Microsystems, Inc. All rights reserved." > $COPYRIGHT_FILE
	$CMD_PKGINFO -qi SUNWescom 1>/dev/null 2>&1
	if [ $? -ne 0 ]; then
	    echolog 'Sun Management Center not installed properly'
            releaseImageToolLock
	    exit 1
	else
	    PKGPARAMS=`$CMD_PKGPARAM -v SUNWescom | $CMD_CUT -d= -f1`
	fi

	for each_param in $PKGPARAMS
	do
	    case $each_param in 
	    PKG) 
		$CMD_ECHO "$each_param=SUNWessmu" >> $PKGINFO_FILE
		;;
	    NAME) 
		$CMD_ECHO "$each_param=\"Dynamic Agent Update runtime package\"" >> $PKGINFO_FILE
		;;
	    DESC)
		$CMD_ECHO "$each_param=\"This package contains installation interface scripts of products\"" >> $PKGINFO_FILE
		;;
	    PKGINST)
		$CMD_ECHO "$each_param=SUNWessmu" >> $PKGINFO_FILE
		;;
	    CATEGORY)
		$CMD_ECHO "$each_param=SunMCsu" >> $PKGINFO_FILE
		;;
	    *PATCH*)
            	;;
            *)
		PARAM_VALUE=`$CMD_PKGPARAM SUNWescom $each_param 2>/dev/null`
		$CMD_ECHO "$each_param=\"$PARAM_VALUE\"" >> $PKGINFO_FILE
		;;
	    esac
	done

	cd $TARGET_ARCHIVE_DIR/tmp_pkgdir
	$CMD_PKGMK -o -d . -r . 1>/dev/null 2>&1
	if [ $? -ne 0 ]; then
		echolog 'Failed to package installation interface scripts'
                releaseImageToolLock
		exit 1
	fi

	cd $TARGET_ARCHIVE_DIR
	TARFILE="$TARGET_ARCHIVE_DIR/sbin.tar"
	$CMD_TAR -cvf $TARFILE ./tmp_pkgdir/SUNWessmu

        $API_INSERT_TAG $UPGRADE_POLICY_FILE products=SunMC installer=es-inst 2>/dev/null

	$API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE installer=es-inst archive-type="tar.Z" 2>/dev/null

	$API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE installer=es-inst command="$ARCHIVE_TARGET_DIRNAME/disk1/sbin/es-inst" 2>/dev/null

	$API_INSERT_TAG $UPGRADE_POLICY_FILE installer=es-inst archive=1 2>/dev/null
	$API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE installer=es-inst archive=1 path="$ARCHIVE_TARGET_DIRNAME/sbin.tar.Z" 2>/dev/null

        SIZE=`$CMD_DU -ks $TARFILE`
        ARCHSIZE=`$CMD_ECHO $SIZE | $CMD_CUT -d" " -f1`

	$API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE installer=es-inst archive=1 tarsize=$ARCHSIZE 2>/dev/null
	$CMD_COMPRESS -f $TARFILE

	
	[ $SPLIT_SIZE -eq 0 ] && SPLIT_SIZE=$DEFAULT_SPLIT_SIZE
	# Command line option was not used.
        
        ARCHIVE_FILE=`$CMD_BASENAME "$TARFILE.Z"`
        if [ -f $ARCHIVE_FILE ]; then
        	SIZE=`$CMD_DU -ks $ARCHIVE_FILE`
        	ARCHSIZE=`$CMD_ECHO $SIZE | $CMD_CUT -d" " -f1`
		$API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE installer=es-inst archive=1 size=$ARCHSIZE 2>/dev/null
                if [ $ARCHSIZE -lt 1024 ]; then
                        $API_INSERT_TAG $UPGRADE_POLICY_FILE installer=es-inst archive=1 sub-archive=1 2>/dev/null
                        $API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE installer=es-inst archive=1 sub-archive=1 path="$ARCHIVE_TARGET_DIRNAME/sbin.tar.Z" 2>/dev/null
                        $API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE installer=es-inst archive=1 sub-archive=1 size=$ARCHSIZE 2>/dev/null
		else

		if [ "DONT_SPLIT" = "SPLIT" ]; then  # IMP : this is required

                    $CMD_SPLIT -b ${SPLIT_SIZE}k $ARCHIVE_FILE $ARCHIVE_FILE-
                    $CMD_RM -rf $ARCHIVE_FILE
                    SUB_ARCHIVES=`$CMD_LS $ARCHIVE_FILE*`
                    sub_index=0

                    for each_subarchive in `$CMD_ECHO "$SUB_ARCHIVES" | $CMD_AWK -F ',' '{ for(i = 1; i <= NF ; i++) print $i }'`
                    do
                	sub_index=`$CMD_EXPR $sub_index + 1`
                        SIZE=`$CMD_DU -ks $each_subarchive`
                        SUBARCHSIZE=`$CMD_ECHO $SIZE | $CMD_CUT -d" " -f1`
                        $API_INSERT_TAG $UPGRADE_POLICY_FILE installer=es-inst archive=1 sub-archive=$sub_index 2>/dev/null
                        $API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE installer=es-inst archive=1 sub-archive=$sub_index path="$ARCHIVE_TARGET_DIRNAME/$each_subarchive" 2>/dev/null
                        $API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE installer=es-inst archive=1 sub-archive=$sub_index size=$SUBARCHSIZE 2>/dev/null
                    done
		fi

		fi 
		#echolog "Not splitting the image"
	else
		echolog "Image file not found"
	fi
	$CMD_RM -rf $TARGET_ARCHIVE_DIR/tmp_pkgdir
	RUNTIME_PKG="DONE"
        cd $PWD
}


# This function copies InstallClient binaries from installed place 
# to target image dir and updates the runtime package prototype file
# Also copies libxml from given source dir
# to target image dir and updates the protofile

update_proto_for_client()
{
        sparc_installclient_src="$API_DIR/../sparc-sun-solaris/InstallClient"
        x86_installclient_src="$API_DIR/../i386-sun-solaris/InstallClient"

	[ ! -f "$sparc_installclient_src" ] && echolog "Cannot locate sparc InstallClient source.." && releaseImageToolLock && exit 1
	[ ! -f "$x86_installclient_src" ] && echolog "Cannot locate i386 InstallClient source.." && releaseImageToolLock && exit 1
	
	PWD=`$CMD_PWD`
	cd $TARGET_ARCHIVE_DIR/tmp_pkgdir/$ARCHIVE_TARGET_DIRNAME
        $CMD_MKDIR -p bin/sparc-sun-solaris
        $CMD_MKDIR -p bin/i386-sun-solaris

	IC_SPARC_BINARY=`$CMD_BASENAME "$sparc_installclient_src"`
	IC_X86_BINARY=`$CMD_BASENAME "$x86_installclient_src"`

	$CMD_CP "$sparc_installclient_src" ./$IC_SPARC_BINARY  
        # must retain the old copy so that 3.5 agent-update.bin works
	$CMD_CP "$sparc_installclient_src" ./bin/sparc-sun-solaris/$IC_SPARC_BINARY
	$CMD_CP "$x86_installclient_src" ./bin/i386-sun-solaris/$IC_X86_BINARY

	$CMD_ECHO "f none $ARCHIVE_TARGET_DIRNAME/InstallClient" >> $PROTO_FILE
        # must retain the old copy so that 3.5 agent-update.bin works
	$CMD_ECHO "f none $ARCHIVE_TARGET_DIRNAME/bin/sparc-sun-solaris/${IC_SPARC_BINARY}" >> $PROTO_FILE
	$CMD_ECHO "f none $ARCHIVE_TARGET_DIRNAME/bin/i386-sun-solaris/${IC_X86_BINARY}" >> $PROTO_FILE
	
	$CMD_MKDIR -p XML/APIs
	$CMD_MKDIR -p lib/sparc-sun-solaris
	$CMD_MKDIR -p lib/i386-sun-solaris

	[ -f "$LIB_DIR/libxml2.so" ] && cp $LIB_DIR/libxml2.so ./XML/libxml2.so
        [ -f "$LIB_DIR/libxml2.so.2" ] && cp $LIB_DIR/libxml2.so.2 ./XML/libxml2.so.2
        # New structure for PU1 sparc libxml
	[ -f "$LIB_DIR/libxml2.so" ] && cp $LIB_DIR/libxml2.so ./lib/sparc-sun-solaris/libxml2.so
        [ -f "$LIB_DIR/libxml2.so.2" ] && cp $LIB_DIR/libxml2.so.2 ./lib/sparc-sun-solaris/libxml2.so.2
        # Copy the x86 version of the libxml
	[ -f "$LIB_DIR/../i386-sun-solaris/libxml2.so" ] && cp $LIB_DIR/../i386-sun-solaris/libxml2.so ./lib/i386-sun-solaris/libxml2.so
        [ -f "$LIB_DIR/../i386-sun-solaris/libxml2.so.2" ] && cp $LIB_DIR/../i386-sun-solaris/libxml2.so.2 ./lib/i386-sun-solaris/libxml2.so.2


	XML_FILES=`$CMD_FIND XML 2>/dev/null`
	for each_entry in $XML_FILES
        do
            TMP_ENTRY="$ARCHIVE_TARGET_DIRNAME/$each_entry"
            if [ -d "$each_entry" ]; then
                $CMD_ECHO "d none $TMP_ENTRY" >> $PROTO_FILE
            else
                $CMD_ECHO "f none $TMP_ENTRY 0555 root sys" >> $PROTO_FILE
            fi
        done

	XML_FILES=`$CMD_FIND lib 2>/dev/null`
	for each_entry in $XML_FILES
        do
            TMP_ENTRY="$ARCHIVE_TARGET_DIRNAME/$each_entry"
            if [ -d "$each_entry" ]; then
                $CMD_ECHO "d none $TMP_ENTRY" >> $PROTO_FILE
            else
                $CMD_ECHO "f none $TMP_ENTRY 0555 root sys" >> $PROTO_FILE
            fi
        done

	cd $PWD
}

# A function extracting source directory information 
# from SELECTED_LIST variable
# The function creates directory structure for 
# archvies of selected Addons.
# $1 SELECTED_LIST.

createAddonDirectories()
{
    UNIQUE_SELECTED_KEYS="" 	# This is IMP don't delete
    for OS in `$CMD_ECHO "$SELECTED_OS" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
    do
	resetSourceList $OS
	resetSelectedKeys $OS

	for addon_product_key in `$CMD_ECHO "$SELECTED_KEYS" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
    	do
		[ "$addon_product_key" = "PRODUCT.PE" ] && continue

		isSelectedKeyProcessed $addon_product_key
		[ $? -eq 0 ] && continue

		addon_srcdir=`getProductAttr "$SOURCE_LIST" "$addon_product_key" "SOURCE_DIR"`
		addon_version=`getProductAttr "$SOURCE_LIST" "$addon_product_key" "VERSION"`
	#echo "Addon source : $addon_srcdir"
	#echo "Addon version : $addon_version"
	if [ "$addon_version" = "3X" ]; then
		makeDirectories "Addons/${addon_srcdir}"
		copySetupResponseFile $addon_product_key "Addons/${addon_srcdir}"
	fi
	done
    done
}

# When a response file is created, the addon subdir is not available
# This function copies response file of product to the subdir
# Then updates the attribute into the policy file

copySetupResponseFile()
{
	ADDON_KEY="$1"
	ADDON_DIR="$TARGET_ARCHIVE_DIR/disk1/image/$2"
	for each_string in `$CMD_ECHO $RESPONSE_FILE_LIST | $CMD_AWK -F '#' '{ for (i = 1; i <= NF; i++) print $i }'`
	do
	    addon_key=`$CMD_ECHO "${each_string}" | $CMD_AWK -F ':' '{ print $1 }'`
	    if [ "$addon_key" = "$ADDON_KEY" ]; then
		response_file=`$CMD_ECHO "${each_string}" | $CMD_AWK -F ':' '{ print $2 }'`
		RESPONSE_FILE_ATTR=`$CMD_BASENAME "$response_file"`
		if [ -z "$response_file" ]; then
		    addon_name=`getProductAttr "$SOURCE_LIST" "$addon_product_key" "NAME"`
		    echolog 'Setup will not be carried out for $2' "$addon_name"
		else
		    $CMD_CP -f $response_file $ADDON_DIR
		    $CMD_RM -f $response_file
		fi
	        $API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=$addon_key setup-response=$ARCHIVE_TARGET_DIRNAME/disk1/image/$2/$RESPONSE_FILE_ATTR 2>/dev/null
	    fi
	done
}

# A high level function archiving all agent packages of selected Addons
# This creates a list of packages to be added into the tarfile 
# Also gets the CD number on which these packages reside
# passes these values to makeArchive and then splitArchive functions.

archiveAddons()
{
	PRODUCT_CD="$1"
	for ARCHIVE_OSVERS in `$CMD_ECHO "$SELECTED_OS" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
	do
            # This is for GUI
	    put_var_in_cfgfile "${ARCHIVE_PROGRESS_FILE}" "OSVERS" "$ARCHIVE_OSVERS" "="
	    put_var_in_cfgfile "${ARCHIVE_PROGRESS_FILE}" "PROCESS" "Archiving" "="
		resetSourceList $ARCHIVE_OSVERS
		resetSortedComponentsList $ARCHIVE_OSVERS
		echo "-----------------------------------------------"
		ADDON_PROD_LIST="$SORTED_INSTALL_COMPONENTS_LIST"

		for each_product_string in `$CMD_ECHO "$ADDON_PROD_LIST" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
		do
			addon_product_key=`$CMD_ECHO "$each_product_string" | $CMD_AWK -F ':' '{ print $4 }'` 
			[ "$addon_product_key" = "PRODUCT.PE" ] && continue
			addon_source_dir=`getProductAttr "$SOURCE_LIST" "$addon_product_key" "SOURCE_DIR"`
			addon_name=`getProductAttr "$SOURCE_LIST" "$addon_product_key" "NAME"`
			addon_packages=`$CMD_ECHO "$each_product_string" | $CMD_AWK -F ':' '{ print $2 }'`
			addon_component=`$CMD_ECHO "$each_product_string" | $CMD_AWK -F ':' '{ print $1 }'`
			addon_cd=`$CMD_ECHO "$each_product_string" | $CMD_AWK -F ':' '{ print $3 }'`
			if [ $PRODUCT_CD -ne 1 ]; then
				[ "$addon_cd" != "$PRODUCT_CD" ] && continue
			fi
		echolog 'packages for product $2 : $3' "$addon_name" "$addon_packages"

		[ -z "$addon_packages" ] && continue

		if [ "$addon_component" = "DEFAULT" ]; then
			# Handle 2.X addons
			#echo "Create 2.X images"
			makeSymonArchive $addon_packages $ARCHIVE_OSVERS $addon_product_key "disk${PRODUCT_CD}"
		else
		makeArchive $addon_packages $ARCHIVE_OSVERS "Addons/$addon_source_dir" "disk${PRODUCT_CD}" "$addon_product_key"
		fi
		done
	done


    UNIQUE_SELECTED_KEYS="" 	# This is IMP don't delete
    for OS in `$CMD_ECHO "$SELECTED_OS" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
    do
	resetSourceList $OS
	resetSelectedKeys $OS

	for addon_product_key in `$CMD_ECHO "$SELECTED_KEYS" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
	do
		[ "$addon_product_key" = "PRODUCT.PE" ] && continue

		isSelectedKeyProcessed $addon_product_key
		[ $? -eq 0 ] && continue

		addon_product_name=`getProductAttr "$SOURCE_LIST" "$addon_product_key" "NAME"`
		addon_source_dir=`getProductAttr "$SOURCE_LIST" "$addon_product_key" "SOURCE_DIR"`
		addon_version=`getProductAttr "$SOURCE_LIST" "$addon_product_key" "VERSION"`
		if [ "$addon_version" = "2X" ]; then
                        # Handle 2.X addons
                        #echo "Create 2.X images"
			compressSymonArchive "Addons/SunMC2.X" $addon_product_key "disk${PRODUCT_CD}"
                else
			compressArchive "Addons/$addon_source_dir" $addon_product_key "disk${PRODUCT_CD}"
		fi
	done
    done
}


# This function updates the install response file with 
# tags associated to each CD in the source image

updateSourceDirectories()
{
	for each_cd in $ALL_CDS
	do
	    case $each_cd in
            	1) saveAutoConfig "SOURCE_DIRECTORY" "/tmp/agentupdate/$ARCHIVE_TARGET_DIRNAME/disk${each_cd}/image"
			;;
            	99) saveAutoConfig "CORE_DISK${LAST_CD}" "/tmp/agentupdate/$ARCHIVE_TARGET_DIRNAME/disk${LAST_CD}/image"
			;;
		*) saveAutoConfig "CORE_DISK${each_cd}" "/tmp/agentupdate/$ARCHIVE_TARGET_DIRNAME/disk${each_cd}/image"
			;;
	    esac
	done
}

# Gets the image name and creates archive target directory

getArchiveTargetDirectory() {
        echolog ''
        echolog 'Product images will be created under: $2' "$AGENT_UPDATE_DIR"
            while [ 1 ] ; do
        	echolog ''
                get_input_from_user 'Enter image name : '
                [ -z "$answer" ] && continue
		CHECK_DIR=`$CMD_DIRNAME $answer`
		if [ "$CHECK_DIR" != "." ]; then
			echolog "Invalid image name!"	
			echolog "Enter another name"
			continue
		fi
                
                $CMD_ECHO "$answer" | $CMD_GREP -e "^[a-zA-Z][-a-zA-Z0-9_]*$" > /dev/null 
                if [ $? -eq 1 ]; then
			echolog "Invalid image name!"	
			echolog "Enter another name"
			continue
                fi
                TARGET_DIR="$AGENT_UPDATE_DIR/$answer"
		if [ -d $TARGET_DIR ]; then
			if [ -f $TARGET_DIR/upgrade-policy.xml ]; then
				echolog "Image with this name already exists"
				echolog "Enter another name"
				continue
			fi
		fi
                ARCHIVE_TARGET_DIRNAME="$answer"
		#update_protofile

                #ARCHIVE_TARGET_DIR=`getPathName "$ORIGINAL_TARGET_DIR"`
                #checkTargetDirectory
		$CMD_MKDIR -p $TARGET_DIR
                break
            done
        TARGET_DIR_WITHOUT_RELOC="$ORIGINAL_TARGET_DIR"
        TARGET_DIR_WITH_RELOC="$TARGET_DIR"
}

# Creates the prototype file for runtime package
# and updates it with basic entries

update_protofile()
{
        mkdir -p $TARGET_DIR/tmp_pkgdir/$ARCHIVE_TARGET_DIRNAME
        PROTO_FILE=$TARGET_DIR/tmp_pkgdir/prototype
	echologverbose '$2' "$PROTO_FILE"
        $CMD_ECHO "i pkginfo" > $PROTO_FILE
        $CMD_ECHO "i copyright" >> $PROTO_FILE
        $CMD_ECHO "!default 0755 root sys" >> $PROTO_FILE

        $CMD_ECHO "d none $ARCHIVE_TARGET_DIRNAME" >> $PROTO_FILE
        $CMD_ECHO "d none $ARCHIVE_TARGET_DIRNAME/disk1" >> $PROTO_FILE
        $CMD_ECHO "d none $ARCHIVE_TARGET_DIRNAME/disk1/image" >> $PROTO_FILE

	DISKDIR=`$CMD_DIRNAME ${SRC_DIR}`
	if [ "$SOURCE_IMAGE" != "PATCH_ONLY" -a -d "$DISKDIR/sbin" ]; then
	    update_proto_for_install_scripts
	fi
}

# Copies unpackaged install script file or a binary in the disk1/sbin directory
# To the target image directory
# Updates the protofile with entries associated to each file

update_proto_for_install_scripts()
{
        PWD=`$CMD_PWD`
        DISKDIR=`$CMD_DIRNAME ${SRC_DIR}`
	cd $DISKDIR
	$CMD_MKDIR -p "$TARGET_DIR/tmp_pkgdir/$ARCHIVE_TARGET_DIRNAME/disk1"
	$CMD_MKDIR -p "$TARGET_DIR/tmp_pkgdir/$ARCHIVE_TARGET_DIRNAME/disk1/image/PE"
        cp -r ./sbin "$TARGET_DIR/tmp_pkgdir/$ARCHIVE_TARGET_DIRNAME/disk1/sbin" 2>/dev/null
        cp -r ./lib "$TARGET_DIR/tmp_pkgdir/$ARCHIVE_TARGET_DIRNAME/disk1/lib" 2>/dev/null
        if [ -f "./image/PE/.locales" ]; then 
           cp ./image/PE/.locales ${TARGET_DIR}/tmp_pkgdir/${ARCHIVE_TARGET_DIRNAME}/disk1/image/PE
        fi
	cd "$TARGET_DIR/tmp_pkgdir/$ARCHIVE_TARGET_DIRNAME/disk1"
	if [ -d ./sbin ]; then
	    $CMD_ECHO "d none $ARCHIVE_TARGET_DIRNAME/disk1/sbin" >> $PROTO_FILE
	fi
	if [ -d ./lib ]; then
		$CMD_ECHO "d none $ARCHIVE_TARGET_DIRNAME/disk1/lib" >> $PROTO_FILE
	fi

	INSTALL_FILES=`$CMD_FIND sbin 2>/dev/null`
	for each_entry in $INSTALL_FILES
	do
	    TMP_ENTRY="$ARCHIVE_TARGET_DIRNAME/disk1/$each_entry"
	    if [ -d "$each_entry" ]; then 
		$CMD_ECHO "d none $TMP_ENTRY" >> $PROTO_FILE
	    else
		$CMD_ECHO "f none $TMP_ENTRY 0555 root sys" >> $PROTO_FILE
	    fi
	done

	LIB_FILES=`$CMD_FIND lib 2>/dev/null`
	for each_entry in $LIB_FILES
	do
	    TMP_ENTRY="$ARCHIVE_TARGET_DIRNAME/disk1/$each_entry"
	    if [ -d "$each_entry" ]; then 
		$CMD_ECHO "d none $TMP_ENTRY" >> $PROTO_FILE
	    else
		$CMD_ECHO "f none $TMP_ENTRY 0555 root sys" >> $PROTO_FILE
	    fi
	done

        LOCALE_ENTRY="image/PE/.locales"
        TMP_ENTRY="${ARCHIVE_TARGET_DIRNAME}/disk1/${LOCALE_ENTRY}"
	[ -f "$LOCALE_ENTRY" ] && $CMD_ECHO "f none $TMP_ENTRY 0555 root sys" >> $PROTO_FILE
	
	cd $PWD
}

# Gets the source directory for a patch only image creation.

getPatchOnlySource () {
    get_input_from_user 'Enter a patch-only source directory:'
    SRC_DIR=`getPathName $answer`
    while [ 1 -eq 1 ]
    do
        checkPatchOnlyDirectory
	if [ $? -eq 1 ]; then
	    SOURCE_IMAGE="PATCH_ONLY"
            echolog ''
            echolog 'Installation files source directory: $2' "$SRC_DIR"
            break
        else
            $CMD_ECHO "  \c"
            echolog '  Invalid source directory: $2' "$SRC_DIR"
            echolog ''
            echolog 'The directory is not a valid patch-only directory'
            get_input_from_user 'Enter a valid patch-only source directory:'
            SRC_DIR=`getPathName $answer`
        fi
    done
}


# Gets the target directory on remote agents

getRemoteTargetDirectory() {
    echolog ''
        temp_dir="/opt"
        get_input_from_user 'Enter the full path of the directory in which to install the Sun Management Center update on each host machine \\(default: $2\\):' "$temp_dir"
	echolog ''
            if [ -z "$answer" ]; then
                REMOTE_TARGET_DIR="$temp_dir"
            else
                REMOTE_TARGET_DIR="$answer"
            fi
        echo ' '
        multiline_echolog 'Note: If the Sun Management Center 3.5 Update 1 agent is already installed \non the host machine, the original agent is updated at the location where \nit is currently installed.'
        sleep 2      # a short pause
}


###################################################################

# This section defines some key functions in the code
# The image tool needs to do all the processings for
# multiple OS versions, considering that the target
# agent systems could be of any OS 

# So every variable having info about a product, that is processed 
# during the image creation has 4 copies, 1 for each OS
# These functions switch in correct variables when a particular 
# OS is being processed. This happens with "reset" version of the function

# As soon as the processing is done, the "set" version of the
# functions are used to store them back for future reference

###################################################################

### BEGIN SECTION #################################################

setSourceList()
{
	case $1 in
            2.6)   SOURCE_LIST_6="$SOURCE_LIST"	;;
            7)     SOURCE_LIST_7="$SOURCE_LIST"	;;
            8)     SOURCE_LIST_8="$SOURCE_LIST"	;;
            9)     SOURCE_LIST_9="$SOURCE_LIST"	;;
            10)     SOURCE_LIST_10="$SOURCE_LIST"	;;
	esac
}

resetSourceList()
{
        case $1 in
            2.6)   SOURCE_LIST="$SOURCE_LIST_6"   ;;
            7)     SOURCE_LIST="$SOURCE_LIST_7"   ;;
            8)     SOURCE_LIST="$SOURCE_LIST_8"  ;;
            9)     SOURCE_LIST="$SOURCE_LIST_9"  ;;
            10)     SOURCE_LIST="$SOURCE_LIST_10"  ;;
        esac
}

setAvailableKeys()
{
	case $1 in
            2.6)   AVAILABLE_KEYS_6="$AVAILABLE_KEYS"	;;
            7) 	   AVAILABLE_KEYS_7="$AVAILABLE_KEYS"	;;
            8)     AVAILABLE_KEYS_8="$AVAILABLE_KEYS"	;;
            9)     AVAILABLE_KEYS_9="$AVAILABLE_KEYS"	;;
            10)     AVAILABLE_KEYS_10="$AVAILABLE_KEYS"	;;
	esac
}

resetAvailableKeys()
{
	case $1 in
            2.6)   AVAILABLE_KEYS="$AVAILABLE_KEYS_6"	;;
            7)     AVAILABLE_KEYS="$AVAILABLE_KEYS_7"	;;
            8)     AVAILABLE_KEYS="$AVAILABLE_KEYS_8"	;;
            9)     AVAILABLE_KEYS="$AVAILABLE_KEYS_9"	;;
            10)     AVAILABLE_KEYS="$AVAILABLE_KEYS_10"	;;
	esac
}

setSelectedKeys()
{
	case $1 in
            2.6)   SELECTED_KEYS_6="$SELECTED_KEYS"	;;
            7) 	   SELECTED_KEYS_7="$SELECTED_KEYS"	;;
            8)     SELECTED_KEYS_8="$SELECTED_KEYS"	;;
            9)     SELECTED_KEYS_9="$SELECTED_KEYS"	;;
            10)     SELECTED_KEYS_10="$SELECTED_KEYS"	;;
	esac
}

resetSelectedKeys()
{
        case $1 in
            2.6)   SELECTED_KEYS="$SELECTED_KEYS_6"       ;;
            7)     SELECTED_KEYS="$SELECTED_KEYS_7"       ;;
            8)     SELECTED_KEYS="$SELECTED_KEYS_8"       ;;
            9)     SELECTED_KEYS="$SELECTED_KEYS_9"       ;;
            10)     SELECTED_KEYS="$SELECTED_KEYS_10"       ;;
        esac
}

setArchiveKeys()
{
	case $1 in
            2.6)   ARCHIVE_KEYS_6="$INSTALL_KEYS"	;;
            7) 	   ARCHIVE_KEYS_7="$INSTALL_KEYS"	;;
            8)     ARCHIVE_KEYS_8="$INSTALL_KEYS"	;;
            9)     ARCHIVE_KEYS_9="$INSTALL_KEYS"	;;
            10)     ARCHIVE_KEYS_10="$INSTALL_KEYS"	;;
	esac
}

resetInstallKeys()
{
	case $1 in
            2.6)   INSTALL_KEYS="$ARCHIVE_KEYS_6"	;;
            7) 	   INSTALL_KEYS="$ARCHIVE_KEYS_7"	;;
            8)     INSTALL_KEYS="$ARCHIVE_KEYS_8" 	;;
            9)     INSTALL_KEYS="$ARCHIVE_KEYS_9" 	;;
            10)     INSTALL_KEYS="$ARCHIVE_KEYS_10" 	;;
	esac
}

setOptionalComponents()
{
	case $1 in
            2.6)   ALL_OPTIONAL_COMPONENTS_6="$ALL_OPTIONAL_COMPONENTS"	;;
            7)     ALL_OPTIONAL_COMPONENTS_7="$ALL_OPTIONAL_COMPONENTS"	;;
            8)     ALL_OPTIONAL_COMPONENTS_8="$ALL_OPTIONAL_COMPONENTS"	;;
            9)     ALL_OPTIONAL_COMPONENTS_9="$ALL_OPTIONAL_COMPONENTS"	;;
            10)     ALL_OPTIONAL_COMPONENTS_10="$ALL_OPTIONAL_COMPONENTS" ;;
	esac
}

resetOptionalComponents()
{
	case $1 in
            2.6)   ALL_OPTIONAL_COMPONENTS="$ALL_OPTIONAL_COMPONENTS_6"	;;
            7)     ALL_OPTIONAL_COMPONENTS="$ALL_OPTIONAL_COMPONENTS_7"	;;
            8)     ALL_OPTIONAL_COMPONENTS="$ALL_OPTIONAL_COMPONENTS_8"	;;
            9)     ALL_OPTIONAL_COMPONENTS="$ALL_OPTIONAL_COMPONENTS_9"	;;
            10)     ALL_OPTIONAL_COMPONENTS="$ALL_OPTIONAL_COMPONENTS_10" ;;
	esac
}

setComponentFiltersList()
{
	case $1 in
            2.6)   COMPONENT_FILTERS_LIST_6="$COMPONENT_FILTERS_LIST"	;;
            7)     COMPONENT_FILTERS_LIST_7="$COMPONENT_FILTERS_LIST"	;;
            8)     COMPONENT_FILTERS_LIST_8="$COMPONENT_FILTERS_LIST"	;;
            9)     COMPONENT_FILTERS_LIST_9="$COMPONENT_FILTERS_LIST"	;;
            10)     COMPONENT_FILTERS_LIST_10="$COMPONENT_FILTERS_LIST"	;;
	esac
}

resetComponentFiltersList()
{
	case $1 in
            2.6)   COMPONENT_FILTERS_LIST="$COMPONENT_FILTERS_LIST_6"	;;
            7)     COMPONENT_FILTERS_LIST="$COMPONENT_FILTERS_LIST_7"	;;
            8)     COMPONENT_FILTERS_LIST="$COMPONENT_FILTERS_LIST_8"	;;
            9)     COMPONENT_FILTERS_LIST="$COMPONENT_FILTERS_LIST_9"	;;
            10)     COMPONENT_FILTERS_LIST="$COMPONENT_FILTERS_LIST_10"	;;
	esac
}

setCompNames()
{
	case $1 in
            2.6)   COMP_NAMES_6="$COMP_NAMES"	;;
            7)     COMP_NAMES_7="$COMP_NAMES"	;;
            8)     COMP_NAMES_8="$COMP_NAMES"	;;
            9)     COMP_NAMES_9="$COMP_NAMES"	;;
            10)     COMP_NAMES_10="$COMP_NAMES"	;;
	esac
}

resetCompNames()
{
	case $1 in
            2.6)   COMP_NAMES="$COMP_NAMES_6"	;;
            7)     COMP_NAMES="$COMP_NAMES_7"	;;
            8)     COMP_NAMES="$COMP_NAMES_8"	;;
            9)     COMP_NAMES="$COMP_NAMES_9"	;;
            10)     COMP_NAMES="$COMP_NAMES_10"	;;
	esac
}

setInitCompDetails()
{
	case $1 in
            2.6)   INIT_COMP_DETAILS_6="$INIT_COMP_DETAILS"	;;
            7)     INIT_COMP_DETAILS_7="$INIT_COMP_DETAILS"	;;
            8)     INIT_COMP_DETAILS_8="$INIT_COMP_DETAILS"	;;
            9)     INIT_COMP_DETAILS_9="$INIT_COMP_DETAILS"	;;
            10)     INIT_COMP_DETAILS_10="$INIT_COMP_DETAILS"	;;
	esac
}

resetInitCompDetails()
{
	case $1 in
            2.6)   INIT_COMP_DETAILS="$INIT_COMP_DETAILS_6"	;;
            7)     INIT_COMP_DETAILS="$INIT_COMP_DETAILS_7"	;;
            8)     INIT_COMP_DETAILS="$INIT_COMP_DETAILS_8"	;;
            9)     INIT_COMP_DETAILS="$INIT_COMP_DETAILS_9"	;;
            10)     INIT_COMP_DETAILS="$INIT_COMP_DETAILS_10"	;;
	esac
}

# Echos uniq optional components list.
getUniqOptionalComponents()
{
	TEMP_COMPONENTS=""
	for OS in `$CMD_ECHO "$SELECTED_OS" | $CMD_AWK -F ',' '{ for (i = 1; i<= NF; i++) print $i }'`
	do
		resetOptionalComponents $OS
		TEMP_COMPONENTS="${TEMP_COMPONENTS}%${ALL_OPTIONAL_COMPONENTS}" 
	done

	COMPONENTS=`$CMD_ECHO "$TEMP_COMPONENTS" | $CMD_AWK 'BEGIN{RS="%"} {print}' | /usr/bin/sort | /usr/bin/uniq`
	COMPONENTS="$COMPONENTS"


#	for each_component in `$CMD_ECHO "$COMPONENTS" | $CMD_AWK -F '%' '{ for (i=1; i<=NF; i++) print $(i) }' | $CMD_AWK -F '@' '{ for(i=0; i<=NF; i++) print $(i) }`
#	do
#	    if [ ! -z "$each_component" -a "$each_component" != " " ]; then
#		if [ -z "$UNIQ_COMPONENTS" ]; then
#			UNIQ_COMPONENTS="${each_component}"
#		else
#			UNIQ_COMPONENTS="${UNIQ_COMPONENTS}@${each_component}"
#		fi
#	    fi
#	done

	UNIQ_COMPONENTS="${COMPONENTS}"
	$CMD_ECHO "$UNIQ_COMPONENTS"
}

getUniqAvailableKeys()
{
	UNIQ_KEYS=""

	for each_key in `$CMD_ECHO "$OS_FOR_AVAILABLE_KEYS" | $CMD_AWK -F ',' '{for (i=1; i<=NF ;i++) print $i }'`
	do
	    if [ ! -z "$each_key" -a "$each_key" != " " ]; then
	        tmp_prodkey=`$CMD_ECHO "$each_key" | $CMD_CUT -d: -f1`
		checkString "$UNIQ_KEYS" "$tmp_prodkey"
		[ $? -eq 0 ] && continue
		if [ -z "$UNIQ_KEYS" ]; then
		    UNIQ_KEYS="${tmp_prodkey}"
		else
		    UNIQ_KEYS="${UNIQ_KEYS} ${tmp_prodkey}"
		fi
	    fi
	done

	$CMD_ECHO "$UNIQ_KEYS"
}

setSelectedKeysFromUniqAvailableKeys()
{
	for OS in `$CMD_ECHO "$SELECTED_OS" | $CMD_AWK -F ',' '{ for (i = 1; i<= NF; i++) print $i }'`
	do
		case $OS in 
			2.6)   TMP_AVAILABLE_KEYS="$AVAILABLE_KEYS_6" ;;
			7)     TMP_AVAILABLE_KEYS="$AVAILABLE_KEYS_7" ;;
			8)     TMP_AVAILABLE_KEYS="$AVAILABLE_KEYS_8" ;;
			9)     TMP_AVAILABLE_KEYS="$AVAILABLE_KEYS_9" ;;
			10)     TMP_AVAILABLE_KEYS="$AVAILABLE_KEYS_10" ;;
		esac

		TMP_SELECTED_LIST=""

		for each_key in `$CMD_ECHO "$SELECTED_KEYS" | $CMD_AWK -F ' ' '{ for ( i=1; i<=NF; i++) print $i }'`
		do
			$CMD_ECHO "$TMP_AVAILABLE_KEYS" | $CMD_GREP $each_key  1>/dev/null 2>&1
			if [ $? -eq 0 ]; then
				$CMD_ECHO "$TMP_SELECTED_LIST" | $CMD_GREP $each_key 1>/dev/null 2>&1
				[ $? -eq 1 ] && TMP_SELECTED_LIST="$TMP_SELECTED_LIST $each_key"
			fi  # the key found in correcponding available keys
		done

                case $OS in
                        2.6)   SELECTED_KEYS_6="$TMP_SELECTED_LIST" ;;
                        7)     SELECTED_KEYS_7="$TMP_SELECTED_LIST" ;;
                        8)     SELECTED_KEYS_8="$TMP_SELECTED_LIST" ;;
                        9)     SELECTED_KEYS_9="$TMP_SELECTED_LIST" ;;
                        10)     SELECTED_KEYS_10="$TMP_SELECTED_LIST" ;;
                esac
	done
}

check_empty_selectedlist()
{
	cleanup_flag="TRUE"

	comp_var=`$CMD_ECHO "$SELECTED_KEYS_6" | $CMD_SED "s/ //g"`
	[ ! -z "$comp_var" ] && cleanup_flag="FALSE"
	comp_var=`$CMD_ECHO "$SELECTED_KEYS_7" | $CMD_SED "s/ //g"`
	[ ! -z "$comp_var" ] && cleanup_flag="FALSE"
	comp_var=`$CMD_ECHO "$SELECTED_KEYS_8" | $CMD_SED "s/ //g"`
	[ ! -z "$comp_var" ] && cleanup_flag="FALSE"
	comp_var=`$CMD_ECHO "$SELECTED_KEYS_9" | $CMD_SED "s/ //g"`
	[ ! -z "$comp_var" ] && cleanup_flag="FALSE"
	comp_var=`$CMD_ECHO "$SELECTED_KEYS_10" | $CMD_SED "s/ //g"`
	[ ! -z "$comp_var" ] && cleanup_flag="FALSE"

	if [ "$cleanup_flag" = "TRUE" ]; then
		echolog 'No product selected' 
		echolog 'Exiting...'
		$CMD_RM -rf $TARGET_ARCHIVE_DIR
                releaseImageToolLock
		exit 0
	fi
}

setSortedComponentsList()
{
	case $1 in
            2.6)   SORTED_COMPONENTS_LIST_6="$SORTED_INSTALL_COMPONENTS_LIST" ;;
            7)     SORTED_COMPONENTS_LIST_7="$SORTED_INSTALL_COMPONENTS_LIST" ;;
            8)     SORTED_COMPONENTS_LIST_8="$SORTED_INSTALL_COMPONENTS_LIST" ;;
            9)     SORTED_COMPONENTS_LIST_9="$SORTED_INSTALL_COMPONENTS_LIST" ;;
            10)     SORTED_COMPONENTS_LIST_10="$SORTED_INSTALL_COMPONENTS_LIST" ;;
	esac
}

resetSortedComponentsList()
{
	case $1 in
            2.6)   SORTED_INSTALL_COMPONENTS_LIST="$SORTED_COMPONENTS_LIST_6" ;;
            7)     SORTED_INSTALL_COMPONENTS_LIST="$SORTED_COMPONENTS_LIST_7" ;;
            8)     SORTED_INSTALL_COMPONENTS_LIST="$SORTED_COMPONENTS_LIST_8" ;;
            9)     SORTED_INSTALL_COMPONENTS_LIST="$SORTED_COMPONENTS_LIST_9" ;;
            10)     SORTED_INSTALL_COMPONENTS_LIST="$SORTED_COMPONENTS_LIST_10" ;;
	esac
}

### END SECTION #################################################



# Gets all the CD indexes so that it runs in a loop
# especially when it has to pause till next CD is inserted.

getAllCDs() 
{
	TEMP_CD_LIST="1"		# This variable is set to 1.
					# In case it is Add-On only image
					# archive tool still needs to create
					# disk1 with product config files.
	for OS in `$CMD_ECHO "$SELECTED_OS" | $CMD_AWK -F ',' '{ for (i = 1; i<= NF; i++) print $i }'`
	do
		resetSortedComponentsList $OS
		CD_LIST=`$CMD_ECHO "$SORTED_INSTALL_COMPONENTS_LIST" | $CMD_AWK 'BEGIN{RS=" "} {print}' | $CMD_SORT -n -t : -k 3 | $CMD_AWK -F ':' '{ print $3}' | /usr/bin/uniq`
	TEMP_CD_LIST="$TEMP_CD_LIST $CD_LIST"
	done

	TMP_FOR_ALL_CDS=`$CMD_ECHO "$TEMP_CD_LIST" | $CMD_AWK 'BEGIN{RS=" "} {print}' | $CMD_SORT -n  | /usr/bin/uniq`
	for cd in $TMP_FOR_ALL_CDS
	do
		ALL_CDS="$ALL_CDS $cd"
	done
	unset TMP_FOR_ALL_CDS TEMP_CD_LIST CD_LIST
}


# Returns 0 if processed
# Returns 1 if not processed
# And then adds it to the processed list

isSelectedKeyProcessed()
{
	product_key=$1
	checkString "$UNIQUE_SELECTED_KEYS" "$product_key"
	#tmp_key=`$CMD_ECHO "$UNIQUE_SELECTED_KEYS" | $CMD_GREP $product_key`
	if [ $? -eq 0 ]; then
		return 0
	else 
		UNIQUE_SELECTED_KEYS="$UNIQUE_SELECTED_KEYS $product_key"
		return 1
	fi
}

# This will create a logfile or set the LOGFILE variable
# $1: Prefix to be added to the log file name 

setArchiveLogdir() 
{
        ARCHIVE_PREFIX="$1"
        [ -z "$ARCHIVE_PREFIX" ] && ARCHIVE_PREFIX="es-imagetool"
	check_logfile "$ARCHIVE_PREFIX"

	[ -f "${LOGDIR}/installation.info" ] && $CMD_RM ${LOGDIR}/installation.info 
	[ -f "${LOGDIR}/installation.properties" ] && $CMD_RM ${LOGDIR}/installation.properties
}


# Reads the SOURCE_LIST and Makes a list of required patches
# For selected product
# This is called in a OS loop
# This is called when given source image is NOT a Patch only source

makeRequiredPatchesList() 
{

    for addon_product_key in `$CMD_ECHO "$SELECTED_KEYS" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
    do
        PATCH_LIST=`getProductAttr "$SOURCE_LIST" "$addon_product_key" "PATCHES"`
        [ -z "$PATCH_LIST" ] && continue
        for each_reqd_patch in `$CMD_ECHO "$PATCH_LIST" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
        do
            if [ -z "$PATCHES_TO_ARCHIVE" ] ; then
                PATCHES_TO_ARCHIVE="${each_reqd_patch}"
            else
                PATCHES_TO_ARCHIVE="${PATCHES_TO_ARCHIVE},${each_reqd_patch}"
            fi
        done
    done

}


# If a given source is PATCH ONLY
# This function goes through OS directories and Common directory
# Then makes a list of available patches

makeAvailablePatchesList() 
{
    if [ "$SOURCE_IMAGE" != "PATCH_ONLY" ]; then
        PATCH_DIR="${SRC_DIR}/Patches"
    else
	PATCH_DIR="${SRC_DIR}"
    fi
    ALL_AVAILABLE_PATCHES=""

    for PATCH_OS in `$CMD_ECHO "$SELECTED_OS" | $CMD_AWK -F ',' '{ for (i = 1; i<= NF; i++) print $i }'`
    do
    	OS_PATCH_DIRECTORY="${PATCH_DIR}/Solaris_${PATCH_OS}"
    	if [ -d "$OS_PATCH_DIRECTORY" ]; then
	    PATCHE_LIST=`$CMD_LS -1 ${OS_PATCH_DIRECTORY}`
	    for each_patch in $PATCHE_LIST
	    do
            	if [ -z "$ALL_AVAILABLE_PATCHES" ] ; then
		  ALL_AVAILABLE_PATCHES="${each_patch}"
		else
		  ALL_AVAILABLE_PATCHES="${ALL_AVAILABLE_PATCHES},${each_patch}"
		fi
	    done
        fi 
    done

    COMMON_PATCH_DIRECTORY="${PATCH_DIR}/Common"

    if [ -d "$COMMON_PATCH_DIRECTORY" ]; then
	PATCHE_LIST=`$CMD_LS -1 ${COMMON_PATCH_DIRECTORY}`
	for each_patch in $PATCHE_LIST
	do
	    for each_patch in $PATCHE_LIST
	    do
            	if [ -z "$ALL_AVAILABLE_PATCHES" ] ; then
		  ALL_AVAILABLE_PATCHES="${each_patch}"
		else
		  ALL_AVAILABLE_PATCHES="${ALL_AVAILABLE_PATCHES},${each_patch}"
		fi
	    done
	done
    fi
}


# If a given source image is PATCH ONLY, it presents patches
# for user selection.

selectPatchesInteractively()
{
    PATCHES_TO_ARCHIVE=""
    echolog ' '
    echolog 'Following patches are available for selection:'

    for each_patch in `$CMD_ECHO "$ALL_AVAILABLE_PATCHES" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
    do
	echolog '$2' "$each_patch"
    done

    echo ' '
    echo ' '

    for each_patch in `$CMD_ECHO "$ALL_AVAILABLE_PATCHES" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
    do
	ask_user 'Do you want to install patch $2' "$each_patch"
	[ -z "$answer" ] && answer=0
	if [ $answer -eq 1 ] ; then
            if [ -z "$PATCHES_TO_ARCHIVE" ] ; then
                PATCHES_TO_ARCHIVE="${each_patch}"
            else
                PATCHES_TO_ARCHIVE="${PATCHES_TO_ARCHIVE},${each_patch}"
            fi
	fi
    done
    
}


# High level function for performing space checks for selected patches.
# This is called in both the cases, when patches are required to be
# bundled with selected products, or when it's a Patch only image creation
# This will make a list of packge dirs under selected patches
# and pass it further to functions that do the actual calculations

checkSpaceForPatches()
{
    [ -z "$PATCHES_TO_ARCHIVE" ] && return

    if [ "$SOURCE_IMAGE" != "PATCH_ONLY" ]; then
        PATCH_DIR="${SRC_DIR}/Patches"
    else
        PATCH_DIR="${SRC_DIR}"
    fi

    PWD=`$CMD_PWD`
    cd "$PATCH_DIR"

    for OSVERS in `$CMD_ECHO "$SELECTED_OS" | $CMD_AWK -F ',' '{ for (i = 1; i<= NF; i++) print $i }'`
    do

	for each_patch in `$CMD_ECHO "$PATCHES_TO_ARCHIVE" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
	do
	    tmp_patch_dir="./Solaris_${OSVERS}/${each_patch}"
	    [ ! -d "$tmp_patch_dir" ] && tmp_patch_dir="./Common/${each_patch}"
	    [ ! -d "$tmp_patch_dir" ] && tmp_patch_dir="./CommonForSolaris/${each_patch}"
	    packages=""
	    if [ -d "$tmp_patch_dir" ]; then
		tmp_packages=`$CMD_LS -1 $tmp_patch_dir`
		for pkg in $tmp_packages
		do
		    [ ! -d "$tmp_patch_dir/$pkg" ] && continue

		    if [ -z "$packages" ]; then
			packages="$pkg"
		    else
			packages="${packages},${pkg}"
		    fi
		done
	    fi

            prod_key="${each_patch}"
            src_dir="${tmp_patch_dir}"
            name="${each_patch}"

            [ -z "$packages" ] && continue
            calculateSpaceForPatches $packages "$src_dir"
            checkSpace
       done
    done
    cd "$PWD"
}


# This calculates the space required for "patch packages"
# based on the blocks entry in the pkgmap files
# $1: A comma seaprated list of packages
# $2: The actual Patch directory 

calculateSpaceForPatches() 
{
    PACKAGE_LIST=$1
    PRODUCT_SRCDIR="$2"

    if [ "$SOURCE_IMAGE" != "PATCH_ONLY" ]; then
        PATCH_DIR="${SRC_DIR}/Patches"
    else
	PATCH_DIR="${SRC_DIR}"
    fi

    IS_COMMON=0
    tmp_size=`$CMD_EXPR $REQUIRED_SPACE_FORARCHIVES`

    #PRODUCT_SRCDIR=`getProductAttr "$SOURCE_LIST" "$PRODUCT" "SOURCE_DIR"`

    INPWD=`$CMD_PWD`
    cd "${PATCH_DIR}/${PRODUCT_SRCDIR}"
    for each_package in `$CMD_ECHO "$PACKAGE_LIST" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
    do
        LOCATION="./$each_package"

	if [ ! -d "$LOCATION" ]; then
	# Commenting out echologs below to prevent erronous warning msgs
	# from being displayed. Since not all components selected may have 
	# pkgs for all the selected OSes, the echologs below may be misleading
	#   echolog 'Package directory $2 not found!' "$each_package"
	#   echolog "  Space calculations will be wrong."
	    continue
	fi

	PKGMAP="${LOCATION}/pkgmap"
	if [ ! -f "$PKGMAP" ] ; then
    	    echolog 'Could not find the pkgmap file for $2' "$each_package"
    	    echolog "  Space calculations will be wrong."
    	    continue
	fi

	pkg_size=`$CMD_HEAD -10 "$PKGMAP" | $CMD_GREP '^:' | $CMD_AWK '{ print $3 }'`
	pkg_size=`$CMD_EXPR $pkg_size`
	tmp_size=`$CMD_EXPR $tmp_size + $pkg_size`
    done

    REQUIRED_SPACE_FORARCHIVES=`$CMD_EXPR $tmp_size`
    cd "$INPWD"
}


# This will create tarfile of all autometically selected patches
# i.e. Patches required for selected products.
# First it archives everything available under Essential directory
# if base product has been selected for upgrade.
# Then it sends patches for compression

archivePatches()
{

    if [ "$SOURCE_IMAGE" != "PATCH_ONLY" ]; then
        PATCH_DIR="${SRC_DIR}/Patches"
    else
	PATCH_DIR="${SRC_DIR}"
    fi

    ESSENTIAL_PATCH_DIRECTORY="${PATCH_DIR}/Essential"

    if [ ! -d "$ESSENTIAL_PATCH_DIRECTORY" ]; then
      if [ -z "$PATCHES_TO_ARCHIVE" ]; then
	echolog 'No patches to add into the image'
	return
      fi
    fi

    if [ ${BASE_PROD_ONLY} -eq 1 ]; then
        if [ ${CALLED_FROM_GUI} -eq 1 ]; then
            setPatchSourceForBaseOnlyGUI
        else
            setPatchSourceForBaseOnly
        fi
    fi
    
    ESSENTIAL_PATCH_DIRECTORY="${PATCH_DIR}/Essential"

    PWD=`$CMD_PWD`

    target_patch_subdir="$TARGET_ARCHIVE_DIR/disk${LAST_CD}/image/Patches/"
    target_disk1_patch_subdir="$TARGET_ARCHIVE_DIR/disk1/image/Patches/"
    $CMD_MKDIR -p $target_patch_subdir
    $CMD_MKDIR -p $target_disk1_patch_subdir

    # Essential patches HAVE TO BE added if available

    if [ -d "$ESSENTIAL_PATCH_DIRECTORY" ]; then

        cd "$PATCH_DIR"

	if [ -d "./Essential/Common" ]; then
            TARFILE="$target_patch_subdir/Common.tar"
            TARFILE1="$target_disk1_patch_subdir/Common.tar"
            if [ -f "$TARFILE" ]; then
	        $CMD_TAR -uvf $TARFILE ./Essential/Common
	        $CMD_TAR -uvf $TARFILE1 ./Essential/Common
	    else
	        $CMD_TAR -cvf $TARFILE ./Essential/Common
	        $CMD_TAR -cvf $TARFILE1 ./Essential/Common
	    fi
	fi

	if [ -d "./Essential/CommonForSolaris" ]; then
            TARFILE="$target_patch_subdir/Common.tar"
            TARFILE1="$target_disk1_patch_subdir/Common.tar"
            if [ -f "$TARFILE" ]; then
	        $CMD_TAR -uvf $TARFILE ./Essential/CommonForSolaris
	        $CMD_TAR -uvf $TARFILE1 ./Essential/CommonForSolaris
	    else
	        $CMD_TAR -cvf $TARFILE ./Essential/CommonForSolaris
	        $CMD_TAR -cvf $TARFILE1 ./Essential/CommonForSolaris
	    fi
	fi

        for PATCH_OS in `$CMD_ECHO "$SELECTED_OS" | $CMD_AWK -F ',' '{for (i = 1; i <= NF; i++) print $i }'`
        do
   	    OS_PATCH_DIRECTORY="${PATCH_DIR}/Essential/Solaris_${PATCH_OS}"
	    [ ! -d "$OS_PATCH_DIRECTORY" ] && continue

    	    TARFILE="$target_patch_subdir/Solaris_${PATCH_OS}.tar"
    	    TARFILE1="$target_disk1_patch_subdir/Solaris_${PATCH_OS}.tar"
            if [ -f "$TARFILE" ]; then
	        $CMD_TAR -uvf $TARFILE ./Essential/Solaris_${PATCH_OS}
	        $CMD_TAR -uvf $TARFILE1 ./Essential/Solaris_${PATCH_OS}
	    else
	        $CMD_TAR -cvf $TARFILE ./Essential/Solaris_${PATCH_OS}
	        $CMD_TAR -cvf $TARFILE1 ./Essential/Solaris_${PATCH_OS}
	    fi
        done

    fi

    COMMON_PATCH_DIRECTORY="${PATCH_DIR}/Common"

    if [ -d "$COMMON_PATCH_DIRECTORY" ]; then
    
        TARFILE="$target_patch_subdir/Common.tar"

        cd "$PATCH_DIR"

        for each_patch in `$CMD_ECHO "$PATCHES_TO_ARCHIVE" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
        do
	    if [ -d ./Common/$each_patch ]; then
                echolog 'Adding $2' "$each_patch..."
                if [ -f "$TARFILE" ]; then
		    $CMD_TAR -uvf $TARFILE ./Common/$each_patch
	        else
		    $CMD_TAR -cvf $TARFILE ./Common/$each_patch
	        fi
	    fi
        done
    fi
 
    for PATCH_OS in `$CMD_ECHO "$SELECTED_OS" | $CMD_AWK -F ',' '{for (i = 1; i <= NF; i++) print $i }'`
    do
   	OS_PATCH_DIRECTORY="${PATCH_DIR}/Solaris_${PATCH_OS}"
	[ ! -d "$OS_PATCH_DIRECTORY" ] && continue

    	TARFILE="$target_patch_subdir/Solaris_${PATCH_OS}.tar"

        cd "$PATCH_DIR"

    	for each_patch in `$CMD_ECHO "$PATCHES_TO_ARCHIVE" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
    	do
	    if [ -d ./Solaris_${PATCH_OS}/$each_patch ]; then
                echolog 'Adding $2' "$each_patch..."
               	if [ -f "$TARFILE" ]; then
	    	    $CMD_TAR -uvf $TARFILE ./Solaris_${PATCH_OS}/$each_patch
	    	else
		     $CMD_TAR -cvf $TARFILE ./Solaris_${PATCH_OS}/$each_patch
	    	fi
	    fi
    	done
    done

    PATCH_IN_POLICY=`$API_QUERY_XML $UPGRADE_POLICY_FILE product key 2>/dev/null`
    checkString "$PATCH_IN_POLICY" "SUNMC.PATCH"
    if [ $? -ne 0 ]; then
        $API_INSERT_TAG $UPGRADE_POLICY_FILE products=SunMC product=SUNMC.PATCH 2>/dev/null
        $API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=SUNMC.PATCH name="Sun Management Center Patches" 2>/dev/null
        $API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=SUNMC.PATCH type="Patch" 2>/dev/null
        $API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=SUNMC.PATCH archive-type="tar.Z" 2>/dev/null
    fi

    cd "$PWD"
    compressArchive "Patches" "SUNMC.PATCH" "disk1"
    cd "$PWD"
    compressArchive "Patches" "SUNMC.PATCH" "disk${LAST_CD}"

}

setPatchSourceForBaseOnlyGUI ()
{

    # Get the file system type of the image dir before changing SRC_DIR
    image_fstype=`$CMD_DF -n "$SRC_DIR" | $CMD_CUT -d: -f2 | $CMD_SED -e 's/^ *\([^    ]*\) *$/\1/' 2>/dev/null`

    if [ "$image_fstype" = "hsfs" ]; then
        if [ "$WAITING_FOR_NEXT_CD" != "TRUE" ]; then 
            /usr/bin/eject -q cd 2> /dev/null
            [ $? -eq 0 ] && /usr/bin/eject cdrom0
            [ $? -ne 0 ] && echolog "Not able to eject the CDROM"
            echolog 'Cannot proceed without disk $LAST_CD'
	    ARCHIVE_TOOL_CURRENT_CD=$LAST_CD
	    echolog 'Writing to properties file'
	    WAITING_FOR_NEXT_CD="TRUE"
	    CD_MOUNTED="FALSE"
	    saveAllVariables
	    exit 1 # exits back to the GUI where path to second CD is asked
	fi
      PATCH_DIR="${SRC_DIR}/Patches"
    else
        l_dirname=`$CMD_DIRNAME $SRC_DIR`
        l_basename=`$CMD_BASENAME $l_dirname`
        if [ "$l_basename" = "x86" ]; then
            PATCH_DIR="${SRC_DIR}/../../../disk${LAST_CD}/x86/image/Patches"
        else
            PATCH_DIR="${SRC_DIR}/../../disk${LAST_CD}/image/Patches"
        fi    
    fi
    
}      

setPatchSourceForBaseOnly ()
{

    # Get the file system type of the image dir before changing SRC_DIR
    image_fstype=`$CMD_DF -n "$SRC_DIR" | $CMD_CUT -d: -f2 | $CMD_SED -e 's/^ *\([^    ]*\) *$/\1/' 2>/dev/null`

    if [ "$image_fstype" = "hsfs" ]; then
        # It's a local CDROM
        /usr/bin/eject -q cd 2> /dev/null
        [ $? -eq 0 ] && /usr/bin/eject cdrom0
        [ $? -ne 0 ] && echolog "Not able to eject the CDROM"

        echolog ' '
        echolog 'Cannot proceed without disk $2' "${LAST_CD}"
        SRC_DIR=""             # reset the SRC_DIR

        while [ 1 ]; do  # loop until you get source directory
            getSourceDirectory
            getSourceVersion
            checkSourceDirArch "$IMAGETOOL_ARCH"
            [ $? -eq 0 ] && break  # correct dir for the architecture
            SRC_DIR=""             # reset the SRC_DIR 
        done
        PATCH_DIR="${SRC_DIR}/Patches"
    else
        l_dirname=`$CMD_DIRNAME $SRC_DIR`
        l_basename=`$CMD_BASENAME $l_dirname`
        if [ "$l_basename" = "x86" ]; then
            PATCH_DIR="${SRC_DIR}/../../../disk${LAST_CD}/x86/image/Patches"
        else
            PATCH_DIR="${SRC_DIR}/../../disk${LAST_CD}/image/Patches"
        fi    
    fi
    
}       


# This assigns an OS variable to required patch list.
# This is because the patches-required list for a product
# will be different for different OS

setOSforAvailableProducts()
{
    for each_product in `$CMD_ECHO "$AVAILABLE_KEYS" | $CMD_AWK -F ' ' '{for (i=1; i<=NF ;i++) print $i }'`
    do
	checkString "$OS_FOR_AVAILABLE_KEYS" "$each_product"
	[ $? -eq 0 ] && continue
	if [ -z "$OS_FOR_AVAILABLE_KEYS" ]; then
	    OS_FOR_AVAILABLE_KEYS="$each_product:$OSVERS"
	else
	    OS_FOR_AVAILABLE_KEYS="$OS_FOR_AVAILABLE_KEYS,$each_product:$OSVERS"
	fi
    done
}

# Scans through the list OS_FOR_AVAILABLE_KEYS
# sets the OSVERS variable to whichever OS version 
# under which the selected product is available
# $1 Selected product key

resetOSforProduct()
{
    tmp_osvers="$OSVERS"
    selected_prodkey="$1"
    for each_product in `$CMD_ECHO "$OS_FOR_AVAILABLE_KEYS" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
    do
	tmp_prodkey=`$CMD_ECHO "$each_product" | $CMD_CUT -d: -f1`
	[ "$tmp_prodkey" != "$selected_prodkey" ] && continue
	
	if [ "$tmp_prodkey" = "$selected_prodkey" ]; then
	    tmp_osvers=`$CMD_ECHO "$each_product" | $CMD_CUT -d: -f2`
	    break
	fi
    done
    OSVERS="$tmp_osvers"
    resetSourceList $OSVERS         # restore source list for OS
    resetAvailableKeys $OSVERS      # restore available keys
    resetOptionalComponents $OSVERS
    resetComponentFiltersList $OSVERS
    resetCompNames $OSVERS
    resetInitCompDetails $OSVERS

    unset tmp_osvers tmp_prodkey selected_prodkey
}


# Interactively select OS versions for which user wants to create
# update images.

selectOSVersions()
{
    echolog ' '
    echolog 'Choose the Solaris versions for all of the destination host machines.'
    echolog 'The Sun Management Center update-image will be created'
    echolog 'only for the Solaris versions you choose.'
    echolog ' '
    echolog 'Supported os version are:'

    check_s10_or_above=0
    s9_or_below=0
    
    is_s10_or_above_selected=0
    is_s9_or_below_selected=0
    is_s9_selected=0
    
    s9_added=0
    ALL_SUPPORTED_OS_EQUIV=""

    for each_sup_os in `$CMD_ECHO "$ALL_SUPPORTED_OS" | $CMD_AWK -F ',' '{ for (i = 1; i<= NF; i++) print $i }'`
    do
        echolog "Solaris_${each_sup_os}" 
        if [ ${each_sup_os} -ge 10 ]; then
            check_s10_or_above=1
        else
            s9_or_below=1
        fi
        [ ${each_sup_os} -eq 9 ] && s9_added=1
        if [ -z "$ALL_SUPPORTED_OS_EQUIV" ]; then
            ALL_SUPPORTED_OS_EQUIV="$each_sup_os"
        else
            ALL_SUPPORTED_OS_EQUIV="$ALL_SUPPORTED_OS_EQUIV,$each_sup_os"
        fi
    done
    if [ ${s9_added} -eq 0 -a ${check_s10_or_above} -eq 1 ]; then
	if [ -z "$ALL_SUPPORTED_OS_EQUIV" ]; then
	    ALL_SUPPORTED_OS_EQUIV="9"
	else
	    ALL_SUPPORTED_OS_EQUIV="$ALL_SUPPORTED_OS_EQUIV,9"
	fi
    fi

    while [ 1 -eq 1 ]
    do
	SELECTED_OS=""
        echolog ' '

        ask_user 'Do you want to select ALL OS versions '
        if [ "$answer" = "1" ]; then
	    SELECTED_OS="$ALL_SUPPORTED_OS_EQUIV"
	    [ $check_s10_or_above -eq 1 ] && is_s10_or_above_selected=1
	    [ $s9_or_below -eq 1 ] && is_s9_or_below_selected=1
        else
            echolog ' '
	    for each_os in `$CMD_ECHO "$ALL_SUPPORTED_OS" | $CMD_AWK -F ',' '{ for (i = 1; i<= NF; i++) print $i }'`
	    do
	        ask_user 'Do you want to create images for $2 ' "Solaris_${each_os}"
	        if [ "$answer" = "1" ]; then
	            if [ ${each_os} -ge 10 ]; then
		        is_s10_or_above_selected=1
		    else
		        is_s9_or_below_selected=1
		    fi
		    [ ${each_os} -eq 9 ] && is_s9_selected=1
		    if [ -z "$SELECTED_OS" ]; then
		        SELECTED_OS="$each_os"
		    else
		        SELECTED_OS="$SELECTED_OS,$each_os"
		    fi
	        fi
	    done
	    if [ ${is_s9_selected} -eq 0 -a ${is_s10_or_above_selected} -eq 1 ]; then
	    	if [ -z "$SELECTED_OS" ]; then
	    	    SELECTED_OS="9"
	    	else
	    	    SELECTED_OS="$SELECTED_OS,9"
	    	fi
	    fi
        fi
	if [ -z "$SELECTED_OS" ]; then
	    echolog ' '
	    echolog 'No OS has been selected'
	else
            echolog ' '
            echolog 'Images will be created for the following OS versions:'
	    for each_sel_os in `$CMD_ECHO "$SELECTED_OS" | $CMD_AWK -F ',' '{ for (i = 1; i<= NF; i++) print $i }'`
	    do
		[ ${each_sel_os} -eq 9 -a ${is_s9_selected} -eq 0 ] && continue #  Aviod displaying S9 among selected OSes if it is not selected.
		echolog "Solaris_${each_sel_os}"
	    done
	    break
	fi
    done
}


# Top level function for space checks
# Makes list of packages of selected products
# and sends them for space calculation 

checkSpaceForProducts()
{
    for OSVERS in `$CMD_ECHO "$SELECTED_OS" | $CMD_AWK -F ',' '{ for (i = 1; i<= NF; i++) print $i }'`
    do
        resetSortedComponentsList $OSVERS
        resetSourceList $OSVERS

        for each_pkglist in `$CMD_ECHO "${SORTED_INSTALL_COMPONENTS_LIST}" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
        do
            prod_key=`$CMD_ECHO "$each_pkglist" | $CMD_AWK -F ':' '{ print $4 }'`
            src_dir=`getProductAttr "$SOURCE_LIST" "$prod_key" "SOURCE_DIR"`
            [ "$prod_key" != "PRODUCT.PE" ] && src_dir="Addons/${src_dir}"
            name=`getProductAttr "$SOURCE_LIST" "$prod_key" "NAME"`
            packages=`$CMD_ECHO "$each_pkglist" | $CMD_AWK -F ':' '{ print $2 }'`
            [ -z "$packages" ] && continue
            calculateSpace $packages $OSVERS "$src_dir" "$prod_key"
            checkSpace
        done
    done

}

# Space checking function
# Keeps on adding required space into REQUIRED_SPACE_FORARCHIVES

calculateSpace() 
{
    PACKAGE_LIST=$1
    OS_VERS=$2
    PRODUCT_SRCDIR="$3"
    PRODUCT_KEY=$4

    IS_COMMON=0
    tmp_size=`$CMD_EXPR $REQUIRED_SPACE_FORARCHIVES`

    #PRODUCT_SRCDIR=`getProductAttr "$SOURCE_LIST" "$PRODUCT" "SOURCE_DIR"`
    UPDATE_PRODUCT_NAME=`getProductAttr "$SOURCE_LIST" "$PRODUCT_KEY" "NAME"`

    INPWD=`$CMD_PWD`
    cd "${SRC_DIR}/${PRODUCT_SRCDIR}"
    for each_package in `$CMD_ECHO "$PACKAGE_LIST" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
    do
        OSDIR="./Solaris_${OS_VERS}"
        LOCATION="./${OSDIR}/Basic/$each_package"
   	[ ! -d "$LOCATION" ] && LOCATION="./Common/Basic/$each_package" && IS_COMMON=1
    	[ ! -d "$LOCATION" ] && LOCATION="./CommonForSolaris/Basic/$each_package" && IS_COMMON=1

	if [ IS_COMMON -eq 1 ]; then
	    checkString "$COMMON_PACKAGES" "$each_package"
	    [ $? -eq 0 ] continue

	    COMMON_PACKAGES="$COMMON_PACKAGES,$each_package"   
	fi

	if [ ! -d "$LOCATION" ]; then
	    echolog 'Package directory $2 not found!' "$each_package"
	    echolog "  Space calculations will be wrong."
	    continue
	fi

	PKGMAP="${LOCATION}/pkgmap"
	if [ ! -f "$PKGMAP" ] ; then
    	    echolog 'Could not find the pkgmap file for $2' "$each_package"
    	    echolog "  Space calculations will be wrong."
    	    continue
	fi

	pkg_size=`$CMD_HEAD -10 "$PKGMAP" | $CMD_GREP '^:' | $CMD_AWK '{ print $3 }'`
	pkg_size=`$CMD_EXPR $pkg_size`
	tmp_size=`$CMD_EXPR $tmp_size + $pkg_size`
    done

    REQUIRED_SPACE_FORARCHIVES=`$CMD_EXPR $tmp_size`
    cd "$INPWD"
}


# The actual space checking calculation
# Space required against space available

checkSpace()
{
    required_space=`$CMD_EXPR $REQUIRED_SPACE_FORARCHIVES`
    config_dir="$AGENT_UPDATE_DIR"

    df_line=`$CMD_DF -k "$config_dir" | $CMD_TAIL -1`
    avail_space=`$CMD_ECHO "$df_line" | $CMD_AWK '{ print $4 }'`

    avail_space_kb=$avail_space
    required_space_kb=`$CMD_EXPR $required_space / 2`

    # Double the number reported by df -k to get 512-byte blocks to get
    # the same units as pkgmap

    avail_space=`$CMD_EXPR $avail_space \* 2`


    if [ $avail_space -lt $required_space ]; then
	echolog ' '
	echolog 'Insufficient disk space for image creation'
        echolog 'Requires $2 kbytes space' "$required_space_kb"
	echolog ' '
	echolog 'Re-start the image tool'
	echolog 'Please use a directory where $2 kbytes space is available' "$required_space_kb"
	echolog ' '
	echolog ' '
	echolog 'Cleaning up the image $2' "$ARCHIVE_TARGET_DIRNAME"
	$CMD_RM -rf $TARGET_ARCHIVE_DIR
	echolog ' '
	echolog 'Exiting ...'
	if [ -f "$AGENT_UPDATE_DIR/tmpGUI.properties" ]; then
	    # this is for GUI
	    put_var_in_cfgfile "$AGENT_UPDATE_DIR/tmpGUI.properties" "REQUIRED_SPACE" "$required_space_kb" "="
	    put_var_in_cfgfile "$AGENT_UPDATE_DIR/tmpGUI.properties" "AVAILABLE_SPACE" "$avail_space_kb" "="
	fi
        releaseImageToolLock
        exit 1
    fi
}


# In case this is Patch only image creation
# It still creates a directory PE and install response file
# It puts disk1/image/Patches as a source dir in thre response file
# This keeps InstallClient's call to es-inst independent of whether
# this is a regular image or Patch only image.
# es-inst is capable of identifying and taking appropriate action


updateResponseForPatchOnly()
{
	INSTALL_RESPONSE_FILE="install-response.cfg"
	AUTOCONFIG_SAVEFILE="$SMART_UPDATE_DIR/disk1/image/PE/$INSTALL_RESPONSE_FILE"
	$CMD_TOUCH "$AUTOCONFIG_SAVEFILE"
        saveAutoConfig "SOURCE_DIRECTORY" "/tmp/agentupdate/$ARCHIVE_TARGET_DIRNAME/disk${LAST_CD}/image/Patches"
}


# This is to avoid two simultaneous running instances of es-[gui]-imagetool

acquireLockForImageTool ()
{
    # TMP_DIR variable required in a common location for gui and cli imagetool
    create_temp_directory
    
    curr_pid=$$
    IMAGETOOL_LOCKFILE="${AGENT_UPDATE_DIR}/.imagetool-lock"
    if [ -f "$IMAGETOOL_LOCKFILE" ]; then
        old_pid=`get_value_from_cfgfile "$IMAGETOOL_LOCKFILE" "IMAGETOOL_PID" "="`
        if [ $? -eq 0 ]; then    # Got pid. A process is running
            /usr/bin/ps -f -p "$old_pid" | $CMD_GREP "imagetool" >/dev/null
            if [ $? -eq 0 ]; then    # An instance of imagetool is running
                echo " "
                echolog "An instance of image tool is already running"
                echolog 'Process id : $2' "$old_pid"
                echo " "
                exit 1
            fi
        fi
    fi

    $CMD_RM -f "$IMAGETOOL_LOCKFILE"
    $CMD_TOUCH "$IMAGETOOL_LOCKFILE"
    [ $? -ne 0 ] && echolog "Failed to acquire lock for imagetool" && exit 1
    put_var_in_cfgfile "$IMAGETOOL_LOCKFILE" "IMAGETOOL_PID" "$curr_pid" "="
    [ $? -ne 0 ] && echolog "Failed to acquire lock for imagetool" && exit 1
    
    echologverbose "Acquired a lock for imagetool"
    return
}


# This is to release the lock when imagetool process exits
# Not so IMP. Even if this is not called, the next lock will be
# created since this process will no more be in running state

releaseImageToolLock ()
{
    curr_pid=$$
    IMAGETOOL_LOCKFILE="${AGENT_UPDATE_DIR}/.imagetool-lock"
    if [ -f "$IMAGETOOL_LOCKFILE" ]; then
        old_pid=`get_value_from_cfgfile "$IMAGETOOL_LOCKFILE" "IMAGETOOL_PID" "="`
        if [ "$curr_pid" = "$old_pid" ]; then    # Release the lock
            $CMD_RM -f "$IMAGETOOL_LOCKFILE"
            echologverbose "Released imagetool lock"
        else                                     # PID mismatch
            echolog "Failed to release imagetool lock"
        fi
    fi
    
    # TMP_DIR cleanup required in a common location for gui and cli imagetool
    remove_temp_directory
}


# This is similar code to archivePatches
# added at vary late stages to support Patch only installation 
# The basic idea is when user gives Patch Only source dir
# all the patches inside, may not be required for any SunMC product
# Still Agent Update should be able to install it
# So this section puts all such selected patches into Essential
# directory. This forces es-inst to install these without any checks

archiveEssentialPatches()
{
    if [ -z "$PATCHES_TO_ARCHIVE" ]; then
	echolog 'No patches to add into the image'
	return
    fi

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

    PATCH_DIR="${SRC_DIR}"

    PWD=`$CMD_PWD`

    target_patch_subdir="${TARGET_ARCHIVE_DIR}/disk${LAST_CD}/image/Patches"
    target_patch_essdir="${target_patch_subdir}/Essential"
    $CMD_MKDIR -p "$target_patch_essdir"

    # First copy all required patches in the dir to this directory

    for PATCH_OS in `$CMD_ECHO "$SELECTED_OS" | $CMD_AWK -F ',' '{for (i = 1; i <= NF; i++) print $i }'`
    do
        OS_PATCH_DIRECTORY="${PATCH_DIR}/Solaris_${PATCH_OS}"
        [ ! -d "$OS_PATCH_DIRECTORY" ] && continue

        target_os_patch_subdir="${target_patch_essdir}/Solaris_${PATCH_OS}"

        cd "$OS_PATCH_DIRECTORY"

        for each_patch in `$CMD_ECHO "$PATCHES_TO_ARCHIVE" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
        do
            if [ -d ./$each_patch ]; then
                echolog 'Copying $2' "$each_patch..."
		put_var_in_cfgfile "${PROGRESS_FILE}" "PACKAGE" "$each_patch" "="
		put_var_in_cfgfile "${PROGRESS_FILE}" "PRODUCT" "Sun Management Center Patches" "="
                $CMD_MKDIR -p "${target_os_patch_subdir}/${each_patch}"
                $CMD_CP -r ./$each_patch/* "${target_os_patch_subdir}/${each_patch}/"
                $CMD_CP -r ./$each_patch/.* "${target_os_patch_subdir}/${each_patch}/"
            fi
        done
    done

    COMMON_PATCH_DIRECTORY="${PATCH_DIR}/CommonForSolairs"
    if [ ! -d "$COMMON_PATCH_DIRECTORY" ]; then
        COMMON_PATCH_DIRECTORY="${PATCH_DIR}/Common"
    fi

    if [ -d "$COMMON_PATCH_DIRECTORY" ]; then

        target_common_patch_subdir="${target_patch_essdir}/Common"
        cd "$COMMON_PATCH_DIRECTORY"

        for each_patch in `$CMD_ECHO "$PATCHES_TO_ARCHIVE" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
        do
            if [ -d ./$each_patch ]; then
                echolog 'Copying $2' "$each_patch..."
		put_var_in_cfgfile "${PROGRESS_FILE}" "PACKAGE" "$each_patch" "="
		put_var_in_cfgfile "${PROGRESS_FILE}" "PRODUCT" "Sun Management Center Patches" "="
                $CMD_MKDIR -p "${target_common_patch_subdir}/${each_patch}"
                $CMD_CP -r ./$each_patch/* "${target_common_patch_subdir}/${each_patch}/"
                $CMD_CP -r ./$each_patch/.* "${target_common_patch_subdir}/${each_patch}/"
            fi
        done
    fi

    # Now start archiving it. At the same time remove the patchdir

    COMMON_PATCH_DIRECTORY="$target_common_patch_subdir"
    if [ -d "$COMMON_PATCH_DIRECTORY" ]; then
        TARFILE="${target_patch_subdir}/Common.tar"
        cd "$target_patch_subdir"
        for each_patch in `$CMD_ECHO "$PATCHES_TO_ARCHIVE" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
        do
            if [ -d ./Essential/Common/$each_patch ]; then
                echolog 'Adding $2' "$each_patch..."
		put_var_in_cfgfile "${PROGRESS_FILE}" "PACKAGE" "$each_patch" "="
		put_var_in_cfgfile "${PROGRESS_FILE}" "PRODUCT" "Sun Management Center Patches" "="
                if [ -f "$TARFILE" ]; then
                    $CMD_TAR -uvf $TARFILE ./Essential/Common/$each_patch
                else
                    $CMD_TAR -cvf $TARFILE ./Essential/Common/$each_patch
                fi
                $CMD_RM -rf ./Essential/Common/$each_patch
            fi
        done
    fi

    for PATCH_OS in `$CMD_ECHO "$SELECTED_OS" | $CMD_AWK -F ',' '{for (i = 1; i <= NF; i++) print $i }'`
    do
        OS_PATCH_DIRECTORY="${target_patch_essdir}/Solaris_${PATCH_OS}"
        [ ! -d "$OS_PATCH_DIRECTORY" ] && continue

        TARFILE="$target_patch_subdir/Solaris_${PATCH_OS}.tar"

        cd "$target_patch_subdir"

        for each_patch in `$CMD_ECHO "$PATCHES_TO_ARCHIVE" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
        do
            if [ -d ./Essential/Solaris_${PATCH_OS}/$each_patch ]; then
                echolog 'Adding $2' "$each_patch..."
		put_var_in_cfgfile "${PROGRESS_FILE}" "PACKAGE" "$each_patch" "="
		put_var_in_cfgfile "${PROGRESS_FILE}" "PRODUCT" "Sun Management Center Patches" "="
                if [ -f "$TARFILE" ]; then
                    $CMD_TAR -uvf $TARFILE ./Essential/Solaris_${PATCH_OS}/$each_patch
                else
                    $CMD_TAR -cvf $TARFILE ./Essential/Solaris_${PATCH_OS}/$each_patch
                fi
                $CMD_RM -rf ./Essential/Solaris_${PATCH_OS}/$each_patch
            fi
        done
    done

    $CMD_RM -rf ./Essential

    PATCH_IN_POLICY=`$API_QUERY_XML $UPGRADE_POLICY_FILE product key 2>/dev/null`
    checkString "$PATCH_IN_POLICY" "SUNMC.PATCH"
    if [ $? -ne 0 ]; then
        $API_INSERT_TAG $UPGRADE_POLICY_FILE products=SunMC product=SUNMC.PATCH 2>/dev/null
        $API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=SUNMC.PATCH name="Sun Management Center Patches" 2>/dev/null
        $API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=SUNMC.PATCH type="Patch" 2>/dev/null
        $API_SET_ATTRIBUTE $UPGRADE_POLICY_FILE product=SUNMC.PATCH archive-type="tar.Z" 2>/dev/null
    fi

    cd "$PWD"
    compressArchive "Patches" "SUNMC.PATCH" "disk${LAST_CD}"

    ARCHIVED_PATCHES_FILE=${TARGET_ARCHIVE_DIR}/.archived-patches

    if [ -f "$ARCHIVED_PATCHES_FILE" ]; then
        $CMD_RM -f "$ARCHIVED_PATCHES_FILE"
    else
        $CMD_TOUCH "$ARCHIVED_PATCHES_FILE"
    fi

    $CMD_ECHO "ESSENTIAL_PATCHES=${PATCHES_TO_ARCHIVE}" >> "$ARCHIVED_PATCHES_FILE"

}

getSourceArchAndSetPathPrefix () {

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

    l_dirname=`$CMD_DIRNAME $SRC_DIR`
    l_basename=`$CMD_BASENAME $l_dirname`
    if [ "$l_basename" = "x86" ]; then
        IMAGETOOL_ARCH="i386"
    else
        IMAGETOOL_ARCH="sparc"
    fi

    case $IMAGETOOL_ARCH in
        sparc) IMAGETOOL_ARCHPREFIX="" ;
               IMAGETOOL_PATHPREFIX="";
        ;;
        i386) IMAGETOOL_ARCHPREFIX="x86" ;
               IMAGETOOL_PATHPREFIX="../";
        ;;
    esac
 
}

# This function detects the pkg architecture of the patches
# that are available inside the source dir.
# returns 0 if all patches are of same ARCH
# returns 1 if thre is a mix up

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

    sparc_count=0
    i386_count=0
    all_count=0

    l_pwd=`$CMD_PWD`
    cd "$SRC_DIR"
    all_patches=`$CMD_LS -d */*`

    for each_patch in $all_patches
    do
        tmp_arch=""
        cd "$SRC_DIR/$each_patch"
        i386_pkginfo_arch=`$CMD_GREP ARCH=i386 SUNW*/pkginfo`
        sparc_pkginfo_arch=`$CMD_GREP ARCH=sparc SUNW*/pkginfo`
        all_pkginfo_arch=`$CMD_GREP ARCH=all SUNW*/pkginfo`

        if [ ! -z "$i386_pkginfo_arch" ]; then 
            i386_count=`$CMD_EXPR $i386_count + 1`
            tmp_arch="${tmp_arch} i386"
        fi
        if [ ! -z "$sparc_pkginfo_arch" ]; then
            sparc_count=`$CMD_EXPR $sparc_count + 1`
            tmp_arch="${tmp_arch} sparc"
        fi
        if [ ! -z "$all_pkginfo_arch" ]; then
            all_count=`$CMD_EXPR $all_count + 1`
            tmp_arch="${tmp_arch} all"
        fi
        if [ -z "$i386_pkginfo_arch" -a -z "$sparc_pkginfo_arch" -a -z "$all_pkginfo_arch" ]; then
            # Default to sparc
            sparc_count=`$CMD_EXPR $sparc_count + 1`
            tmp_arch="${tmp_arch} unknown"
        fi
        echologverbose 'Patch: $2 Arch: $3' $each_patch "$tmp_arch"
    done

    if [ $i386_count -gt 0 -a $sparc_count -gt 0 ]; then
        # Mixed architecture
        echologverbose 'sparc patches: $2     i386 patches: $3' $sparc_count $i386_count
        cd $l_pwd
        return 1
    fi

    # Set the ARCH variable so that it's recorded in the policy file.
    if [ $all_count -gt 0 -a $i386_count -eq 0 -a $sparc_count -eq 0 ]; then
        IMAGETOOL_ARCH="sparc,i386"
    elif [ $i386_count -gt 0 ]; then
        IMAGETOOL_ARCH="i386"
    else
        IMAGETOOL_ARCH="sparc"
    fi
    cd $l_pwd
    return 0

}


