#!/bin/sh 
# Copyright 12/16/04 Sun Microsystems, Inc. All Rights Reserved.
# pragma ident  "@(#)uninst-functions.sh	1.97 04/12/16 Sun Microsystems"

# Prints usage for es-uninst
#
print_usage_uninst() {
    eval /usr/bin/echo "\"`/usr/bin/gettext  '  Usage: $PROGNAME [ -f | -F | -X  | -h | -v ] \n Where the options represent:\n' `\""
    /usr/bin/echo ""
    /usr/bin/gettext ' Default: User can  select from a list  of installed Addons which ones\n          he wishes to uninstall. The  selection will be processed for\n          dependencies. At this time, he  will also have the option of\n          selecting  the  base product,which will result in all Addons\n          also being uninstalled. \n'
    /usr/bin/echo ""
    /usr/bin/gettext ' -f:      Uninstall everything without asking for confirmation.\n'
    /usr/bin/echo ""
    /usr/bin/gettext ' -F:      Uninstall  everything  without  asking  for confirmation and\n          without  stopping  any running  Sun Management Center processes. This option\n          should  be used in a  situation where the executables called\n          while stopping  Sun Management Center processes are not  going to be present\n          where  expected.\n'
    /usr/bin/gettext '          For example, if  the OS has  been  upgraded\n          after Sun Management Center  was  installed, from  say 2.7 to 2.8, then some\n          dynamically generated  pathnames would be incorrect. In this\n          case, this option  would avoid  error being reported  during\n          uninstall.\n'
    /usr/bin/echo ""
    /usr/bin/gettext ' -X:      Complete Sun Management Center Cleanup.\n'
    /usr/bin/echo ""
    /usr/bin/gettext ' -h:      Prints this usage.'
    /usr/bin/echo ""
    /usr/bin/gettext ' -v:      Verbose mode.'
    /usr/bin/echo ""
    #
    # Other unpublished options are -p -X -r -g
    #
}

# Checks for argument & sets uninst flags accordingly
#
process_options_uninst() {
    
    # Sets uninst flags to default values
    #
    reset_flags_uninst

    
    if [ ! -z "$1" ]; then
        /usr/bin/echo "$@" | /usr/bin/grep "-" > /dev/null 2>&1
        [ $? -eq 1 ] && print_usage_uninst && exit_SunMC_uninstall "$ARGUMENTS_ERROR"
    
        arg_count=0       
        while getopts p:r:R:XFfghv OPT
        do
            case $OPT in
                X)  # This option is not visible to user
                    # This will remove all SunMC without Registry read
                    # This can be used when Registry file is courrupt.
                    #
                    remove_without_registry=1
                    arg_count=`/usr/bin/expr "$arg_count" + 1`
                    ;;

                F)
                    force_base_uninst=1
                    base_uninst=1
                    stop_components=0
                    arg_count=`/usr/bin/expr "$arg_count" + 1`
                    ;;

                f)  
                    force_base_uninst=1
                    base_uninst=1
                    stop_components=1
                    arg_count=`/usr/bin/expr "$arg_count" + 1`
                    ;;
                
                p)  # This option is not visible to user
                    # 
                    remove_addon_only=1
                    ADDON_KEY="$OPTARG"
                    arg_count=`/usr/bin/expr "$arg_count" + 1`
                    ;;

                r)
                    remove_addon_by_force=1
                    arg_count=`/usr/bin/expr "$arg_count" + 1`
                    ADDON_KEY="$OPTARG"
                    ;;
                
                R)  # This option is not visible to user
                    # 
                    remove_addon_by_force=1
                    ADDON_DIR="$OPTARG"
                    arg_count=`/usr/bin/expr "$arg_count" + 1`
                    ;;
      
                g)  # This option is not visible to user
                    # This will keep /var/opt/SUNWsymon/
                    #
                    keep_cfg=1
                    ;;
                h)
                    print_usage_uninst
                    exit "$NO_ERROR"
                    ;;

                v)  VERBOSE="ON"
                    ;;       
                *)   
                    print_usage_uninst
                    exit_SunMC_uninstall "$ARGUMENTS_ERROR"
                    ;;
            esac
        done
     
        if [ $arg_count -gt 1 ]; then
            /usr/bin/gettext "Only one option supported.\n"
            print_usage_uninst 
            exit_SunMC_uninstall "$ARGUMENTS_ERROR"
        fi  
    fi

    unset arg_count

}

# Sets all uninst flags to default value
# Input:None
# Returns : None
reset_flags_uninst() {

   force_base_uninst=0
   keep_cfg=0
   base_uninst=0
   stop_components=1
   remove_without_registry=0

   # Now other functions calling uninst can set it from outside.
   #
   [ -z "$Keep_Data" ] && Keep_Data=0
   
   export Keep_Data
   
   database_uninst_error=1
   failed_flag=0
   
   update_registry=0

   # In case -p option , this is set
   #
   remove_addon_only=0
   remove_addon_by_force=0
   EXIT_STATUS_UNINST=0
 
   registry_removed_flag=0
   SUNWesora_preserved=0

   # Database related flags
   #
   DB_CLEAN_EXPL="FALSE"
   DB_USER_EXIST="TRUE"
   DB_GROUP_EXIST="TRUE"
}

# Select products to uninstall 
# Returns : L_SURE : List of all products to uninstall
#
select_uninstall_todo() {

   if [ -z "$L_INSTALLED_PRODUCTS" ]; then
      echolog ''
      echolog 'Nothing to uninstall.'   
      exit_SunMC_uninstall "$BAD_INSTALLATION_ERROR"
   fi

   if [ $base_uninst -eq  0 -a $remove_addon_only -eq 0 -a $remove_addon_by_force -eq 0 ]; then

      #This may modify base_uninst also
      #
      ask_products_to_user

   else

      # This list will be later used to find product names when xml API's are not available to read Registry

      L_PRODUCT_NAMES=""
      for each_product in `$CMD_ECHO "$L_INSTALLED_PRODUCTS" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
      do
         tmp_str=`get_product_names "$each_product"`
         L_PRODUCT_NAMES="$L_PRODUCT_NAMES$each_product:$tmp_str,"
         tmp_str=`/usr/bin/echo $tmp_str | /usr/bin/cut -c 1-48 `
      done 

      # If this is addon_only uninstallation That is, -p option
      # Come up with valid PRODICUT IDS's in a list & process dependancies
      #
      if [ $remove_addon_only -eq 1 -o $remove_addon_by_force -eq 1 ]; then

         # Find Addon KEY ID from addon dir
         found_flag=0
         if [ -z "$ADDON_KEY" ] ; then
             for each_addon in `$CMD_ECHO "$L_INSTALLED_ADDONS" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`            
             do 
                temp_dir=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$each_addon" "target_subdir"  2> /dev/null `
                [ $? -gt 0 ] && exit_SunMC_uninstall "$REGISTRY_READ_ERROR"
               
                
                if [ "$temp_dir" = "$ADDON_DIR" ];then
                   L_SELECTED=$each_addon
                   found_flag=1
                   break
                fi
             done
         else
             for each_addon in `$CMD_ECHO "$L_INSTALLED_ADDONS" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`            
             do 
                if [ "$each_addon" = "$ADDON_KEY" ];then
                   L_SELECTED="$ADDON_KEY"
                   found_flag=1
                   break
                fi
             done
         fi
            
         if [ $found_flag -eq 0 ]; then
            echolog 'No such addon $2' "$ADDON_KEY $ADDON_DIR"
            exit_SunMC_uninstall  "$ADDON_DIR_ERROR"
         fi
        
         if [ $remove_addon_by_force -eq 1 ]; then
            L_SURE=$L_SELECTED
         else
            process_dependancies $L_SELECTED
            [ $? -gt 0 ] &&  exit_SunMC_uninstall "$DEPENDANCY_ERROR"
         fi
      else
         if [ "$force_base_uninst" = "1" ] ; then
            L_SURE="$L_INSTALLED_PRODUCTS"
         fi
      fi
   fi

   if [ $no_server -eq 0 -o $no_agent -eq 0 ] ; then # Only agent and server layer
      echolog '' 
      if [ "$Keep_Data" = "1" ]; then
         echolog 'Database will be Preserved.'
      else
         Keep_Data=1
         multiline_echolog 'Select Save Data to save all user and configuration data. Your data is\nsaved and can be restored when you re-install Sun Management Center.'
         ask_user "Do you want to preserve data "
         echolog ''
         [ $answer -eq 0 ] && Keep_Data=0
      fi
      export Keep_Data
   fi           
   
   if [ "$force_base_uninst" != "1" -a "$remove_addon_by_force" != "1" ] ; then
      ask_user 'Proceed with uninstall '
      echolog ''
      [ $answer -eq 0 ] && exit_SunMC_uninstall "$USER_ABORT_ERROR"
   fi

   # mark all products which are selected for uninstallation as not-setup in registry
   #
   #for each_product in  `$CMD_ECHO "$L_SURE" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
   #do
   #   if [ "$each_product" = "$BASE_PRODUCT" ] ; then
   #      # Mark all installed layers as unset         
   #      #
   #      for each_layer in `$CMD_ECHO "$L_BASE_INSTALLED_LAYERS" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
   #      do
   #         $API_SET_ATTRIBUTE "$REGISTRY" "category=Installation" "layer=$each_layer" "setup-status=0"  1> /dev/null 2>&1 
   #      done
   #   fi
   #   $API_SET_ATTRIBUTE "$REGISTRY" "category=SunMC" "product=$each_product" "setup-status=0"  1> /dev/null 2>&1
  #done

  # Now afterwords if programm is aborted, registry will be updated
  #
  update_registry=1

}

# Get a sorted list of packages to be uninstalled.
# Sorts by reverse timestamp
# Input : $1 = PKG_LIST  
# Returns : echos sorted list
#
sort_packages() {
      
    [ -z "$@" ] && return 
    
    #echolog ''
    echolog "Sorting list of packages according to reverse timestamp..."
    
    temp_info_list=""

    for each_pkg in `$CMD_ECHO $@ | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
    do
        temp_info_list="$temp_info_list /var/sadm/pkg/$each_pkg/pkginfo"
    done

    # Sort the file list using ls -t
    temp_sorted_list=`/usr/bin/ls -t $temp_info_list`

    #  Turn the file list back into a package list
    temp_pkg_list=""
              
    for each_file in `$CMD_ECHO "$temp_sorted_list" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
    do
        pkgname=`/usr/bin/echo $each_file | /usr/bin/cut -f5 -d\/`
        temp_pkg_list="$temp_pkg_list $pkgname"
    done
    
    L_PACKAGES_LEFT=$temp_pkg_list

    [ ! -z "$L_PACKAGES_LEFT" ] && echologverbose '$2Sorted list of packages in reverse timestamp order:$3' "\n" "$L_PACKAGES_LEFT"
   
    unset temp_pkg_list temp_info_list temp_sorted_list

    return  

}

# Stops all SunMC processes running. Also stops databse services
# Inputs : None
# Returns : None
#
stop_all_processes() {
   
   [ ! -n "$BASEDIR" ] && return

   /usr/bin/gettext "Stopping all Sun Management Center processes.  This may take a few moments...\n"
   #numproc=0
   #numproc=`/usr/bin/ps -aef | /usr/bin/grep "esd - init" | /usr/bin/grep -v "grep" | /usr/bin/wc -l`
   #if [ $numproc -gt 0 ] ; then
   #   [ -z "$JAVA_ERROR" ] && JAVA_ERROR=98
   $BASEDIR/sbin/es-stop -A
   # ret=$?
   # if [ "$ret" = "$JAVA_ERROR" ] ; then
   #    echolog 'Cannot continue with uninstall.'
   #    exit_SunMC_uninstall "$JAVA_ERROR" 
   # fi     
   #fi        

   # clean up Oracle and Java server processes if es-stop -A couln't do
   if [ $no_server -eq 0 ] ; then
      #Stop server
      #
      $BASEDIR/classes/base/server/bin/es-server-stop.sh

      # stop database
      #
      get_lsnr_and_ora_proc_count
      if [ $lcnt -gt 0 -o $scnt -gt 0 ]; then
         prstring=`$ESROOT/base/bin/sparc-sun-solaris${OSVERS}/smcpwchk $SMCORAU 2>/dev/null`
         retcode=$?
         if [ $retcode = 2 ]; then
            echolog 'the user $2 was not found by a getpwnam system call ,not in /etc/passwd, nis, nis+, etc..' "$SMCORAU"
            DB_CLEAN_EXPL="TRUE"
         fi
         grstring=`$ESROOT/base/bin/sparc-sun-solaris${OSVERS}/smcgrchk $SMCORAG 2>/dev/null`
         retcode=$?
         if [ $retcode = 2 ]; then
            echolog 'the group $2 was not found by a getgrnam system call ,not in /etc/group, nis, nis+, etc..' "$SMCORAG"
            DB_CLEAN_EXPL="TRUE" 
         fi

         if [ ! -f $BASEDIR/sbin/db-stop ]; then
            DB_CLEAN_EXPL="TRUE"
         fi

         if [ "$DB_CLEAN_EXPL" = "FALSE" ]; then
            su - $SMCORAU -c $BASEDIR/sbin/db-stop
         fi

         #  Confirm that the db and listener are down
         #
	 get_lsnr_and_ora_proc_count
         if [ $lcnt -gt 0 -o $scnt -gt 0 ]; then
            # explicit killing
            #
            DB_CLEAN_EXPL="TRUE"
         fi

         if [ "$DB_CLEAN_EXPL" = "TRUE" ]; then

            # forcefully kill Sun Management Center database processes
            echolog ""
            echolog "Need to forcefully kill the database processes, please wait"
            echolog ""
             
            kill_ora_processes
             
            # if both "$SMCORAU" and "$SMCORAG" are not found shared memory and semaphores will remain
            #
            release_shm_sems "$SMCORAU" "$SMCORAG"
         fi
      fi
      	       	  
      # Stop any scheduled discovery request
      #
      kill_processes "discover"
  fi
        
}


# Processes (DIRECT / INDIRECT dependances & informs user accordingly
# Input   : $1 => list of products selected by user for uninstallation.
# Returns : - L_SURE filtered out product list which can be uninstalled
#           - L_REJECT List of rejected products because of dependancies
#           - L_CONFLICT List of dependant products because of which L_REJECT can 
#             can not be uninstalled     
#
process_dependancies () {

   L_DEPENDANT=""
   L_REJECT=""
   L_CONFLICT=""
   L_SURE=""
   
   for each_product in `$CMD_ECHO $@ | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
   do

      #Find recursively all dependacies in depth of tree.
      #
      L_DEPENDANT=`get_dependant_products "$each_product" `

      L_TEMP=""
      while [ "$L_TEMP" != "$L_DEPENDANT" ]
      do         
         L_TEMP="$L_DEPENDANT"
         
         for each_dependant in `$CMD_ECHO "$L_DEPENDANT" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
         do

            L_TEMP2=`get_dependant_products "$each_dependant" `

            for each_temp in `$CMD_ECHO "$L_TEMP2" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
            do  
               /usr/bin/echo $L_DEPENDANT | /usr/bin/grep $each_temp > /dev/null
               if [ $? -gt 0 ] ; then
                  L_DEPENDANT="$L_DEPENDANT $each_temp"
               fi
            done
         done
      done

      prod_reject=0

      for each_dependant in `$CMD_ECHO "$L_DEPENDANT" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
      do
         /usr/bin/echo $L_REJECT | /usr/bin/grep $each_dependant > /dev/null
         if [ $? -eq 0 ]; then
            [ $? -gt 0 ] && L_REJECT="$L_REJECT $each_product"
            prod_reject=1   
         else
            /usr/bin/echo $@ | /usr/bin/grep $each_dependant > /dev/null
            if [ $? -gt 0 ]; then
               /usr/bin/echo $L_CONFLICT | /usr/bin/grep $each_dependant > /dev/null
               [ $? -gt 0 ] && L_CONFLICT="$L_CONFLICT $each_dependant"
               /usr/bin/echo $L_REJECT | /usr/bin/grep $each_product > /dev/null
               [ $? -gt 0 ] && L_REJECT="$L_REJECT $each_product"
               prod_reject=1   
            fi
         fi

      done
          
      if [ $prod_reject -eq = 0 ]; then
         L_SURE="$L_SURE $each_product"
      fi
       
   done
           
   if [ "$L_REJECT" ] ; then
      echolog ''
      echolog 'Product[s] $2 can not be uninstalled because of dependancies in $3.' "`get_product_names "$L_REJECT"`" "`get_product_names "$L_CONFLICT"`"
   fi

   echolog ''
   if [ "$L_SURE" ] ; then
      echolog 'The following product[s] will be removed:$2$3.' "\n" "`get_product_names "$L_SURE"`"
   else
      echolog 'Nothing to uninstall.'
   fi

   [ "$L_REJECT" ] && return 1

   return 0

}


# Presents user list of all installed products
# Offers user to select from this list
#   In case user selects base product to uninstall, sets base_uninst & returns
#      list of all installed products
#      Otherwise, returns a list of selected products to uninstall
# Also processes (DIRECT / INDIRECT dependances & informs user accordingly
# Returns : A final list of selected ptoducts to uninstall L_SURE => "PROD1 PROD4.."
#
ask_products_to_user() {
   answer=1
   while [ $answer -gt 0 ]
   do
   
      #Display Avialable Products

      echolog '' 
      echolog 'Following Sun Management Center Products are installed:'
      echolog '-------------------------------------------------------------------------------'
      echolog ' PRODUCT $2 DEPENDENT PRODUCTS' "\r\t\t\t\t\t\t"
      echolog '-------------------------------------------------------------------------------'
      L_PRODUCT_NAMES=""
      for each_product in `$CMD_ECHO "$L_INSTALLED_PRODUCTS" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
      do
         #Find dependant products from registry 
         
         L_DEPENDANT=`get_dependant_products "$each_product" `
         
         tmp_str=`get_product_names "$each_product"`     
         
         # This list will be latter used to find product names when xml API's are not available to read Registry.
         #
         L_PRODUCT_NAMES="$L_PRODUCT_NAMES$each_product:$tmp_str,"
         
         tmp_str=`/usr/bin/echo $tmp_str | /usr/bin/cut -c 1-48 `

         if [ "$each_product" != "PRODUCT.PE" ] ; then
            [ ! "$L_DEPENDANT" ] && 
            if [ ! "$L_DEPENDANT" ]; then
                tmp_localized_text=`/usr/bin/gettext "None" 2> /dev/null `
                tmp_str="$tmp_str\r\t\t\t\t\t\t $tmp_localized_text\t"
            fi
         else
            if [ ! -z "$L_INSTALLED_ADDONS" ]; then
               tmp_localized_text=`/usr/bin/gettext "All Addons" 2> /dev/null `
               tmp_str="$tmp_str\r\t\t\t\t\t\t $tmp_localized_text\t"
            else
               tmp_localized_text=`/usr/bin/gettext "None" 2> /dev/null `
               tmp_str="$tmp_str\r\t\t\t\t\t\t $tmp_localized_text\t"
            fi
         fi
        
         for each_dependant in `$CMD_ECHO "$L_DEPENDANT" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
         do 
            tmp_str="$tmp_str\r\t\t\t\t\t\t `get_product_names "$each_dependant"`\n"
         done
         echolog '$2' "$tmp_str"
      
     done

      echolog ''
      echolog ''
      base_uninst=0
      L_SELECTED=""

      for each_product in `$CMD_ECHO "$L_INSTALLED_PRODUCTS" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
      do
         ask_user 'Do you want to uninstall $2 ' "`get_product_names "$each_product"`"
         if [ $answer -eq 1 ]; then
              
            L_SELECTED="$L_SELECTED $each_product"

            if [ "$each_product" = "$BASE_PRODUCT" ]; then
               echolog ''
               echolog 'This will uninstall ALL Sun Management Center Products. !!!'
               base_uninst=1
               stop_components=1
               L_SURE=$L_INSTALLED_PRODUCTS
               break
            fi
         fi
      done
     
      if [ $base_uninst -eq 0 ]; then
         process_dependancies $L_SELECTED
      fi    
  
      echolog ''
  
      answer=0
      [ ! -z "$L_INSTALLED_PRODUCTS" ] && ask_user "Do you want to change selection "
  
      #echolog ''

      if [ $answer -eq 0 -a ! "$L_SURE" ] ; then
         echolog ''
         echolog 'Nothing selected for uninstall.'
         exit_SunMC_uninstall "$NO_ERROR"
      fi
   done        
   
   unset L_CONFLICT L_REJECT L_DEPENDANT L_TEMP prod_reject 

}


# Please do not insert tabs/white spaces in this function
# This creates ADMIN file for pkgrm
# Input: None
# Returns : Creates file  ${TMP_DIR}/adminfile<PID>
# NOTE: Please do not change/insert white spaces in this function.
#
make_admin_file() {
ADMIN=${TMP_DIR}/adminfile$$
cat << !EOF > $ADMIN
mail=
instance=overwrite
partial=nocheck
runlevel=nocheck
idepend=nocheck
rdepend=nocheck
space=nocheck
setuid=nocheck
conflict=nochange
action=nocheck
basedir=default
!EOF
} 
  
# remove any crontab entry added by Sun MC
# Input: none
# Returns : none
#
remove_crontab_entries() {

   echologverbose 'Removing cronjobs set by Sun Management Center.'

   TMPCRONTAB=/tmp/crontab$$

   if [ -f ${TMPCRONTAB} ]; then
      /usr/bin/rm -f ${TMPCRONTAB} 
   fi

   # is the crontab file populated for this user?
   /usr/bin/crontab -l 1>/dev/null 2>/dev/null
   if [ $? -eq 0 ]; then
      # if removal of every entry in the crontab file that references the
      # generate-analyze-table script would make the crontab file empty, then remove
      # the crontab file outright
      if [ -z "`/usr/bin/crontab -l | /usr/bin/grep -v generate-analyze-table`" ]; then
         /usr/bin/crontab -r
      else
         # remove any crontab entry added by Sun MC, and leave behind any entries made
         # from elsewhere
         /usr/bin/crontab -l | /usr/bin/grep -v generate-analyze-table > $TMPCRONTAB
         cat $TMPCRONTAB | /usr/bin/crontab
      fi
   fi

   # ensure its gone
   if [ -f ${TMPCRONTAB} ]; then
      /usr/bin/rm -f ${TMPCRONTAB} 
   fi
}

# Gets list of all packages to be uninstalled - from registry
# This also REMOVES product entry from REGISTRY
# Input : $1 => L_SURE : a list of products to be uninstalled
# Returns :  1. echos L_PACKAGES => "package1 package2 ..."
#            2. L_PROD_PACKAGE => "PROD1:package1 PROD1:package2 PROD2:package3..."
#            3. L_PACKAGES_REMOVED => packages which r in registry but not on system
get_packages () {
   
   echolog "Making list of packages to uninstall..."
   
   L_PACKAGES_LEFT=""
   L_PROD_PACKAGE=""

   
   for each_product in `$CMD_ECHO $@ | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
   do   
      
      $API_SET_ATTRIBUTE "$REGISTRY" "category=SunMC" "product=$each_product" "setup-status=0" 1> /dev/null 2>&1
      
      temp_list=""

      L_COMPONENTS=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$each_product" "component" "key" 2> /dev/null `
      [ $? -gt 0 ] && exit_SunMC_uninstall "$REGISTRY_READ_ERROR"
        
      L_COMPONENTS=`/usr/bin/echo $L_COMPONENTS | /usr/bin/sed "s/,/ /g" `

      for each_component in `$CMD_ECHO "$L_COMPONENTS" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
      do
         temp_list2=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$each_product" "component=$each_component" "package" "key" 2> /dev/null `
         [ $? -gt 0 ] && exit_SunMC_uninstall "$REGISTRY_READ_ERROR"
         
         # Mark each package as a failed one in registry
         #
         for each_package in `$CMD_ECHO "$temp_list2" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
         do
            
            $API_SET_ATTRIBUTE "$REGISTRY" "category=SunMC" "product=$each_product" "component=$each_component" "package=$each_package" "status=0" 1> /dev/null 2>&1
            [ $? -gt 0 ] && exit_SunMC "$REGISTRY_WRITE_ERROR"
               
            # Find if package exitst on system if not, discard it from list
            /usr/bin/pkginfo -q $each_package
            if [ $? -gt 0 ] ; then #package does not exist at all
               L_PACKAGES_REMOVED="$L_PACKAGES_REMOVED $each_package"
            fi               
          
         done

         temp_list="$temp_list,$temp_list2"
      done

      # Get Database packages if base products is to be uninstalled
      #
      if [ "$each_product" = "$BASE_PRODUCT" ] ; then
         temp_list2=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "database_package" "key" 2> /dev/null `
         if [ ! -z "$temp_list2" ]; then
            for each_package in `$CMD_ECHO "$temp_list2" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
            do
               $API_SET_ATTRIBUTE "$REGISTRY" "category=Installation" "database_package=$each_package" "status=0" 1> /dev/null 2>&1
               [ $? -gt 0 ] && exit_SunMC "$REGISTRY_WRITE_ERROR"
               
               # Find if package exitst on system if not, discard it from list
               /usr/bin/pkginfo -q $each_package
               if [ $? -gt 0 ] ; then #package does not exist at all
                  L_PACKAGES_REMOVED="$L_PACKAGES_REMOVED $each_package"
               fi               
            done
            temp_list="$temp_list,$temp_list2"
         fi
      fi

      L_PROD_PACKAGE="$L_PROD_PACKAGE $each_product:$temp_list"
      L_PROD_PACKAGE=`/usr/bin/echo $L_PROD_PACKAGE | /usr/bin/sed "s/:,/:/g" `
      
      temp_list=`/usr/bin/echo $temp_list | /usr/bin/sed "s/,/ /g" `
      L_PACKAGES_LEFT="$L_PACKAGES_LEFT $temp_list"

   done
   
   # Remove repete packages in L_PACKAGES_LEFT
   #

   L_PACKAGES_LEFT=`/usr/bin/echo $L_PACKAGES_LEFT | /usr/bin/sed "s/ /,/g" `
   L_PACKAGES_LEFT="$L_PACKAGES_LEFT,@"
   for each_package in `$CMD_ECHO "$L_PACKAGES_LEFT" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
   do
     L_PACKAGES_LEFT=`/usr/bin/echo $L_PACKAGES_LEFT | /usr/bin/sed "s/$each_package,/###/" `       
     L_PACKAGES_LEFT=`/usr/bin/echo $L_PACKAGES_LEFT | /usr/bin/sed "s/$each_package,//g" `       
     L_PACKAGES_LEFT=`/usr/bin/echo $L_PACKAGES_LEFT | /usr/bin/sed "s/###/$each_package,/" `
   done
   L_PACKAGES_LEFT=`/usr/bin/echo $L_PACKAGES_LEFT | /usr/bin/sed "s/@//" `
   L_PACKAGES_LEFT=`/usr/bin/echo $L_PACKAGES_LEFT | /usr/bin/sed "s/,/ /g" `
   
   # Remove the packages from L_PACKAGES_LEFT which are not on the system 
   #
   for each_package in `$CMD_ECHO "$L_PACKAGES_REMOVED" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
   do
     L_PACKAGES_LEFT=`/usr/bin/echo $L_PACKAGES_LEFT | /usr/bin/sed "s/$each_package//" `
   done
   
   [ ! -z "$L_PACKAGES_LEFT" ] && echologverbose '$2The following packages will be removed:$3' "\n" "$L_PACKAGES_LEFT"
   
   [ ! -z "$L_PACKAGES_REMOVED" ] && echologverbose '"\n"The following packages have already been removed :$2' "$L_PACKAGES_REMOVED"
   
   
   
   unset P_PACKS L_COMPONENTS temp_list 

}


# Remove packages from sorted list L_PACKAGES_LEFT
# GO ON removing untill we can remove. Stop when none of package in a list can be removed.
# Input: Reads packages from L_PACKAGES_LEFT
# Returns : - Delets packages uninstalled from L_PACKAGES_LEFT. 
#           - At the end, L_PACKAGES_LEFT contain failed packages
#           - Also sets orabasedir & tblbasedir in case database is to be removed.
#           - addos removed package to the list L_PACKAGES_REMOVED
#
remove_packages() {

   # Admion file for pkgrm
   #
   make_admin_file
   
   # move to the root
   #
   cd /
   
   orabasedir=""
   tblbasedir=""

   #L_PACKAGES_REMOVED=""

   continue_flag=1 
   package_count=1 
   failed_flag=0
   uninst_flag=1
   while [ $continue_flag -eq 1 ]
   do         
      if [ $package_count -eq 1 ]; then
         fresh_flag=1
         packages_left=`/usr/bin/echo $L_PACKAGES_LEFT | wc -w`
         continue_flag=1
         stop_flag=1
      fi
   
      # Fetch n'th package
      #
      uninst_package=`/usr/bin/echo $L_PACKAGES_LEFT | /usr/bin/cut -d" " -f$package_count `
      [ -z "$uninst_package" ] && break
      
      # find orabasedir 
      #
      if [ "$uninst_package" != "SUNWestbl" ]; then
         uninst_flag=1
         if [ "$uninst_package" = "SUNWesora" ]; then
            orabasedir=`/usr/bin/pkgparam -f /var/sadm/pkg/SUNWesora/pkginfo BASEDIR`
            get_dependent_pkgs "SUNWesora"
            if [ -z "$dependent_pkgs" ] ; then
               uninst_flag=1
            else
               echolog 'Few packages dependant on SUNWesora found.'
               echolog 'Preserving SUNWesora package...'
               L_PACKAGES_LEFT=`/usr/bin/echo $L_PACKAGES_LEFT | sed s/$uninst_package//`
               packages_left=`/usr/bin/expr $packages_left - 1`
               SUNWesora_preserved=1
               uninst_flag=0
            fi
         fi
      else
         # Always remove SUNWestbl; data should have been exported by now
         tblbasedir=`/usr/bin/pkgparam -f /var/sadm/pkg/SUNWestbl/pkginfo BASEDIR`
         uninst_flag=1
      fi
   
      # Attempt removal
      #
      if [ $uninst_flag -eq 1 ]; then
         echolog ''
         echolog 'Removing package : $2...' "$uninst_package"
         /usr/sbin/pkgrm $rm_options -a $ADMIN $uninst_package
         if [ $? -eq 0 ]; then
            L_PACKAGES_LEFT=`/usr/bin/echo $L_PACKAGES_LEFT | /usr/bin/sed s/$uninst_package//`
            L_PACKAGES_REMOVED="$L_PACKAGES_REMOVED $uninst_package"
            packages_left=`/usr/bin/expr $packages_left - 1`
            stop_flag=0
         else
            package_count=`/usr/bin/expr $package_count + 1`
            failed_flag=1
            EXIT_STATUS_UNINST="$PKGRM_ERROR"
         fi
      fi
      
      # Decide if another attempt to remove packages in a list should be made or not
      #
      if [ $package_count -gt $packages_left ] ; then
         if [ $stop_flag -gt 0 ]; then
            continue_flag=0
         else
            package_count=1       
         fi
      fi
   
   done

   # Remove admin file created for pkgrm
   #
   /usr/bin/rm -f $ADMIN

   unset continue_flag package_count fresh_flag stop_flag package_count packages_left

}

# Removes database if Keep_Data flag is reset & none of the packages 
# in unins list failed $failed_flag=0
# If Keep_Data is set then removes only log files
# Input:None
# Output: Return state of database uninst
#
remove_database() {

   # Remove database if and only if all packages uninstalled completely. i.e. failed_flag=$2=0
   #
   if [ "$2" = "0" ]; then

      [ "$no_server" = "0" -a "$Keep_Data" != "1" ] && echolog '$2Database not preserved, deleting...' "\n"

      ORATABLOC=/var/opt/oracle
      ORATAB=${ORATABLOC}/oratab
      TMPORATB=/var/tmp/oratab$$ 
   
      if [ -f ${TMPORATB} ]; then
         /usr/bin/rm -f ${TMPORATB} 2>/dev/null
      fi

      # Make sure an oratab file exists on this system
      #
      if [ -s ${ORATAB} ];then
	 # Neither permissions nor ownership on the oratab files need to be changed.
         #/usr/bin/chown $ORACLE_OWNER ${ORATAB}
         #/usr/bin/chmod 664 ${ORATAB}

         # If an entry exists in $ORATAB for this $ORACLE_HOME, delete it 
         #
         FOUND_OLD=`/usr/bin/grep "^[^#]*:${ORACLE_HOME}:" ${ORATAB}`

         if [ -n "${FOUND_OLD}" ];then
            # if removal of SunMC entry from the oratab file will make it empty,
            # then remove the oratab file itself
            oratab_cnt=`/usr/bin/cat ${ORATAB} | /usr/bin/grep -v "^[^#]*:${ORACLE_HOME}:" | /usr/bin/grep -v "^[#]"`
            if [ -z "$oratab_cnt" ]; then
               /usr/bin/rm -f ${ORATAB} 2>/dev/null
               if [ -d "$ORATABLOC" ]; then
                  oracle_cnt=`/usr/bin/ls -1 "$ORATABLOC"|/usr/bin/wc -l`
                  if [ $oracle_cnt -eq 0 ] ; then
                     /usr/bin/rm -rf $ORATABLOC 2>/dev/null
                  fi
               fi
            else
               /usr/bin/cat ${ORATAB} | /usr/bin/grep -v "^[^#]*:${ORACLE_HOME}:" | /usr/bin/grep -v "^[#]" > $TMPORATB
               /usr/bin/cat $TMPORATB > $ORATAB
               /usr/bin/rm -f $TMPORATB 2>/dev/null
            fi
         fi 
      fi
 

      # if SUNWestbl package is installed in a different location
      # then clean that up as well
      #
      if [ -n "$tblbasedir" -a -d "$tblbasedir" ]; then
          /usr/bin/rm -rf $tblbasedir/db > /dev/null 2>&1
       
         if [ "$tblbasedir" != "/var/opt/SUNWsymon" ]; then
            /usr/bin/rmdir $tblbasedir > /dev/null 2>&1
            # The above line is to attempt removal of $tblbasedir directory, if empty 
         fi
         
      fi
      


      if [ "$Keep_Data" -ne 1 ] ; then

         # Please do not delete this. This is required when
         # gui calls post uninstall. These variabes are undefined for such case
         [ -z "$SMCORAU" ] && SMCORAU="smcorau"
         [ -z "$SMCORAG" ] && SMCORAG="smcorag"

         #  Delete Oracle Admin User and Group
         #
         verifyDeleteOracleUser $SMCORAU 
         ret_code=$?
         if [ $ret_code != 0 ]; then
            echolog "Execution of verifyDeleteOracleUser failed."
            return $ret_code
         fi

         groupid=""
         verifyDeleteOracleGroup $SMCORAG 
         ret_code=$?
         if [ $ret_code != 0 ]; then
            echolog "Execution of verifyDeleteOracleUser failed."
         fi

      fi

      # Ensure we cleanup any oracle related sql and log files
      # used by the smcorau user
      #
      remove_sql_log_files	       	  
      /usr/bin/rm -f ${TMP_SMC_DB_LOGS}/make.log
      /usr/bin/rm -rf ${TMP_DIR}/smcdb_db*
      /usr/bin/rm -rf ${TMP_SMC_DB_LOGS}/sunmclog
      /usr/bin/rm -rf ${TMP_SMC_DB_LOGS}/catoutu.log* 
      /usr/bin/rm -rf /tmp/clntst8.* > /dev/null 2>&1
   fi
   return $ret_code

}

# Removes files created by SunMC in /var/opt/SUNWsymon/....
# Preserves /VAROPTDIR/cfg if keep_cfg flag is set
# Preserves $VAROPTDIR/db if database is not uninstalled correctly
#
remove_var_dir () {
   
   # Remove agent setup dir in case of HA
   #
   if [ "$remove_without_registry" != "1" ]; then
      AGENT_ESDIR=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "layer=LAYER.AGENT" "agent-cfg-dir" 2> /dev/null `
      [ $? -eq 0 ] && [ -d "$AGENT_ESDIR" ] && /usr/bin/rm -rf "$AGENT_ESDIR"
   fi   
     
   [ -z "$VAROPTDIR" ] && VAROPTDIR="/var/opt/SUNWsymon"
   [ ! -d "$VAROPTDIR" ] && return 1
   
   # delete_list contains all directories/files in VAROPTDIR
   #
   delete_list=`/usr/bin/ls $VAROPTDIR`
   
   # Filter out install as we need to preserve log files
   #
   delete_list=`/usr/bin/echo $delete_list | /usr/bin/sed "s/install//"`

   # Filter out VAROPTDIR/cfg from delete_list if keep_cfg flag is set
   #   
   if [ "$keep_cfg" = "1" ]; then
      echolog '' 
      /usr/bin/echo $delete_list | /usr/bin/grep "cfg" > /dev/null
      if [ $? -eq 0 ]; then
         delete_list=`/usr/bin/echo $delete_list | /usr/bin/sed "s/cfg//" `
         echolog 'Preserving $2/cfg/' "$VAROPTDIR"
      else
         echologverbose '$2/cfg/ not found.' "$VAROPTDIR"
      fi
   fi
   
   # If database is to be preserved or error occured while uninstalling it,
   # then filter out db from delete list
   #
   if [ "$Keep_Data" = "1" -o $database_uninst_error -gt 0 ]; then
      echolog '' 
      /usr/bin/echo $delete_list | /usr/bin/grep "db" > /dev/null
      if [ $? -eq 0 ]; then
         delete_list=`/usr/bin/echo $delete_list | /usr/bin/sed "s/db//"`
         echolog 'Preserving $2/db/' "$VAROPTDIR"
      else
         echologverbose '$2/db/ not found.' "$VAROPTDIR"
      fi
   fi
  
   # remove symbolic links
   #
   if [ -h $VAROPTDIR/db ]; then
       /usr/bin/rm -rf $VAROPTDIR/db >/dev/null 2>&1
   fi

   # Issue rm command for all directories except those which are to be preserved
   #
   for each_item in $delete_list
   do
      del_item="/var/opt/SUNWsymon/$each_item"
      echologverbose 'Removing $2' "$del_item"
      /usr/bin/rm -rf $del_item
   done
   
   unset last_dir delete_list del_item
   
}



# Report a uninstall status to user.
# Productwise list of all Uninstalled/Failed packages
# Ask user to remove failed packages manually.
#
display_uninst_status() {

   [ -z "$L_PROD_PACKAGE" ] && return
   
   echolog '' 
   echolog 'Status of uninstallation:'
   echolog '-------------------------------------------------------------------------------'
   
   if [ -z "$L_PACKAGES_LEFT" ] ; then
      echolog 'PRODUCT$2  STATUS' "\r\t\t\t\t\t\t\t"
   else 
      echolog 'PRODUCT$2  STATUS$3 FAILED PACKAGES' "\r\t\t\t\t\t" "\r\t\t\t\t\t\t"
   fi
   echolog '-------------------------------------------------------------------------------'

   for each_item in `$CMD_ECHO "$L_PROD_PACKAGE" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
   do
      temp_product=`/usr/bin/echo $each_item | /usr/bin/cut -d: -f1 `
      temp_str=""
      temp_packages=`/usr/bin/echo $each_item | /usr/bin/cut -d: -f2 `
      temp_packages=`/usr/bin/echo $temp_packages | /usr/bin/sed "s/,/ /g"`
      failed_flag=0
      temp_count=1

      for each_package in `$CMD_ECHO "$temp_packages" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
      do
         /usr/bin/echo $L_PACKAGES_LEFT | /usr/bin/grep $each_package > /dev/null
         if [ $? -eq 0 ] ; then
            failed_flag=1
            /usr/bin/echo $temp_str | /usr/bin/grep $each_package > /dev/null
            if [ $? -gt 0 ]; then
               if [ $temp_count -gt 2 ]; then
                  temp_str="$temp_str\n\t\t\t\t\t\t $each_package"
                  temp_count=1
               else
                  temp_str="$temp_str $each_package"
                  temp_count=`/usr/bin/expr "$temp_count" + 1`
               fi
            fi
         fi 
      done

      if [ $failed_flag -eq 0 ]; then
         temp_prod_name=`get_product_names_from_list "$temp_product"`
         temp_prod_name=`/usr/bin/echo $temp_prod_name | /usr/bin/cut -c 1-56 `
         echolog '$2 $3 Removed' "$temp_prod_name" "\r\t\t\t\t\t\t\t"
         #
      else
         echolog '$2$3 Failed $4 $5' "`get_product_names_from_list "$temp_product"`" "\r\t\t\t\t\t" "\r\t\t\t\t\t\t" "$temp_str"
      fi
   done
   
   if [ "$SUNWesora_preserved" = "1" ]; then
      echolog ''
      echolog 'Following packages are dependent on SUNWesora:$2' "$dependent_pkgs"
      echolog 'SUNWesora package preserved because these package level dependencies.'
      echolog 'Remove this package manually if required.' 
   fi
   
   if [ ! -z "$L_PACKAGES_LEFT" ] ; then
      echolog ''
      echolog 'You must remove failed packages manually.'
   fi
   
   echolog ''

   #[ ! -z "$LOGFILE" ] && echolog 'Uninstall logfile is : $2 ' "$LOGFILE"

}

#
# $1 - Product ID
# This function should be used to find product names when xml API's are not installed
# OR registry is not available.
# This returns product names from a list which is stored before uninstall of actual packgaes
#
get_product_names_from_list() {
   [ -z "$1" ] && return 1
   # put temp crets in a list
   tmp_l_prod_names=` /usr/bin/echo "$L_PRODUCT_NAMES" | /usr/bin/sed "s/ /_/g" 2> /dev/null `
   for each_record in `$CMD_ECHO "$tmp_l_prod_names" | $CMD_AWK -F',' '{ for (i = 1; i <= NF; i++) print $i }'`
   do
      tmp_prod_key=`/usr/bin/echo $each_record | /usr/bin/cut -f1 -d: 2> /dev/null  `
      tmp_prod_name=`/usr/bin/echo "$each_record" | /usr/bin/cut -f2 -d":" 2> /dev/null `
      tmp_prod_name=`/usr/bin/echo "$tmp_prod_name" |  /usr/bin/sed "s/_/ /g" 2> /dev/null `
      if [ "$tmp_prod_key" = "$1" ]; then
         if [ ! -z "$tmp_prod_name" ] ; then
             /usr/bin/echo "$tmp_prod_name"
             unset tmp_l_prod_names tmp_prod_key tmp_prod_name
             return 0
         else
             /usr/bin/echo "$1"
             unset tmp_l_prod_names tmp_prod_key tmp_prod_name
             return 1
         fi
      fi
   done       
   /usr/bin/echo "$1"
   unset tmp_l_prod_names tmp_prod_key tmp_prod_name
   return 1
}


set_uninst_environment() {

   # To ensure that \r\t works on telnet
   #
   /usr/bin/stty tabs > /dev/null 2>&1 # Should not give error when called from wrappers
   [ -x /usr/bin/tabs ] && /usr/bin/tabs -8
   
   # This sets BASEDIR,VAROPTDIR,CONFIGDIR,SYMONHOME etc...
   #
   set_basedir 

   # Since uninstall doesn't need to support
   # any relocation stuff call the temporary
   # directory functions with blank parameters.

   remove_temp_directory

   # Ensure directory is available
   #
   create_temp_directory 

   /usr/bin/clear
   HOST=`/usr/bin/hostname`
   # Set a trap - in case user aborts..

   # Ensure that script is called by superuser
   #
   check_root

   # Initialize Registry
   #
   initializeRegistry

   #In case of relocated script source...
   set_commondirs
  
  
   # Set OS parameters required for pkgrm
   check_osver
   rm_options=" -n"

   #This creates log file uninstall.PID.... 
   #
   check_logfile "uninstall"

   # Initialize Registry first
   #
   #initializeRegistry

   # Find what is installed & what is setup 
   #
   get_SunMC_install_status

   echolog ''
   echolog 'This script will help you to uninstall the Sun Management Center software.'
   echolog ''

}

clean_SunMC () {
   
   # Ensure that script is called by superuser
   #
   check_root

   Keep_Data=0
   failed_flag=0
   base_uninst=1
   stop_components=1
   no_console=1
   no_server=1
   no_agent=1
   no_HA=1
   L_SURE=""

   [ -z "$VAROPTDIR" ] && VAROPTDIR="/var/opt/SUNWsymon"
   [ -z "$VARDIR" ] && VARDIR=$VAROPTDIR/cfg
   /usr/bin/pkginfo -qi SUNWescom
   if [ $? -eq 1 ];then
      BASEDIR="/opt/SUNWsymon"
   else
      BASEDIR=`/usr/bin/pkginfo -r SUNWescom`/SUNWsymon
   fi

   # Required in case of HA -different ESDIR for agent needs to be fetched 
   #
   [ -z "$LOGDIR" ] && LOGDIR="$VAROPTDIR/install" && $CMD_MKDIR -p $LOGDIR
   if [ -f "$BASEDIR/.registry_home" ] ; then
       REGISTRY=`/usr/bin/cat $BASEDIR/.registry_home`
   fi
   
   
   #This creates log file uninstall.PID.... 
   #
   check_logfile "uninstall"

   # remmove crontab entries etc, temp sql files etc.
   #
   do_pre_uninstall_processing 

   # Set OS parameters required for pkgrm
   #
   check_osver
   rm_options=" -n"
   
   L_PACKAGES_LEFT=`/usr/bin/pkginfo -c symon | /usr/bin/awk '{print $2}'`

   if [ ! -z "$L_PACKAGES_LEFT" ]; then
      echologverbose ''
      echologverbose 'The following packages will be removed: '
      echologverbose '$2' "$L_PACKAGES_LEFT"
      echologverbose ''
      sort_packages "$L_PACKAGES_LEFT"
      remove_packages
   else
      echolog 'No Sun Management Center package is installed on the system.'
  fi 

   # Removes database if Keep_Data flag is reset & none of the packages 
   # in unins list failed $failed_flag=0
   # If Keep_Data is set then removes only log files
   #
   remove_database $Keep_Data $failed_flag

   # Force removal of database in any case
   #
   database_uninst_error=0

   # Cleans all files & directories created by SunMC @ VAROPTDIR.
   # Keeps VAROPTDIR/cfg if keep_cfg flag is set
   # Keeps VAROPTDIR/SUNMcDB if Keep_Data is set or database uninst failed
   # Keeps VAROPTDIR/install as it contains logs
   #
   remove_var_dir
   
   # Remove basedir itself
   #
   if [ ! -z "$BASEDIR" ]; then
      cd "/tmp"
      temp_left_packages=`/usr/bin/pkginfo -c symon 2> /dev/null `
      [ -z "$temp_left_packages" ] && [ ! -z "$BASEDIR" ] && /usr/bin/rm -rf "$BASEDIR"
   else
      cd "/tmp"
      /usr/bin/rm -rf "/opt/SUNWsymon" #  2> /dev/null
   fi
   
   /usr/bin/rm -f ${TMP_DIR}/sunmc_ports.x
   /usr/bin/rm -f /tmp/symon-help-j.x
   if [ ! -z "$L_PACKAGES_LEFT" ]; then
      echolog 'Following packages failed to uninstall. You must remove them manually.'
      echolog '$2' "$L_PACKAGES_LEFT"
   
   fi
   
   HOST=`/usr/bin/hostname`
   [ -z "$REGISTRY" ] && REGISTRY="/var/opt/SUNWsymon/install/Registry_${HOST}.xml"
   if [ -f "$REGISTRY" ]; then
      DATE_FORMAT=`eval /usr/bin/echo "+\\\%y\\\%m\\\%d\\\%H\\\%M\\\%S"`
      TIMESTAMP=`/usr/bin/date $DATE_FORMAT`
      /usr/bin/mv -f "$REGISTRY" "${REGISTRY}.bak.$TIMESTAMP.$$"
   fi

   # Remove XML directories
   #
   /usr/bin/rm -rf ${TMP_DIR} 
   if [ -d "/tmp/SunMC31Install" ] ; then
       /usr/bin/rm -rf /tmp/SunMC31Install
   fi
   if [ -d "/tmp/SunMCInstall" ] ; then
       /usr/bin/rm -rf /tmp/SunMCInstall
   fi

   update_registry=0


   # This file will be present in case of DE
   #
   /usr/bin/rm -f $VARDIR/base-consoles_3_0_00_00-j.x >/dev/null 2>&1

   # Restore snmpdx if disabled at install time
   #
   restore_snmpdx
   
   echolog ''
   #[ ! -z "$LOGFILE" ] && echolog 'Uninstall logfile is : $2 ' "$LOGFILE"

   if [ ! -z "$VAROPTDIR" ] ;then
       /usr/bin/rm -rf "$VAROPTDIR/install"
       [ -z "`/usr/bin/ls "$VAROPTDIR" `" ] && /usr/bin/rm -rf "$VAROPTDIR" 
   fi
   exit "$NO_ERROR"

}

#
# Backup configuration files
#
save_cfg_files() {
    # Be extra careful that $VAROPTDIR is defined; don't accidentally
    # delete stuff in /.
    if [ -d "$VAROPTDIR" ] ; then
        /usr/bin/mkdir -p $VAROPTDIR/upgrade > /dev/null 2>&1

        # Clean out any leftover files first
        /usr/bin/rm -rf $VAROPTDIR/upgrade/cfg $VAROPTDIR/upgrade/bin >/dev/null 2>&1

        # Back up cfg and bin
        /usr/bin/cp -rp $VAROPTDIR/cfg $VAROPTDIR/upgrade
        if [ $? -ne 0 ]; then
            return 1
        fi
        /usr/bin/rm -rf $VAROPTDIR/cfg > /dev/null 2>&1

        /usr/bin/cp -rp $VAROPTDIR/bin $VAROPTDIR/upgrade
        if [ $? -ne 0 ]; then
            return 1
        fi
        /usr/bin/rm -rf $VAROPTDIR/bin
    fi
    return 0
}

export_core_database () {

    # Setup database environment for export
    if [ ! -f "$ESROOT/db/cfg/dbadmin.cfg" ] ; then
        echolog 'Database configuration file missing: cannot export data'
        return 1
    else
        . $ESROOT/db/cfg/dbadmin.cfg
    fi
    db_setupEnvironment; [ $? -ne 0 ] && return 1
    set_db_password;     [ $? -ne 0 ] && return 1

    # Export Sun Management Center core data
    db_start_database
    # Calculate the amount of available space before exporting
    # This is only going to be called for 3.5/817 version
    db_determine_export_size "3.5" 
    if [ $? -ne 0 ] ; then
       echolog 'Error while exporting database data'
       return 2
    fi

    # Export Sun Management Center core data
    db_do_export "$SUNMC_SCHEMA" "$SUNMC_SCHEMA_PWD" regular_export $LOGFILE
    if [ $? -ne 0 ] ; then
        echolog 'Error while exporting database data'
        return 1
    fi
    db_do_export "$SUNMC_USER" "$SUNMC_USER_PWD" regular_export $LOGFILE
    if [ $? -ne 0 ] ; then
        echolog 'Error while exporting database data'
        return 1
    fi
    db_stop_database

    return 0
}

do_pre_uninstall_processing () {

   set_basedir
   [ $no_server -eq 0 ] && set_db_env
   /usr/bin/mkdir -p $VAROPTDIR/install/
   /usr/bin/locale > $VAROPTDIR/install/env_file

   [ $stop_components -eq 1 ] && stop_all_processes

   #
   # We should call uninstall scripts for addons before clearing
   # files because thay may be using some files like cfginfo.
   #
   export base_uninst
   if [ ! -z "$L_SURE" ]; then
       uninstall_registered_addons $L_SURE
   else
       uninstall_unregistered_addons
   fi

   if [ $base_uninst -eq 1 ] ; then

      if [ "$Keep_Data" -eq 1 ] ; then
         if [ $no_server -eq 0 ]; then
            export_core_database
         fi
         ecd_retstat=$?
         
         # The return status 2 is used to identify "out of disk space" condition before the
         #actual export takes place
         if [ $ecd_retstat -eq 2 ] ; then
           exit 1
         fi

         if [ $ecd_retstat -ne 0 ] ; then
            echolog 'WARNING: unable to export database for Sun Management Center base product. Data will NOT be preserved.'
         fi

         save_cfg_files
         if [ $? -ne 0 ]; then
            echolog 'WARNING: unable to copy configuration files for Sun Management Center base product. Data will NOT be preserved.'
         fi
      fi

      # Stop all processes, stop database,all_sql_logs,discovery if any.
      #
      #[ $stop_components -eq 1 ] && stop_all_processes
  
      # Kill console 
      # 3.5 - Will not kill console during uninstall
      # 
      #[ $no_console  -eq 0 ] &&  kill_processes ConsoleMain
   
      #Assist user in removing java
      #
      #remove_java

      #Remove all cronjobs created by SunMC
      #
      remove_crontab_entries

      # 
      # Call removeLockhartLinks to remove links created if any
      # unregister SMLegacyLoginModule from Sun Web Console
      #
      removeWebConsoleLinks

      # Remove some setup time created files
      #
      [ -d "$BASEDIR/web/help" ] && /usr/bin/rm -rf $BASEDIR/web/help
      [ -d "$BASEDIR/web/conf" ] && /usr/bin/rm -rf $BASEDIR/web/conf
      [ -d "$BASEDIR/web/logs" ] && /usr/bin/rm -rf $BASEDIR/web/logs
      [ -f "$BASEDIR/sbin/.cfginfo" ] && /usr/bin/rm -f $BASEDIR/sbin/.cfginfo
      [ -f "$BASEDIR/sbin/.cfginfo.old" ] && /usr/bin/rm -f $BASEDIR/sbin/.cfginfo.old
      [ -f "$BASEDIR/sbin/sqlnet.log" ] && /usr/bin/rm -f $BASEDIR/sbin/sqlnet.log
      [ -f "$VARDIR/.sdklicense" ] && /usr/bin/rm -f $VARDIR/.sdklicense
      [ -f "$VARDIR/.license" ] && /usr/bin/rm -f $VARDIR/.license

      # Remove all sql& log files in /tmp
      #
      if [ -x $BASEDIR/db/build/cleanup-tmp.sh ]; then
         $BASEDIR/db/build/cleanup-tmp.sh
         /usr/bin/rm -f $BASEDIR/db/build/cleanup-tmp.sh
      else
         echologverbose 'Database logfile cleanup script not present.'
      fi
      
      # Ensure we cleanup any oracle related sql and log files
      # used by the smcorau user
      #
      remove_sql_log_files	       	  
      /usr/bin/rm -f ${TMP_SMC_DB_LOGS}/make.log
      /usr/bin/rm -rf ${TMP_DIR}/smcdb_db*
      /usr/bin/rm -rf ${TMP_SMC_DB_LOGS}/sunmclog
      /usr/bin/rm -rf ${TMP_SMC_DB_LOGS}/catoutu.log*
      /usr/bin/rm -f /tmp/clntst8.* > /dev/null 2>&1 

      #
      # Remove all the created groups - will use a hardcoded list if not availablein registry.
      #
      if [ "$Keep_Data" -ne 1 ] ; then
          remove_created_groups
      fi

   fi
   return 0 
}


# This is to take care of unsync registry when called with -X option
#
uninstall_unregistered_addons () {
    [ -z "$BASEDIR" ] && return 0
    addon_scripts=`/usr/bin/ls -tr $BASEDIR/addons/*/sbin/es-uninst.sh 2> /dev/null`
    for each_addon in $addon_scripts
    do
        $each_addon
    done
}



uninstall_registered_addons () {
   
   [ -z "$@" ] && return
   
   [ ! -z "$Keep_Data" ] && export Keep_Data
   
   echolog ''
   
   for each_addon in `$CMD_ECHO $@ | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
   do 
      [ "$each_addon" = "$BASE_PRODUCT" ] && continue

      addon_dir=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$each_addon" "target_subdir"  2> /dev/null `
      [ $? -gt 0 ] && exit_SunMC_uninstall "$REGISTRY_READ_ERROR"
      if [ -f "$BASEDIR/addons/$addon_dir/sbin/es-uninst.sh" ]; then
         echolog 'Calling Uninstall script of $2...' "`get_product_names "$each_addon"`"
         $BASEDIR/addons/$addon_dir/sbin/es-uninst.sh
         if [ $? -gt 0 ]; then
            echolog ""
            echolog  'A problem occurred with $2 uninstall.'  "`get_product_names "$each_addon"`"
         fi 
      else
         echologverbose 'Uninstall script for addon $2 not found.' "`get_product_names "$each_addon"`"
      fi
   done

}


exit_SunMC_uninstall() {

  # Update registry
  #
  if [ "$update_registry" = "1" ]; then
  
     # Report a uninstall status to user.
     # Productwise list of all Uninstalled/Failed packages
     # Ask user to remove failed packages manually.
     #
     display_uninst_status
  
     if [ "$1" != "$REGISTRY_READ_ERROR" -a "$1" != "$REGISTRY_WRITE_ERROR" -a "$1" != "$REGISTRY_PERMISSION_ERROR" ]; then
        pack_registry
     fi
    
  fi
  
  #if [ "$1" = "0" ]; then
  #   [ ! -z "$L_SURE" ] && echologverbose 'Uninstallation all requested Sun Management Center products is complete !!!' 
  #fi 

  exit "$1"

}

#
# Removes groups created at the time of server layer setup.
# These groups are esops, esadm, esdomadm
#
remove_created_groups() {
    createdgroups=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "layer=LAYER.SERVER" "groups_added" 2> /dev/null` 
    createdgroups=`/usr/bin/echo $createdgroups`

    # This hardcoding is to take care of bug in 3.0 uninstallation.
    # Because 3.0 uninstall does not remove these groups, entries in Registry are not made
    # during 3.5 installation. In such cases, 3.5 uninstallation also skips removal. 
    #
    [ -z "$createdgroups" ] && createdgroups="esadm esdomadm esops" 
    for each_group in $createdgroups ; do
        /usr/sbin/groupdel $each_group 2> /dev/null
    done
}

do_post_uninstall_processing() {

   if [ $base_uninst -eq 1 ] ; then
      # Remove database
      # if Keep_Data set then remove only flags
      #
      remove_database $Keep_Data $failed_flag
      database_uninst_error=$?
 
      # Cleans all files & directories created by SunMC @ VAROPTDIR.
      # Keeps VAROPTDIR/cfg if keep_cfg flag is set
      # Keeps VAROPTDIR/SUNMcDB if Keep_Data is set or database uninst failed
      # Keeps VAROPTDIR/install as it contains logs
      #
      if [ "$Keep_Data" = "0" ] ; then
         remove_var_dir $keep_cfg
      else
         echolog 'Preserving $2.' "$VAROPTDIR"
      fi

      # Cleanup dynamically created stuff
      #
      if [ -n "$orabasedir" -a -d $orabasedir/SUNWsymon/oracle ]; then
         /usr/bin/rm -rf $orabasedir/SUNWsymon/oracle >/dev/null 2>&1
      fi
 
      if [ -n "$orabasedir" -a -d $orabasedir/SUNWsymon/db ]; then
         /usr/bin/rm -rf $orabasedir/SUNWsymon/db >/dev/null 2>&1
      fi
   
      # Remove all the console banner related file which were copied
      # at install time. This is only for development system
      #
      /usr/bin/rm -f $VARDIR/base-consoles_3_0_00_00-j.x >/dev/null 2>&1

      # Remove Registry home file form BASEDIR
      #
      /usr/bin/rm -f "$BASEDIR/.registry_home"

      /usr/bin/rm -f /tmp/symon-help-j.x
      /usr/bin/rm -f ${TMP_DIR}/sunmc_ports.x
      temp_left_packages=`/usr/bin/pkginfo -c symon 2> /dev/null `
      #[ -z "$temp_left_packages" ] && /usr/bin/rm -rf $BASEDIR

      # Restore snmpdx if disabled at install time
      #
      restore_snmpdx

      # removing archive download directory.
      /usr/bin/rm -f ${TMP_DIR}/sunmc_ports.x

      # removing dynamically created files
      if [ $Keep_Data -eq 0 ]; then
          smartupdate_remove
      fi
      /usr/bin/rm -rf ${BASEDIR}/web/
      /usr/bin/rm -rf ${BASEDIR}/classes/
      /usr/bin/rm -rf ${BASEDIR}/lib/
      /usr/bin/rm -rf ${BASEDIR}/sbin/
      /usr/bin/rm -rf ${BASEDIR}/vardir/
   fi

   [ -z "$temp_left_packages" ] && /usr/bin/rmdir $BASEDIR > /dev/null 2>&1
   # The above line is to attempt removal of SUNWsymon if empty

   unset temp_left_packages
}

# restore snmpdx if disabled at install time
#
restore_snmpdx() {
 
   # Restore SNMPDX if disabled at install time
   #
   if [ -r "/etc/rc3.d/D.sunmc.S76snmpdx" ]; then
      /usr/bin/mv -f /etc/rc3.d/D.sunmc.S76snmpdx /etc/rc3.d/S76snmpdx  > /dev/null 2>&1 
      /usr/bin/chmod 744 /etc/rc3.d/S76snmpdx  > /dev/null 2>&1 
      if [ -x "/etc/rc3.d/S76snmpdx" ];then
         /etc/rc3.d/S76snmpdx start > /dev/null 2>&1 
         echologverbose '/etc/rc3.d/S76snmpdx restored and started.'
         /usr/bin/rm -f "/etc/rc3.d/S83snmpdx" > /dev/null 2>&1 
      fi
   fi
         
   if [ -r "/etc/rc3.d/D.sunmc.S77dmi" ] ; then
      /usr/bin/mv -f /etc/rc3.d/D.sunmc.S77dmi /etc/rc3.d/S77dmi  > /dev/null 2>&1 
      /usr/bin/chmod 744 /etc/rc3.d/S77dmi  > /dev/null 2>&1 
      if [ -x "/etc/rc3.d/S77dmi" ];then
         /etc/rc3.d/S77dmi start > /dev/null 2>&1 
         echologverbose '/etc/rc3.d/S77dmi restored and started.'
      fi
   fi

   
}

# Inputs - $1 => $L_SURE a product list which was unintslalled
#
pack_registry() {

   echologverbose ''
   echologverbose 'Updating Registry...'
   
   # Remove all from Registry what was uninstalled
   #
   for each_product in `$CMD_ECHO "$L_INSTALLED_PRODUCTS" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
   do   
      
      L_COMPONENTS=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$each_product" "component" "key" 2> /dev/null `
      #[ $? -gt 0 ] && exit_SunMC_uninstall "$REGISTRY_READ_ERROR"
      for each_component in `$CMD_ECHO "$L_COMPONENTS" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
      do
         temp_list=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$each_product" "component=$each_component" "package" "key" 2> /dev/null `
         #[ $? -gt 0 ] && exit_SunMC_uninstall "$REGISTRY_READ_ERROR"
         
         for each_package in `$CMD_ECHO "$temp_list" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
         do
            /usr/bin/pkginfo -q $each_package
            if [ $? -gt 0 ] ; then
               $API_REMOVE_TAG "$REGISTRY" "category=SunMC" "product=$each_product" "component=$each_component" "package=$each_package"  1> /dev/null 2>&1
               #[ $? -gt 0 ] && exit_SunMC_uninstall "$REGISTRY_WRITE_ERROR"
            fi               
         done

         temp_list=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$each_product" "component=$each_component" "package" "key" 2> /dev/null `
         #[ $? -gt 0 ] && exit_SunMC_uninstall "$REGISTRY_READ_ERROR"
         if [ -z "$temp_list" ]; then
            $API_REMOVE_TAG "$REGISTRY" "category=SunMC" "product=$each_product" "component=$each_component"  1> /dev/null 2>&1
            #[ $? -gt 0 ] && exit_SunMC_uninstall "$REGISTRY_WRITE_ERROR"
         fi
      done
   
      L_COMPONENTS=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$each_product" "component" "key" 2> /dev/null `
      #[ $? -gt 0 ] && exit_SunMC_uninstall "$REGISTRY_READ_ERROR"
     
      if [ -z "$L_COMPONENTS" ]; then
         $API_REMOVE_TAG "$REGISTRY" "category=SunMC" "product=$each_product"    1> /dev/null 2>&1
         #[ $? -gt 0 ] && exit_SunMC_uninstall "$REGISTRY_WRITE_ERROR"
      fi
   done
   
   L_INSTALLED_PRODUCTS=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product" "key" 2> /dev/null `
   #[ $? -gt 0 ] && exit_SunMC "$REGISTRY_READ_ERROR"

   # remove registry file itself  if no product remained in registry !!!
   #
   if [ -z "$L_INSTALLED_PRODUCTS" ]; then
      HOST=`/usr/bin/hostname`
      [ -z "$REGISTRY" ] && REGISTRY="/var/opt/SUNWsymon/install/Registry_${HOST}.xml"
      if [ -f "$REGISTRY" ] ; then
         DATE_FORMAT=`eval /usr/bin/echo "+\\\%y\\\%m\\\%d\\\%H\\\%M\\\%S"`
         TIMESTAMP=`/usr/bin/date $DATE_FORMAT`
         /usr/bin/mv -f "$REGISTRY" "${REGISTRY}.bak.$TIMESTAMP.$$"
      fi
      # Remove XML directories
      #
      /usr/bin/rm -rf ${TMP_DIR} 
      /usr/bin/rm -rf /tmp/SunMC31Install
      /usr/bin/rm -rf ${TMP_SMC_DB_LOGS}

      # If this is not HA installation then remove /install direcory itself
      # After this statement, no message can go to logfile. can not use echolog.
      if [ "$no_HA" != "0" ] ; then
         if [ ! -z "$VAROPTDIR" ] ;then
            /usr/bin/rm -rf "$VAROPTDIR/install"
            [ -z "`/usr/bin/ls "$VAROPTDIR" `" ] && /usr/bin/rm -rf "$VAROPTDIR" 
         fi
      fi
   else
      [ ! -z "$LOGFILE" ] && echolog 'Uninstall logfile is : $2 ' "$LOGFILE"
   fi
   update_registry=0

}


get_dependent_pkgs () {
   pkglist=`/usr/bin/ls /var/sadm/pkg`
   dependent_pkgs=""
   for each_pkg in $pkglist
   do
      depend_file="/var/sadm/pkg/${each_pkg}/install/depend"
      if [ -f "$depend_file" ] ; then
         /usr/bin/grep -w "$1" $depend_file > /dev/null 2>&1
         if [ $? -ne 0 ] ; then
            continue
         fi
         dep_list=`/usr/bin/cat $depend_file | /usr/bin/grep -v "^[ 	]*#" | /usr/bin/nawk '{if ($1 == "P") print $2}'`
         /usr/bin/echo $dep_list | /usr/bin/grep -w "$1" > /dev/null 2>&1
         if [ $? -eq 0 ] ; then
            temp_str=`/usr/bin/pkgparam $each_pkg CATEGORY 2> /dev/null`
            if [ $? -eq 0 ]; then
               temp_str=`/usr/bin/echo $temp_str | /usr/bin/grep -i "symon" 2> /dev/null`                   
               [ $? -gt 0 ] && dependent_pkgs="$dependent_pkgs $each_pkg"
            fi
         fi
      fi
   done
   unset temp_str pkglist dep_list
}

smartupdate_remove()
{
	[ -z "$BASEDIR" ] && return
	
        /usr/bin/rm -f ${BASEDIR}/web/agentupdate

        echologverbose 'Deleting archives...'
	/usr/bin/rm -rf /var/opt/SUNWsymon/agentupdate

        echologverbose 'Deleting archive-tool logs...'

        /usr/bin/rm -f /var/opt/SUNWsymon/install/*archive*

	/usr/bin/rm -rf /var/opt/SUNWsymon/AdvancedServices/tasks/agentupdate
	/usr/bin/rm -rf /var/opt/SUNWsymon/AdvancedServices/services/agentupdate
        /usr/bin/rm -f /var/opt/SUNWsymon/log/InstallServer.log

        return 0
}

