#!/bin/sh

# Copyright 05/31/05 Sun Microsystems, Inc. All Rights Reserved.
#pragma ident "@(#)es-imagetool	1.82 05/05/31 Sun Microsystems"

#           Main starts here                                            #
#########################################################################
PROGNAME="archive-tool"
IMAGETOOL_PROGNAME="$0"

PREV_DIR=`/usr/bin/pwd`
SCRIPT_DIR=`/usr/bin/dirname "$0"`
TOOLS_DIR=${SCRIPT_DIR}/../lib/sbin

AGENT_UPDATE_DIR="/var/opt/SUNWsymon/agentupdate"

AUTOCONFIG_SAVEFILE=""
REMOTE_TARGET_DIR="/opt"

UPGRADE_POLICY_FILE=""
UPGRADE_POLICY_FILE_NAME=""

API_DIR=""
LIB_DIR=""

ARCHIVE_BASE_FLAG=0
ARCHIVE_ADDON_FLAG=0
ARCHIVE_PATCHES_FLAG=0
ARCHIVE_PRODUCT_SELECTION=""
WEBPORT=80
SPLIT_SIZE=0
DEFAULT_SPLIT_SIZE=1024

SETUP_RESPONSE_FILE=""
INSTALL_RESPONSE_FILE=""
RESPONSE_FILE_LIST=""
COMPONENT_SCRIPT_LIST=""

# The source image processing will create 4 source lists. One for each OS. 
# Declaring required variables.

SOURCE_LIST_6="" ; SELECTED_KEYS_6=""; AVAILABLE_KEYS_6="";
ALL_OPTIONAL_COMPONENTS_6=""; SORTED_COMPONENTS_LIST_6=""; 
COMPONENT_FILTERS_LIST_6=""; COMP_NAMES_6=""; INIT_COMP_DETAILS_6=""
SOURCE_LIST_7="" ; SELECTED_KEYS_7=""; AVAILABLE_KEYS_7="";
ALL_OPTIONAL_COMPONENTS_7=""; SORTED_COMPONENTS_LIST_7="";
COMPONENT_FILTERS_LIST_7=""; COMP_NAMES_7=""; INIT_COMP_DETAILS_7=""
SOURCE_LIST_8="" ; SELECTED_KEYS_8=""; AVAILABLE_KEYS_8="";
ALL_OPTIONAL_COMPONENTS_8=""; SORTED_COMPONENTS_LIST_8="";
COMPONENT_FILTERS_LIST_8=""; COMP_NAMES_8=""; INIT_COMP_DETAILS_8=""
SOURCE_LIST_9="" ; SELECTED_KEYS_9=""; AVAILABLE_KEYS_9="";
ALL_OPTIONAL_COMPONENTS_9=""; SORTED_COMPONENTS_LIST_9="";
COMPONENT_FILTERS_LIST_9=""; COMP_NAMES_9=""; INIT_COMP_DETAILS_9=""
SOURCE_LIST_10="" ; SELECTED_KEYS_10=""; AVAILABLE_KEYS_10="";
ALL_OPTIONAL_COMPONENTS_10=""; SORTED_COMPONENTS_LIST_10="";
COMPONENT_FILTERS_LIST_10=""; COMP_NAMES_10=""; INIT_COMP_DETAILS_10=""
UNIQUE_SELECTED_KEYS=""
ALL_CDS=""

PROTO_FILE=""
RUNTIME_PKG=""

PATCHES_TO_ARCHIVE=""
ALL_AVAILABLE_PATCHES=""

SMARTUPDATE_COMPATIBLE_PRODUCTS=""
OS_FOR_AVAILABLE_KEYS=""
ALL_SUPPORTED_OS="2.6,7,8,9,10"
SELECTED_OS=""

REQUIRED_SPACE_FORARCHIVES=0
COMMON_PACKAGES=""

INSTALL_SCRIPTS_DIR=`/usr/bin/pkgparam SUNWescom BASEDIR`/SUNWsymon/lib/sbin

. ${SCRIPT_DIR}/es-common.sh
. ${TOOLS_DIR}/archive-tool-functions.sh
. ${TOOLS_DIR}/script-errors.sh
. ${TOOLS_DIR}/install-functions.sh

setInstallFlags
set_basedir


umask 022 
while getopts hs: OPT
do
	case $OPT in
		h) 
                        usage
			exit 0
			;;
		s)
			SPLIT_SIZE="$OPTARG"
			check_split_size
			;;
		*)
			usage
			exit 0
			;;
	esac
done

check_root
acquireLockForImageTool

check_server

setAPIDirs
API_CREATE_DOC="$API_DIR/createDocument" 
API_INSERT_TAG="$API_DIR/insertTag" 
API_SET_ATTRIBUTE="$API_DIR/setAttribute" 
API_QUERY_XML="$API_DIR/queryXml" 

checkOSVersion
set_commondirs

AGENT_ONLY=1
INSTALL_LAYERS="LAYER.AGENT"
INSTALL_TYPE="BASE"
BASE_PRODUCT_DIR="PE"
BASE_PRODUCT_KEY="PRODUCT.PE"
#LOCALE_CODE=C
#L10N_CODE=en
check_for_l10n

setArchiveLogdir "es-imagetool"
initializeRegistry 	# Required for install-functions

$CMD_CLEAR

$CMD_ECHO ''
echolog 'This script will help you to create distributable images of Sun \\(TM\\) Management Center software'
$CMD_ECHO ''

$CMD_ECHO " "
echolog 'The update-image can contain one or more of the following:'
$CMD_ECHO " "
echolog 'Base Agent Packages'
echolog 'Add-on Agent Packages'
echolog 'Agent Patches Only'
$CMD_ECHO " "
echolog 'Note: Required patches are automatically included with chosen packages'
echolog ' '
ask_user ' Do you want to upgrade components of Base Agent'
if [ $answer -eq 1 ]; then
    ARCHIVE_BASE_FLAG=1
    ARCHIVE_PATCHES_FLAG=1
fi
ask_user ' Do you want to install/upgrade components of Addons'
if [ $answer -eq 1 ]; then
    ARCHIVE_ADDON_FLAG=1
    ARCHIVE_PATCHES_FLAG=1
fi
if [ $ARCHIVE_PATCHES_FLAG -eq 0 ]; then
    ask_user ' Do you want to install Patches'
    if [ $answer -eq 1 ]; then
        ARCHIVE_PATCHES_FLAG=1
    fi
fi

BASE_PROD_ONLY=0
[ "$ARCHIVE_BASE_FLAG" = "1" ] && [ "$ARCHIVE_ADDON_FLAG" = "0" ] && BASE_PROD_ONLY=1
export BASE_PROD_ONLY
CALLED_FROM_GUI=0

checkOSVersion

[ "$ARCHIVE_BASE_FLAG" = "0" ] && [ "$ARCHIVE_ADDON_FLAG" = "0" ] && [ "$ARCHIVE_PATCHES_FLAG" = "0" ] && releaseImageToolLock && exit 0

if [ "$ARCHIVE_BASE_FLAG" = "0" -a "$ARCHIVE_ADDON_FLAG" = "0" ]; then
    echolog ' '
    echolog ' '
    multiline_echolog 'For patch only image creation, use the directory\nwhere the patches were downloaded to.'
    echolog ' '
    getPatchOnlySource
else
    echolog ' '
    echolog ' '
    multiline_echolog 'If you have the Sun Management Center installation CD,\nuse the image directory on the first CD\nIf you copied the CDs on your hard drive, use the path to disk1/image' 
    echolog ' '
    getSourceDirectory
    getSourceVersion
fi

while [ 1 -eq 1 ] ; do
    if [ "$ARCHIVE_BASE_FLAG" = "1" -a "$SOURCE_IMAGE" != "DEFAULT" ]; then
        # This means user said yes to base but base is not available in source
        echolog "Base Agent Packages not found in the specified location."
        echolog "Specify the source directory containing the Base Agent Packages."
        echo " " 
        SRC_DIR=""
        SOURCE_IMAGE="DEFAULT"    # reset,  otherwise this goes into loop
        getSourceDirectory
        getSourceVersion
        continue
    fi    

    if [ "$ARCHIVE_ADDON_FLAG" = "1" -a ! -d "$SRC_DIR/Addons" ]; then
        # This means user said yes to Addons but Addons not available in source
        echolog "Add-on Agent Packages not found in the specified location."
        echolog "Specify the source directory containing the Add-on Agent Packages."
        echo " " 
        SRC_DIR=""
        SOURCE_IMAGE="DEFAULT"    # reset,  otherwise this goes into loop
        getSourceDirectory
        getSourceVersion
        continue
    fi

    if [ "$SOURCE_IMAGE" = "PATCH_ONLY" ]; then
        detect_patch_arch
        
        if [ $? -ne 0 ]; then
            # This means the image contains patches for both sparc and x86
            echo ' '
            echo ' '
            echolog "The patch directory contains patches applicable to sparc and i386 platforms."
            echolog "The update image can have patches applicable to only one of the platforms."
            multiline_echolog "Create separate patch only directories for sparc and i386 patches \nand then create the update images."
            echo ' '
            echo ' '
            echolog 'For more details, See: $2' "$LOGFILE"
            echo ' '
            echo ' '
            exit 3
        fi
    fi
    break    
done

if [ "$ARCHIVE_BASE_FLAG" = "1" ]; then
    getRemoteTargetDirectory
    getLocales
else
    REMOTE_TARGET_DIR="/opt" ## If base product is not selected
			     ## this will be simply ignored.
fi

getSourceArchAndSetPathPrefix

getArchiveTargetDirectory

TARGET_ARCHIVE_DIR=$TARGET_DIR
SMART_UPDATE_DIR="$TARGET_ARCHIVE_DIR"
AUTOCONFIG_SAVEFILE=$SMART_UPDATE_DIR/tmpResponses.cfg

#createLink
#updateResponses
saveAutoConfig "TARGET_DIRECTORY" "$REMOTE_TARGET_DIR"
saveAutoConfig "SETUP_NOW" "0"
saveAutoConfig "PRESERVE_OLD_DATA" "1"
saveAutoConfig "RESPONSES_FOR_AGENT_UPDATE" "TRUE"
if [ "$ARCHIVE_BASE_FLAG" = "1" ]; then
    saveAutoConfig "INSTALL_LOCALES" "$INSTALL_LOCALES"
fi

#getPolicyFileNames
#updateBasePolicy

ALL_SUPPORTED_OS=`find_available_os_versions`
selectOSVersions

if [ "$SOURCE_IMAGE" = "PATCH_ONLY" ]; then
    $CMD_ECHO ' '
    echolog 'The source directory is a patch only directory.'
    echolog 'Making list of all available patches...'
    makeAvailablePatchesList		# Create a list of available patches
    getLastCD

    selectPatchesInteractively
    echolog 'Disk Space Checking ....'
    checkSpaceForPatches

    makeDirectories "PE"
    updateResponseForPatchOnly
    updateSetupResponseForNoBase "1"

    init_policy_file
    updatePolicyForBaseProduct
    update_protofile
    update_proto_for_client
    [ "$RUNTIME_PKG" != "DONE" ] && make_runtime_package
       
    echolog 'adding patches...'
    archiveEssentialPatches
    $CMD_ECHO   " " 
    echolog 'Image Tool logfile is : $2' "$LOGFILE"
    $CMD_ECHO   " " 
    echologverbose "$LOG_LINE"
    $CMD_ECHO   " " 
    echologverbose "$LOG_LINE"
    $CMD_ECHO   " "
    releaseImageToolLock
    exit 0
fi

makeDirectories "PE"

#askBaseLayer
getBaseResponseFileNames

findSmartUpdateCompatibleProducts

$CMD_ECHO "\n"

	AUTOCONFIG_RUNFILE=$AUTOCONFIG_SAVEFILE

	for OSVERS in `$CMD_ECHO "$SELECTED_OS" | $CMD_AWK -F ',' '{ for (i = 1; i<= NF; i++) print $i }'`
	do
		resetSourceList $OSVERS 	# restore source list for OS
		resetAvailableKeys $OSVERS	# restore available keys
		resetOptionalComponents $OSVERS
		resetComponentFiltersList $OSVERS
		resetCompNames $OSVERS
		resetInitCompDetails $OSVERS
		echolog 'Scanning Solaris_$2 directory of the source image' "$OSVERS"
		AGENT_ONLY=1
		INSTALL_LAYERS="LAYER.AGENT"
		if [ "$ARCHIVE_BASE_FLAG" = "1" ]; then
			INSTALL_TYPE="BASE"
			SOURCE_IMAGE="DEFAULT"
		else
			INSTALL_TYPE="ADDON"
			SOURCE_IMAGE="ADDON_ONLY"
		fi
		# scanSourceForAllProducts may change the value of OSVERS
		# check and restore value of the var if necessary after call
		# to the function		
                curr_os=$OSVERS
                scanSourceForAllProducts
                [ "$OSVERS" != "$curr_os" ] && OSVERS=${curr_os}

		setSourceList $OSVERS
		setComponentFiltersList $OSVERS
		setCompNames $OSVERS
		setInitCompDetails $OSVERS

		#echo "$SOURCE_LIST"
		setOptionalComponents $OSVERS

		listAllAvailableProducts

		setAvailableKeys $OSVERS
		setOSforAvailableProducts
	done

	UNIQ_AVAILABLE_KEYS=""
	UNIQ_OPTIONAL_COMPONENTS_LIST=""

	UNIQ_AVAILABLE_KEYS=`getUniqAvailableKeys`
	UNIQ_OPTIONAL_COMPONENTS_LIST=`getUniqOptionalComponents`

	AVAILABLE_KEYS="$UNIQ_AVAILABLE_KEYS"
	ALL_OPTIONAL_COMPONENTS="$UNIQ_OPTIONAL_COMPONENTS_LIST"

	#LAST_OS=`getLastOSonCD`
	checkOSVersion
	resetSourceList $OSVERS
	#OSVERS=$LAST_OS

	processProducts
	ARCHIVE_PRODUCT_SELECTION="DONE"

	setSelectedKeysFromUniqAvailableKeys

	check_empty_selectedlist

	if [ "$ARCHIVE_BASE_FLAG" = "1" ]; then
		askBaseSetupQuestions
	else
		updateSetupResponseForNoBase "1"
	fi

        init_policy_file
	updatePolicyForAddons
	askAddonSetupResponses
	createAddonDirectories

	echolog 'Preparing for image creation. Please wait...'

	for OSVERS in `$CMD_ECHO "$SELECTED_OS" | $CMD_AWK -F ',' '{ for (i = 1; i<= NF; i++) print $i }'`
	do
		resetSourceList $OSVERS 	# restore source list for OS
		resetAvailableKeys $OSVERS	# restore available keys
		resetOptionalComponents $OSVERS
		resetComponentFiltersList $OSVERS
		resetCompNames $OSVERS
		resetInitCompDetails $OSVERS
		AGENT_ONLY=1
		INSTALL_LAYERS="LAYER.AGENT"
		if [ "$ARCHIVE_BASE_FLAG" = "1" ]; then
			INSTALL_TYPE="BASE"
			SOURCE_IMAGE="DEFAULT"
		else
			INSTALL_TYPE="ADDON"
			SOURCE_IMAGE="ADDON_ONLY"
		fi

		processProducts			# Required to set other
						# variables such as 
						# REJECT_PACKAGE_LIST

		setSelectedKeys $OSVERS

		prepareForInstall

		setSourceList $OSVERS		# store modified source list
		setArchiveKeys $OSVERS 		# may not be required
		
		makeRequiredPatchesList		# Create a list of required
						# patches to be archived

		sortByCD			

		setSortedComponentsList $OSVERS 
	done



echolog 'Disk Space Checking ....'
checkSpaceForProducts
checkSpaceForPatches


#echo $RESPONSE_FILE_LIST

echolog 'Starting image creation...'
echolog '$2' "$SCREEN_LINE"
echolog ''

update_protofile
update_proto_for_client
updatePolicyForBaseProduct

if [ "$ARCHIVE_BASE_FLAG" = "1" ]; then
	echolog "adding base product"
	archiveBaseProduct
fi

echolog "adding Addons "
getAllCDs
updateSourceDirectories

AUTOCONFIG_SAVEFILE=""
AUTOCONFIG_RUNFILE=""

getLastCD

for each_cd in $ALL_CDS
do
        # 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 [ "$each_cd" != "1" ];then
                # check for disk image
                SRC_DIR="$SRC_DIR/${IMAGETOOL_PATHPREFIX}../../disk$each_cd/${IMAGETOOL_ARCHPREFIX}/image"
        fi
	if [ ! -d "$SRC_DIR" ]; then
            # The image path is probably from CDROM 

            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"
            fi

	    $CMD_ECHO ' '
	    echolog 'Cannot proceed without disk $2' "$each_cd"
            echolog 'Insert the next CD or enter the source directory path for disk $2' "$each_cd"
	    $CMD_ECHO ' '
	fi
        while [ 1 ]; do
            getSourceDirectory
            getSourceVersion
            checkSourceDirArch "$IMAGETOOL_ARCH"
            [ $? -eq 0 ] && break  # correct dir for the architecture
            SRC_DIR=""             # reset the SRC_DIR 
        done
        archiveAddons $each_cd
        [ "$RUNTIME_PKG" != "DONE" ] && make_runtime_package
done

echolog 'adding patches...'
archivePatches

$CMD_ECHO   " " 
echolog 'Image Tool logfile is : $2' "$LOGFILE"
$CMD_ECHO   " " 
echologverbose "$LOG_LINE"
$CMD_ECHO   " " 
echologverbose "$LOG_LINE"
$CMD_ECHO   " "

releaseImageToolLock
exit 0


