#!/bin/sh
# Copyright 01/04/05 Sun Microsystems, Inc. All Rights Reserved.
# pragma ident  "@(#)db-common.sh	1.142 05/01/04 Sun Microsystems"

# params:  groupname
# 
verifyCreateOracleGroup ()
{
 
   if [ -z "$1" ]; then
      echolog 'verifyCreateOracleGroup - the groupname parm is null, returning failure code'
      return 99
   fi
  
   if [ ! -r /etc/group ]; then
      echolog 'verifyCreateOracleGroup - /etc/group file not found'
      echolog ''
      return 1
   fi

   gname=$1
 
   gline=`/usr/bin/grep -i "^[ ]*$gname:" /etc/group`

   if [ "$gline" = "" ]; then
      gncnt=0
   else
      gncnt=`echo $gline | wc -l`
   fi

   if [ $gncnt -ne 1 ]; then
      if [ $gncnt -eq 0 ]; then

         echologverbose 'verifyCreateOracleGroup - group named $2 does not exist in the /etc/group file' "$1"
         grstring=`$ESROOT/base/bin/sparc-sun-solaris${OSVERS}/smcgrchk $gname 2>/dev/null`
         retcode=$?

         if [ $retcode = 0 ]; then
            echologverbose 'the group $2 was found by call to getgrnam system call ,probably nis, nis+, etc..' "$1"
         else
            if [ $retcode = 2 ]; then

               echologverbose 'creating new group $2' "$1"
               /usr/sbin/groupadd $1
               retcode=$?

               if [ $retcode -ne 0 ]; then
                  echolog 'verifyCreateOracleGroup - failed to create new group $2' "$1"
                  return $retcode
               fi
 
               gline=`/usr/bin/grep -i "^[ ]*$gname:" /etc/group`
  
               if [ "$gline" = "" ]; then
                  gncnt=0
               else
                  gncnt=`echo $gline | wc -l`
               fi

               if [ $gncnt -ne 1 ]; then
                  echolog 'verifyCreateOracleGroup - inconsistent group details in /etc/group file for new group $2' "$1"
                  return 1
               fi

            fi
         fi
      fi 
  
      if [ $gncnt -gt 1 ]; then
         echolog 'verifyCreateOracleGroup - more than one entry for the group named $2 exists in the /etc/group file' "$1"
         return 1
      fi 
   fi 

   grstring=`$ESROOT/base/bin/sparc-sun-solaris${OSVERS}/smcgrchk $gname 2>/dev/null`
   retcode=$?

   if [ $retcode = 0 ]; then
      gvalue=`echo $grstring | awk -F':' '{print $3}'`
      retcode=$?

      if [ $retcode -ne 0 ]; then
         echolog 'verifyCreateOracleGroup - failed to obtain group id count info from awk command'
         return $retcode
      fi
   else
      if [ $retcode = 2 ]; then
         gvalue=`echo $gline | awk -F':' '{print $3}'`
         retcode=$?

         if [ $retcode -ne 0 ]; then
            echolog 'verifyCreateOracleGroup - failed to obtain group id count info from awk command'
            return $retcode
         fi

         gvcnt=`cat /etc/group | awk -F':' '{print $3}' | /usr/bin/grep -i $gvalue | wc -l`

         if [ $gncnt -ne 1 ]; then
            if [ $gncnt -eq 0 ]; then
               echolog 'verifyCreateOracleGroup - group id for group $2 does not exist in the /etc/group file' "$1"
               return 1
            fi 
        
            if [ $gncnt -gt 1 ]; then
               echolog 'verifyCreateOracleGroup - more than one entry for the group id for group $2 exists in the /etc/group file' "$1"
               return 1
            fi 
         fi 

      fi
   fi

   groupid=$gvalue
   return 0
}




# params:  username, groupname, groupvalue, homedir

verifyCreateOracleUser ()
{

 if [ -z "$1" ]
  then
    echolog 'verifyCreateOracleUser - the username parm is null, returning failure code'
    return 99
  fi

  if [ -z "$2" ]
  then
    echolog 'verifyCreateOracleUser - the groupname parm is null, returning failure code'
    return 99
  fi

  if [ -z "$3" ]
  then
    echolog 'verifyCreateOracleUser - the groupid parm is null, returning failure code'
    return 99
  fi

  if [ -z "$4" ]
  then
    echolog 'verifyCreateOracleUser - the homedir parm is null, returning failure code'
    return 99
  fi


# This was done before xml registry
#  if [ $# -lt 4 ] ; then
#     echolog ''
#     echolog 'verifyCreateOracleUser - Improper parameters. returning failure code'
#     echolog 'username, groupname, groupvalue, homedir:$2 ' "$@"
#     return 99
#  fi
 




  if [ ! -r /etc/passwd ]; then
     echolog 'verifyCreateOracleUser - /etc/passwd file not found'
     echolog
     echolog
     return 1
  fi

  uname=$1
  gname=$2
  gvalue=$3
  homedir=$4



  trailslash=`echo $homedir | /usr/bin/grep -i "/$" | wc -l`

  if [ $trailslash = 0 ]
  then
     homedir="$homedir/"
  fi



  uline=`/usr/bin/grep -i "^[ ]*$uname:" /etc/passwd`



  if [ "$uline" = "" ]
  then
    uncnt=0

    if [ -d $homedir$uname ]; then
      /usr/bin/rm -rf $homedir$uname
    fi

  else
    uncnt=`echo $uline | wc -l`

    if [ $uncnt -eq 1 ]
    then

      if [ ! -d $homedir$uname ]; then
         echolog "verifyCreateOracleUser - the existing $uname user home directory - $homedir$uname does not exist"
         echolog "verifyCreateOracleUser - will perform a userdel on the current user, before re-creating"

         hdir=`echo $uline | awk -F':' '{print $6}'`
   
         hdircnt=`echo $hdir | wc -l`

         if [ $hdircnt -eq 1 ]
         then
            if [ -d $hdir ]
            then
               /usr/sbin/userdel -r $uname
               retcode=$?
            else
              /usr/sbin/userdel $uname
              retcode=$?
            fi
         else
              /usr/sbin/userdel $uname
              retcode=$?
         fi


         if [ $retcode -ne 0 ]
         then
            echolog 'verifyCreateOracleUser - failed to delete user $2' "$1"
            return $retcode
         fi

         # critical line to ensure that subsequent logic creates the user
         uncnt=0

      fi

    else

       if [ -d $homedir$uname ]; then
         /usr/bin/rm -rf $homedir$uname
       fi

    fi


  fi


  if [ $uncnt -ne 1 ]
  then
    if [ $uncnt -eq 0 ]
    then
       echologverbose 'verifyCreateOracleUser - user named $2 does not exist in the /etc/passwd file' "$1"

       grstring=`$ESROOT/base/bin/sparc-sun-solaris${OSVERS}/smcpwchk $uname 2>/dev/null`

       retcode=$?

       if [ $retcode = 0 ]
       then
          echologverbose 'the group $2 was found by call to getpwnam system call ,probably nis, nis+, etc..' "$1"

         if [ ! -d "${homedir}${uname}" ]; then
            /usr/bin/mkdir -p ${homedir}${uname}
         fi

       else
         if [ $retcode = 2 ]
         then

            echologverbose 'creating new user $2' "$1"

            /usr/sbin/useradd -d $homedir$uname -m -g $gvalue -s /bin/sh $uname > /dev/null 2>&1

            retcode=$?
 
            if [ $retcode -ne 0 ]
            then
               echolog 'verifyCreateOracleUser - failed to create new user $2' "$1"
               echolog "This may be because of a blank line at the end of a passwd file or a malformed passwd file. Exiting..." 
	       return $retcode
            fi

            uline=`/usr/bin/grep -i "^[ ]*$uname:" /etc/passwd`
 
            if [ "$uline" = "" ]
            then
              uncnt=0
            else
              uncnt=`echo $uline | wc -l`
            fi

            if [ $uncnt -ne 1 ]
            then
               echolog 'verifyCreateOracleUser - inconsistent user details in /etc/passwd file for new user $2' "$1"
               return 1
            fi

            if [ ! -d $homedir$uname ]; then
               echolog "verifyCreateOracleUser - home directory - $homedir$uname does not exist"
               return 1
            fi

         fi
       fi

    fi 

    if [ $uncnt -gt 1 ]
    then
       echolog 'verifyCreateOracleUser - more than one entry for the user named $2 exists in the /etc/passwd file' "$1"
       return 1
    fi 

  fi 



  pwstring=`$ESROOT/base/bin/sparc-sun-solaris${OSVERS}/smcpwchk $uname 2>/dev/null`

  retcode=$?

  if [ $retcode = 0 ]
  then
     gvalue=`echo $pwstring | awk -F':' '{print $3}'`

     retcode=$?

     if [ $retcode -ne 0 ]
     then
        echolog 'verifyCreateOracleUser - failed to obtain user id value from awk command'
        return $retcode
     fi

  else
     if [ $retcode = 2 ]
     then

        uvalue=`echo $uline | awk -F':' '{print $3}'`

        retcode=$?

        if [ $retcode -ne 0 ]
        then
           echolog 'verifyCreateOracleUser - failed to obtain user id value from awk command'
           return $retcode
        fi

        uvcnt=`cat /etc/passwd | awk -F':' '{print $3}' | /usr/bin/grep -i $uvalue | wc -l`

        if [ $uvcnt -ne 1 ]
        then
          if [ $uvcnt -eq 0 ]
          then
             echolog 'verifyCreateOracleUser - user id for user $2 does not exist in the /etc/passwd file' "$1"
             return 1
          fi 
          if [ $uvcnt -gt 1 ]
          then
             echolog 'verifyCreateOracleUser - more than one entry for the user id for user $2 exists in the /etc/passwd file' "$1"
             return 1
          fi 
        fi 

     fi
  fi

  userid=$uvalue

 
  #
  #Now the user is created successfully, so add .hushlogin file in the
  #home directory to supress the login messages.
  #

 if [ -d "${homedir}${uname}" ]; then
    /usr/bin/touch "${homedir}${uname}/.hushlogin"
    if [ $? -ne 0 ] ; then
       echolog 'Could not touch the file .hushlogin, login messages will be displayed.'
    fi
 fi





  return 0
}






# params:  groupname

verifyDeleteOracleGroup ()
{

  if [ -z "$1" ]
  then
    echolog 'verifyDeleteOracleGroup - the groupname parm is null, returning failure code'
    return 99
  fi



  if [ ! -r /etc/group ]
  then
     echolog 'verifyDeleteOracleGroup - /etc/group file not found'
     echolog
     echolog
     return 1
  fi

  gname=$1



  gline=`/usr/bin/grep -i "^[ ]*$gname:" /etc/group`


  if [ "$gline" = "" ]
  then
    gncnt=0
  else
    gncnt=`echo $gline | wc -l`
  fi


    if [ $gncnt -gt 0 ]
    then

       #
       #  May have to check for the execution of ypbind? and then
       #  we may also need to check for nis+ process nisbind? or something
       #

       if [  -r /etc/nsswitch.conf ]
       then
         grfirst=`/usr/bin/grep -i "^[ ]*group[ ]*:" /etc/nsswitch.conf | cut -f2 -d':' | awk '{print $1}'`
         nsfile_exists="true"
       else
         # if file does not exist, then set grfirst to equal files
         # so remaining logic flows as predicted
         grfirst="files"
         nsfile_exists="false"
       fi 

         #
         #  If the the nsswitch.conf files exists and the first entry for group 
         #  is not files, then inform the user we can't try a groupdel.  The user 
         #  will have to deal with this manually.
         #

         if [ "$grfirst" != "files" ]
         then
            echolog 'verifyDeleteOracleGroup - the nsswitch.conf files first entry for group is not files'
            echolog 'verifyDeleteOracleGroup - you must manually delete the local group $2' "$SMCORAG" 
         else

            echologverbose 'verifyDeleteOracleGroup - group named $2 does exist in the /etc/group file' "$1"
            echologverbose 'deleting existing group $2' "$1"
            /usr/sbin/groupdel $1
 
            retcode=$?

            if [ $retcode -ne 0 ]
            then
               echolog 'verifyDeleteOracleGroup - failed to delete group $2' "$1"
            
               if [ $retcode = 6 ]
               then
                   echolog 'verifyDeleteOracleGroup -  **** You must manually delete group  ****'
               fi
               return $retcode
            fi

            gline=`/usr/bin/grep -i "^[ ]*$gname:" /etc/group`

            if [ "$gline" = "" ]; then
              gncnt=0
            else
              gncnt=`echo $gline | wc -l`
            fi
 
            if [ $gncnt -ne 0 ]; then
               echolog 'verifyDeleteOracleGroup - inconsistent group details in /etc/group file for delete group $2' "$1"
               return 1
            fi

         fi

    fi 


   return 0

}


# params:  username

verifyDeleteOracleUser ()
{
  if [ -z "$1" ]
  then
    echolog 'verifyDeleteOracleUser - the username parm is null, returning failure code'
    return 99
  fi


  if [ ! -r /etc/passwd ]
  then
     echolog 'verifyDeleteOracleUser - /etc/passwd file not found'
     echolog
     echolog
     return 1
  fi

  uname=$1

  uline=`/usr/bin/grep -i "^[ ]*$uname:" /etc/passwd`



  if [ "$uline" = "" ]
  then
    uncnt=0
  else
    uncnt=`echo $uline | wc -l`
  fi


    if [ $uncnt -gt 0 ]
    then

       #
       #  May have to check for the execution of ypbind? and then
       #  we may also need to check for nis+ process nisbind? or something
       #

       if [  -r /etc/nsswitch.conf ]
       then
         pwfirst=`/usr/bin/grep -i "^[ ]*passwd[ ]*:" /etc/nsswitch.conf | cut -f2 -d':' | awk '{print $1}'`
         nsfile_exists="true"
       else
         # if the file does not exist, then set pwfirst to files
         # so the remaining logic flows as predicted
         pwfirst="files"
         nsfile_exists="false"
       fi 

         #
         #  If the the nsswitch.conf files exists and the first entry for passwd 
         #  is not files, then inform the user we can't try a userdel.  The user 
         #  will have to deal with this manually.
         #

         if [ "$pwfirst" != "files" ]
         then
            echolog 'verifyDeleteOracleUser - the nsswitch.conf files first entry for passwd is not files'
            echolog 'verifyDeleteOracleUser - you must manually delete the local user $2' "$SMCORAU" 
         else
            echologverbose 'verifyDeleteOracleUser - user named $2 does exist in the /etc/passwd file' "$1"
            echologverbose 'deleting user $2' "$1"

            hdir=`echo $uline | awk -F':' '{print $6}'`
   
            hdircnt=`echo $hdir | wc -l`

            if [ $hdircnt -eq 1 ]
            then
               if [ -d $hdir ]
               then
                  /usr/sbin/userdel -r $uname
                  retcode=$?
               else
                 /usr/sbin/userdel $uname
                 retcode=$?
               fi
            else
                 /usr/sbin/userdel $uname
                 retcode=$?
            fi


            if [ $retcode -ne 0 ]
            then
               echolog 'verifyDeleteOracleUser - failed to delete user $2' "$1"
               return $retcode
            fi

            uline=`/usr/bin/grep -i "^[ ]*$uname:" /etc/passwd`
 
            if [ "$uline" = "" ]
            then
              uncnt=0
            else
              uncnt=`echo $uline | wc -l`
            fi

            if [ $uncnt -ne 0 ]
            then
               echolog 'verifyDeleteOracleUser - inconsistent user details in /etc/passwd file for deleted user $2' "$1"
               return 1
            fi

         fi

    fi 


   return 0

}



smcdb_configuration() {
    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
        fi
    fi
    # add the Sun MC crontab entry.  It should not produce any standard output or standard error
    # and should not generate an e-mail message
    cat >> $TMPCRONTAB << EOF
0 0 * * 0-6 cd $BASEDIR/lib/sbin;$BASEDIR/lib/sbin/generate-analyze-table.sh 1>/dev/null 2>/dev/null
EOF
    cat $TMPCRONTAB | /usr/bin/crontab

    # remove temporary crontab file
	/usr/bin/rm -f $TMPCRONTAB

 #
 # Make sure an oratab file exists on this system
 #
 ORATABLOC=/var/opt/oracle
 ORATAB=${ORATABLOC}/oratab
 TMPORATB=/var/tmp/oratab$$

 # If the file doesn't exist then create and update it with new entry.
 #

 if [ ! -s ${ORATAB} ];then
    if [ ! -d ${ORATABLOC} ];then
       /usr/bin/mkdir -p ${ORATABLOC}
    fi

   /usr/bin/cat <<!>> ${ORATAB}
${ORACLE_SID}:${ORACLE_HOME}:N
!

 else

   # $ORATAB exists.

   # Check if this oratab file belongs to 3.0 installation.
   #
   OLD_SID=SunMC30
   FOUND_30=`/usr/bin/grep "^${OLD_SID}:" ${ORATAB}`
   if [ -n "${FOUND_30}" ] ; then
       other_instances=`/usr/bin/grep -v "^${OLD_SID}:" ${ORATAB} | /usr/bin/wc -l`
        if [ "${other_instances}" -eq 0 ] ; then
           # There are no instances other then SunMC30.
           # Change permissions to 644
           /usr/bin/chmod 644 ${ORATAB} 2>/dev/null
        fi
       # Remove the 3.0 entry from oratab file.
       /usr/bin/grep -v "^${OLD_SID}:"  ${ORATAB} > ${TMPORATB} 2>/dev/null
       /usr/bin/cat ${TMPORATB} > ${ORATAB}
       /usr/bin/rm -f $TMPORATB 2>/dev/null
   fi             

   # Check if an entry exists in $ORATAB for this $SID and this $ORACLE_HOME,
   # don't do anything.
   #

   FOUND=`/usr/bin/grep "^${ORACLE_SID}:${ORACLE_HOME}:" ${ORATAB}`
   if [ -z "${FOUND}" ];then

       #
       # If there is an old entry with no sid and same oracle home,
       # that entry will be marked as a comment.
       #

       FOUND_OLD=`/usr/bin/grep "^.*:${ORACLE_HOME}:" ${ORATAB}`
       if [ -n "${FOUND_OLD}" ];then
           /usr/bin/sed -e "s?^.*:$ORACLE_HOME:?#&?" $ORATAB > $TMPORATB
           /usr/bin/cat $TMPORATB > $ORATAB
           /usr/bin/rm -f $TMPORATB 2>/dev/null
       fi
        /usr/bin/cat <<!>> ${ORATAB}
${ORACLE_SID}:$ORACLE_HOME:N
!
   fi
    #else

      #echo "Entry already exists in the ${ORATAB} file for this"|tee -a $LOG
      #echo "ORACLE_SID and ORACLE_HOME.  No changes made to file."|tee -a $LOG
 fi



    #
    # reset the configuration files for Sun Management Center DB
    #
    listener_file="$ORACLE_HOME/network/admin/listener.ora"
    tns_file="$ORACLE_HOME/network/admin/tnsnames.ora"
    init_file="$ORACLE_HOME/admin/SunMC/pfile/initSunMC.ora"
    trace_file="$ORACLE_HOME/admin/SunMC/udump/trace.txt"
    sqlnet_file="$ORACLE_HOME/network/admin/sqlnet.ora"

    /usr/bin/chmod 600 $listener_file $tns_file $sqlnet_file
    sid_name="SMCDBPROC"
    #
    # configure the trace.txt which controls generation of stored procedure
    # tracing from the trace package (see package-body-trace.sql)
    #
    echo "off" > $trace_file

        #
        # configure the listener file
        #
        echo "# LISTENER.ORA Configuration File:$listener_file
# Generated by Sun Management Center DB Installation.

SID_LIST_SMCDBLISTENER =
  (SID_LIST =
    (SID_DESC =
      (SID_NAME = PLS$sid_name)
      (ORACLE_HOME = $ORACLE_HOME)
    )
    (SID_DESC =
      (GLOBAL_DBNAME = SunMC)
      (ORACLE_HOME = $ORACLE_HOME)
      (SID_NAME = SunMC)
    )
  )

SMCDBLISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS_LIST =
        (ADDRESS = (PROTOCOL = TCP)(HOST = $SMCDB_HOST)(PORT = $SMCDB_PORT))
      )
      (ADDRESS_LIST =
        (ADDRESS = (PROTOCOL = IPC)(KEY = $sid_name))
      )
    )
  )

ADMIN_RESTRICTIONS_smcdblistener = ON" > $listener_file
        [ $? -ne 0 ] && return "1"

        #
        # configure tns service file
        #
        echo "# TNSNAMES.ORA Configuration File:$tns_file
# Generated by Sun Management Center DB Installation.

SUNMC =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = $SMCDB_HOST)(PORT = $SMCDB_PORT))
    )
    (CONNECT_DATA =
      (SERVICE_NAME = SunMC)
    )
  )

EXTPROC_CONNECTION_DATA =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = IPC)(KEY = $sid_name))
    )
    (CONNECT_DATA =
      (SID = PLS$sid_name)
      (PRESENTATION = RO)
    )
  )" > $tns_file

 [ $? -ne 0 ] && return "1"

 if [ -f "$init_file" ]; then
   inifile_lcount=`/usr/bin/egrep -v "^$" $init_file|/usr/bin/wc -l|/usr/bin/awk '{ print $1 }'`
   inifile_lccount=`/usr/bin/egrep "^#.*" $init_file|/usr/bin/wc -l|/usr/bin/awk '{ print $1 }'`
 else
   inifile_lcount=0
   inifile_lccount=0
 fi

 if [ $inifile_lcount -eq $inifile_lccount ]; then
        #
        # configure database initialization file
        #
        echo "\n#
#
# initSunMC.ora for Sun Management Center Oracle
#
# Copyright (c) 10/01/01 Sun Microsystems, Inc. All Rights Reserved.
#

db_name = \"SunMC\"
instance_name = SunMC

service_names = SunMC

control_files = (\"/var/opt/SUNWsymon/db/oradata/SunMC/control01.ctl\", \"/var/opt/SUNWsymon/db/oradata/SunMC/control02.ctl\", \"/var/opt/SUNWsymon/db/oradata/SunMC/control03.ctl\")

open_cursors = 100
max_enabled_roles = 30
# db_file_multiblock_read_count = 16

db_block_buffers = 2048

shared_pool_size = 8M
shared_pool_reserved_size = 1M

large_pool_size = 48M
java_pool_size = 0

log_checkpoint_interval = 10000
log_checkpoint_timeout = 1800

processes = 115

log_buffer = 163840

# audit_trail = false  # if you want auditing
# timed_statistics = false  # if you want timed statistics
# max_dump_file_size = 10000  # limit trace file size to 5M each


# define directories to store trace and alert files
background_dump_dest = $ORACLE_HOME/admin/SunMC/bdump
core_dump_dest = $ORACLE_HOME/admin/SunMC/cdump
user_dump_dest = $ORACLE_HOME/admin/SunMC/udump
utl_file_dir=$ORACLE_HOME/admin/SunMC/udump

db_block_size = 8192

remote_login_passwordfile = exclusive

os_authent_prefix = \"\"

# The following parameters are needed for the Advanced Replication Option
#job_queue_processes = 4
#job_queue_interval = 60
#distributed_transactions = 10
#open_links = 4

# Uncomment the following line when your listener is configured for SSL
# (listener.ora and sqlnet.ora)
#

compatible = \"8.1.0\"
sort_area_size = 65536
sort_area_retained_size = 65536

# indicate explicit local listener for Sun Management Center DB
#
#
# using multi-thread mode
#
#
#
MTS_DISPATCHERS = \"(PROTOCOL=TCP)\"
LOCAL_LISTENER = \"(ADDRESS_LIST = (ADDRESS = (PROTOCOL = IPC)(KEY = $sid_name))(ADDRESS=(PROTOCOL=TCP)(PORT=$SMCDB_PORT)(HOST=$SMCDB_HOST)))\"" > $init_file

    if [ -f $ORACLE_HOME/dbs/init${ORACLE_SID}.ora ] ; then
	/usr/bin/rm -f $ORACLE_HOME/dbs/init${ORACLE_SID}.ora
    fi
    /usr/bin/ln -s $init_file $ORACLE_HOME/dbs >/dev/null 2>&1
 fi
    return 0
}

# smcdb_configure_initora 
# configure database initialization file
#  This section has been replaced with the next set of functions
#  which provide the functionality requested by RFE#
# 
smcdb_configure_initora () {
    
    smc_run_memconfig=0

    init_file="$ORACLE_HOME/admin/SunMC/pfile/initSunMC.ora"
    dbase_file="$VAROPTDIR/cfg/dbase.cfg"

    db_setupEnvironment
    [ $? -ne 0 ] && return 1

    smc_retstat=0
    smc_verify_current_setup
    smc_retstat=$?

    if [ $smc_retstat -ne 0 ]; then
      smc_run_memconfig=1
      if [ $smc_retstat -eq 1 ]; then
         echologverbose "SunMC database configuration files missing."
         return 1
      elif [ $smc_retstat -eq 2 ]; then
         echologverbose "Database initialization parameter file missing."
      elif [ $smc_retstat -eq 3 ]; then
         echologverbose "Database consistency information missing."
      else
         echologverbose "Database configuration files different from original."
      fi
   fi

    SMC_MEMSIZE=0
    smc_get_physical_memory
    if [ $? -ne 0 ]; then 
      echologverbose "Error identifying physical memory for SunMC server"
      return 1
    fi

    SMC_CONFIG=""; SMC_MEM_CONFIG=0
    smc_get_current_memconfig $SMC_CONFIG_FILE $SMC_MEMSIZE
    if [ $? -ne 0 ]; then
      echologverbose "Error identifying standard database configuration for SunMC server"
      return 1
    fi

    SMC_STANDARD_LIMIT=0
    smc_get_config_section_key_value $SMC_CONFIG_FILE db_mem_limit standard_limit SMC_STANDARD_LIMIT 
    if [ $? -ne 0 ]; then
      echologverbose "Error retrieving standard redolog size for SunMC server"
      return 1
    fi
    SMC_MEM_CONFIG=`/usr/bin/expr $SMC_MEM_CONFIG \* $SMC_STANDARD_LIMIT / 100`

    #SMC_MEMSIZE, SMC_CONFIG and SMC_MEM_CONFIG need to be checked against the 
    # configuration file "dbase.cfg" old entries
    #
    smc_memsize_old=0
    smc_config_old=""
    smc_oramem_old=0

    smc_memsize_old=`/usr/bin/egrep '^physicalMemory=' $dbase_file | /usr/bin/cut -f2 -d=`
    smc_config_old=`/usr/bin/egrep '^memoryConfig=' $dbase_file | /usr/bin/cut -f2 -d=`
    smc_oramem_old=`/usr/bin/egrep '^oraMemory=' $dbase_file | /usr/bin/cut -f2 -d=`

    if [ -z "$smc_memsize_old" -o "$SMC_MEMSIZE" -lt "$smc_memsize_old" ]; then
      smc_run_memconfig=1    
    elif [ "$SMC_MEMSIZE" -ge "$smc_memsize_old" -a "$SMC_MEM_CONFIG" -gt "$smc_oramem_old" ]; then
      smc_run_memconfig=1
    elif [ "$SMC_MEMSIZE" -gt "$smc_memsize_old" -a "$smc_config_old" = "custom" ]; then
      smc_run_memconfig=1
      SMC_CONFIG="custom"
      SMC_MEM_CONFIG=$smc_oramem_old
   fi 

    SMC_REDOLOG_SIZE=0
    smc_get_config_section_key_value $SMC_CONFIG_FILE db_redolog_file size SMC_REDOLOG_SIZE 
    if [ $? -ne 0 ]; then
      echologverbose "Error retrieving standard redolog size for SunMC server"
      return 1
    fi

    SMC_REDOLOG_SIZE=`/usr/bin/expr $SMC_REDOLOG_SIZE \* 3` 
    db_check_avail_disk_size "$ORA_DATADIR" $SMC_REDOLOG_SIZE
    if [ $? -ne 0 ]; then 
      echologverbose "Not enough disk space to resize redolog file"
      return 1
    fi

    if [ "$smc_run_memconfig" -eq 1 ]; then
      echologverbose "Configuring database initialization parameter file"
      smc_retstat=0

      $BASEDIR/sbin/db-memconfig.sh -m $SMC_MEM_CONFIG -d $SMC_REDOLOG_SIZE
      smc_retstat=$?

      if [ $smc_retstat -ne 0 ]; then
        echologverbose 'Error configuring database initialization parameter file. Return status: $2' "$smc_retstat"
        return 1
      fi
    fi
#
#
    /usr/bin/chmod u+w $init_file
    if [ -f $ORACLE_HOME/dbs/init${ORACLE_SID}.ora ]; then
	/usr/bin/rm -f $ORACLE_HOME/dbs/init${ORACLE_SID}.ora
    fi
    /usr/bin/ln -s $init_file $ORACLE_HOME/dbs >/dev/null 2>&1

    return 0
}

# Check database listener port is free or not
# Input: $1 = port number
# Returns : 0 if port not busy, else returns 1
# 
#
smcdb_check_port_number() {

    
    /usr/bin/netstat -an | /usr/bin/grep "\*\.$1 " >/dev/null 2>&1
    [ $? -eq 0 ] && return 1

    /usr/bin/grep -w "$1/tcp" /etc/services >/dev/null 2>&1
    [ $? -eq 0 ] && return 1

    return 0
}



remove_db_data() {

   su - $SMCORAU -c "$BASEDIR/lib/sbin/sm_setup_db.sh -i" >> $DB_LOGFILE 2>&1
   retcode=$?
   
   if [ $retcode -ne 0 ]; then
      echolog "FAILED to clean database data"
      exit_SunMC "$DATABASE_ERROR"
   fi

}

remove_dat_files() {

    if [ -d $VARDIR ] ; then
	/usr/bin/rm -f $VARDIR/discovery*.dat
	/usr/bin/rm -f $VARDIR/discovery*.x
	/usr/bin/rm -rf $VARDIR/discovery
	/usr/bin/rm -f $VARDIR/topology+view*.dat
	/usr/bin/rm -f $VARDIR/topology-modules-d.dat
	/usr/bin/rm -f $VARDIR/cfgserver-modules-d.dat
	/usr/bin/rm -f $VARDIR/event-modules-d.dat
	/usr/bin/rm -f $VARDIR/metadata-modules-d.dat
	/usr/bin/rm -f $VARDIR/trap-modules-d.dat
	/usr/bin/rm -f $VARDIR/schedule.dat

        # Remove changes to module settings.
        (cd $VARDIR; `cat $VARDIR/base-modules-d.dat | awk '{files=files $1 ".dat "} END {print "/usr/bin/rm " files}'`) >/dev/null 2>&1

    fi
}

#
# 
#
smcdb_check_memory_available() {
    if [ -n "$RELOCATED_ROOT"  -a "$RELOCATED_ROOT" != "/" ] ; then
        #cant check, only warn
        echolog 'A minimum of 512 MB RAM is required to run the Sun Management Center 3.5 Update 1 Server.'
        echolog "Before doing setup, ensure you have 512 MB RAM."
        return
    fi
    
    MEMSIZE=`/usr/sbin/prtconf | grep "Memory size: " | cut -f3 -d' '`

    if [ "$MEMSIZE" -lt "512" ]; then
        echolog 'A minimum of 512 MB RAM is required to run the Sun Management Center 3.5 Update 1 Server.'
        echolog 'Current system has $2 MB RAM.' "$MEMSIZE"    
    
        checkString "$PROGNAME" "es-inst"
        if [ $? -eq 0 ] ; then
            echolog "Can not continue to install Server Layer."
            exit_SunMC "$DATABASE_ERROR"
        else
            echolog "Can not continue to setup Sun Management Center DB."
            exit_SunMC "$DATABASE_ERROR"
        fi
    fi

    MEMSIZE=`/usr/bin/expr $MEMSIZE \* 1024 \* 1024 / 2`

}

# Given a HEX or Octal number, returns decimal equivalant.
# 
make_radix_10()
{
  radix=`/usr/bin/echo $1 | /usr/bin/cut -c 1-2 2> /dev/null  `
  [ "$radix" = "0x" -o "$radix" = "0X" ] && temp_no=`/usr/bin/echo $1 | /usr/bin/sed "s/$radix//"` && /usr/bin/echo "{ibase=16;x=$temp_no;x}" | /usr/bin/bc && return 0
  radix=`/usr/bin/echo $1 | /usr/bin/cut -c 1-1 2> /dev/null `
  [ "$radix" = "0" -o "$radix" = "O" ] && temp_no=`/usr/bin/echo $1 | /usr/bin/sed "s/$radix//"` && /usr/bin/echo "{ibase=8;x=$temp_no;x}" | /usr/bin/bc && return 0
  /usr/bin/echo $1 
  return 0
}

smcdb_check_system() {
    #
    # set sharing memory for oracle in /etc/system
    #
    echologverbose "Checking /etc/system file..."
    echologverbose ""

    SYSTEM_TEMP=/tmp/tmp1.s_$$
    TEMP_FILE=/tmp/tmp2.s_$$
 
    # It is MUST to remove this file before updating /etc/system file 
    # otherwise, this leaves a BUG security hole.
    # Please refer BUGID:4620473 for more details
    # 
    /usr/bin/rm -f ${TEMP_FILE}
    /usr/bin/rm -f ${SYSTEM_TEMP}

    /usr/bin/cp /etc/system $SYSTEM_TEMP

    DETECT_SUNMC_MODS=`grep "This file has been modified by Sun" $SYSTEM_TEMP`

    SHMMAX=`/usr/bin/grep "set shmsys:shminfo_shmmax" "$SYSTEM_TEMP" | /usr/bin/grep -v "[ ]*\*" | /usr/bin/cut -f2 -d'='`
    SHMMIN=`/usr/bin/grep "set shmsys:shminfo_shmmin" "$SYSTEM_TEMP" | /usr/bin/grep -v "[ ]*\*" | /usr/bin/cut -f2 -d'='`
    SHMMNI=`/usr/bin/grep "set shmsys:shminfo_shmmni" "$SYSTEM_TEMP" | /usr/bin/grep -v "[ ]*\*" | /usr/bin/cut -f2 -d'='`
    SHMSEG=`/usr/bin/grep "set shmsys:shminfo_shmseg" "$SYSTEM_TEMP" | /usr/bin/grep -v "[ ]*\*" | /usr/bin/cut -f2 -d'='`
    SEMMNI=`/usr/bin/grep "set semsys:seminfo_semmni" "$SYSTEM_TEMP" | /usr/bin/grep -v "[ ]*\*" | /usr/bin/cut -f2 -d'='`
    SEMMSL=`/usr/bin/grep "set semsys:seminfo_semmsl" "$SYSTEM_TEMP" | /usr/bin/grep -v "[ ]*\*" | /usr/bin/cut -f2 -d'='`
    SEMMNS=`/usr/bin/grep "set semsys:seminfo_semmns" "$SYSTEM_TEMP" | /usr/bin/grep -v "[ ]*\*" | /usr/bin/cut -f2 -d'='`
    SEMOPM=`/usr/bin/grep "set semsys:seminfo_semopm" "$SYSTEM_TEMP" | /usr/bin/grep -v "[ ]*\*" | /usr/bin/cut -f2 -d'='`
    SEMVMX=`/usr/bin/grep "set semsys:seminfo_semvmx" "$SYSTEM_TEMP" | /usr/bin/grep -v "[ ]*\*" | /usr/bin/cut -f2 -d'='`

    # In case of GNOME, /etc/system contains hex entries
    #
    SHMMAX=`make_radix_10 $SHMMAX ` 
    SHMMIN=`make_radix_10 $SHMMIN `
    SHMMNI=`make_radix_10 $SHMMNI `
    SHMSEG=`make_radix_10 $SHMSEG `
    SEMMNI=`make_radix_10 $SEMMNI `
    SEMMSL=`make_radix_10 $SEMMSL `
    SEMMNS=`make_radix_10 $SEMMNS `
    SEMOPM=`make_radix_10 $SEMOPM `
    SEMVMX=`make_radix_10 $SEMVMX `




    SHMMIN_REQ="1"

    if [ -n "$SHMMNI" -a -z "$DETECT_SUNMC_MODS" -o -n "$SHMMNI" -a "$SHMMNI" -lt 100 ]; then
        SHMMNI_REQ=`echo "{x=100 + $SHMMNI; x }" | /usr/bin/bc`
    else
        SHMMNI_REQ="100"
    fi

    SHMSEG_REQ="10"

    if [ -n "$SEMMNI" -a -z "$DETECT_SUNMC_MODS" -o -n "$SEMMNI" -a "$SEMMNI" -lt 100 ]; then
        SEMMNI_REQ=`echo "{x=100 + $SEMMNI; x }" | /usr/bin/bc`
    else
        SEMMNI_REQ="100"
    fi

    if [ -n "$SEMMSL" -a -z "$DETECT_SUNMC_MODS" -o -n "$SEMMSL" -a "$SEMMSL" -lt 115 ]; then
        SEMMSL_REQ=`echo "{x=115 + $SEMMSL; x }" | /usr/bin/bc`
    else
        SEMMSL_REQ="115"
    fi

    if [ -n "$SEMMNS" -a -z "$DETECT_SUNMC_MODS" -o -n "$SEMMNS" -a "$SEMMNS" -lt 200 ]; then
        SEMMNS_REQ=`echo "{x=200 + $SEMMNS; x }" | /usr/bin/bc`
    else
        SEMMNS_REQ="200"
    fi

    SEMOPM_REQ="100"
    SEMVMX_REQ="32767"

    SYSTEM_NEEDCHANGE="0"

    if [ $? -ne 0 ]; then
        return "1"
    fi

    # Note that the first comment line is grepped above.
    # See variable DETECT_SUNMC_MODS.
    if [ -z "$DETECT_SUNMC_MODS" ]; then
        echo "************************************************************************" >> $SYSTEM_TEMP
        echo "* This file has been modified by Sun (TM) Management Center 3.5 Update 1 setup. *" >> $SYSTEM_TEMP
        echo "*     	 	DO NOT REMOVE THESE TWO COMMENTS LINES.              *" >> $SYSTEM_TEMP
        echo "************************************************************************" >> $SYSTEM_TEMP
        SYSTEM_NEEDCHANGE="1"
    fi


    if [ -z "$SHMMAX" ]; then
        SYSTEM_NEEDCHANGE="1"
        echo "set shmsys:shminfo_shmmax=$MEMSIZE" >> $SYSTEM_TEMP
    else
        tmpvar=`echo "{x=0; if ( $SHMMAX < $MEMSIZE ) x=1; x}" | /usr/bin/bc`
        if [ $tmpvar -eq 1 ]; then
            repl_cmd=`echo "s/\\(set shmsys:shminfo_shmmax\\).*/\\1=$MEMSIZE/"`
            /usr/bin/cat $SYSTEM_TEMP | /usr/bin/sed -e "$repl_cmd" > $TEMP_FILE
            if [ $? -eq 0 ]; then
                SYSTEM_NEEDCHANGE="1"
                /usr/bin/mv $TEMP_FILE $SYSTEM_TEMP
            fi
        fi
    fi


    if [ "$SHMMIN" -lt "$SHMMIN_REQ" -o -z "$SHMMIN" ]; then
        if [ -z "$SHMMIN" ]; then
            SYSTEM_NEEDCHANGE="1"
            echo "set shmsys:shminfo_shmmin=$SHMMIN_REQ" >> $SYSTEM_TEMP
        else
            repl_cmd=`echo "s/\\(set shmsys:shminfo_shmmin\\).*/\\1=$SHMMIN_REQ/"`
            /usr/bin/cat $SYSTEM_TEMP | /usr/bin/sed -e "$repl_cmd" > $TEMP_FILE
            if [ $? -eq 0 ]; then
                SYSTEM_NEEDCHANGE="1"
                /usr/bin/mv $TEMP_FILE $SYSTEM_TEMP
            fi
        fi
    fi

    if [ "$SHMMNI" -lt "$SHMMNI_REQ" -o -z "$SHMMNI"  ]; then
        if [ -z "$SHMMNI" ]; then
            SYSTEM_NEEDCHANGE="1"
            echo "set shmsys:shminfo_shmmni=$SHMMNI_REQ" >> $SYSTEM_TEMP
        else
            repl_cmd=`echo "s/\\(set shmsys:shminfo_shmmni\\).*/\\1=$SHMMNI_REQ/"`
            /usr/bin/cat $SYSTEM_TEMP | /usr/bin/sed -e "$repl_cmd" > $TEMP_FILE
            if [ $? -eq 0 ]; then
                SYSTEM_NEEDCHANGE="1"
                /usr/bin/mv $TEMP_FILE $SYSTEM_TEMP
            fi
        fi
    fi

    if [ "$SHMSEG" -lt "$SHMSEG_REQ" -o -z "$SHMSEG"  ]; then
        if [ -z "$SHMSEG" ]; then
            SYSTEM_NEEDCHANGE="1"
            echo "set shmsys:shminfo_shmseg=$SHMSEG_REQ" >> $SYSTEM_TEMP
        else
            repl_cmd=`echo "s/\\(set shmsys:shminfo_shmseg\\).*/\\1=$SHMSEG_REQ/"`
            /usr/bin/cat $SYSTEM_TEMP | /usr/bin/sed -e "$repl_cmd" > $TEMP_FILE
            if [ $? -eq 0 ]; then
                SYSTEM_NEEDCHANGE="1"
                /usr/bin/mv $TEMP_FILE $SYSTEM_TEMP
            fi
        fi
    fi

    if [ "$SEMMNI" -lt "$SEMMNI_REQ" -o -z "$SEMMNI" ]; then
        if [ -z "$SEMMNI" ]; then
            SYSTEM_NEEDCHANGE="1"
            echo "set semsys:seminfo_semmni=$SEMMNI_REQ" >> $SYSTEM_TEMP
        else
            repl_cmd=`echo "s/\\(set semsys:seminfo_semmni\\).*/\\1=$SEMMNI_REQ/"`
            /usr/bin/cat $SYSTEM_TEMP | /usr/bin/sed -e "$repl_cmd" > $TEMP_FILE
            if [ $? -eq 0 ]; then
                SYSTEM_NEEDCHANGE="1"
                /usr/bin/mv $TEMP_FILE $SYSTEM_TEMP
            fi
        fi
    fi

    if [ "$SEMMSL" -lt "$SEMMSL_REQ" -o -z "$SEMMSL" ]; then
        if [ -z "$SEMMSL" ]; then
            SYSTEM_NEEDCHANGE="1"
            echo "set semsys:seminfo_semmsl=$SEMMSL_REQ" >> $SYSTEM_TEMP
        else
            repl_cmd=`echo "s/\\(set semsys:seminfo_semmsl\\).*/\\1=$SEMMSL_REQ/"`
            /usr/bin/cat $SYSTEM_TEMP | /usr/bin/sed -e "$repl_cmd" > $TEMP_FILE
            if [ $? -eq 0 ]; then
                SYSTEM_NEEDCHANGE="1"
                /usr/bin/mv $TEMP_FILE $SYSTEM_TEMP
            fi
        fi
    fi

    if [ "$SEMMNS" -lt "$SEMMNS_REQ" -o -z "$SEMMNS" ]; then
        if [ -z "$SEMMNS" ]; then
            SYSTEM_NEEDCHANGE="1"
            echo "set semsys:seminfo_semmns=$SEMMNS_REQ" >> $SYSTEM_TEMP
        else
            repl_cmd=`echo "s/\\(set semsys:seminfo_semmns\\).*/\\1=$SEMMNS_REQ/"`
            /usr/bin/cat $SYSTEM_TEMP | /usr/bin/sed -e "$repl_cmd" > $TEMP_FILE
            if [ $? -eq 0 ]; then
                SYSTEM_NEEDCHANGE="1"
                /usr/bin/mv $TEMP_FILE $SYSTEM_TEMP
            fi
        fi
    fi

    if [ "$SEMOPM" -lt "$SEMOPM_REQ" -o -z "$SEMOPM" ]; then
        if [ -z "$SEMOPM" ]; then
            SYSTEM_NEEDCHANGE="1"
            echo "set semsys:seminfo_semopm=$SEMOPM_REQ" >> $SYSTEM_TEMP
        else
            repl_cmd=`echo "s/\\(set semsys:seminfo_semopm\\).*/\\1=$SEMOPM_REQ/"`
            /usr/bin/cat $SYSTEM_TEMP | /usr/bin/sed -e "$repl_cmd" > $TEMP_FILE
            if [ $? -eq 0 ]; then
                SYSTEM_NEEDCHANGE="1"
                /usr/bin/mv $TEMP_FILE $SYSTEM_TEMP
            fi
        fi
    fi

    if [ "$SEMVMX" -lt "$SEMVMX_REQ" -o -z "$SEMVMX" ]; then
        if [ -z "$SEMVMX" ]; then
            SYSTEM_NEEDCHANGE="1"
            echo "set semsys:seminfo_semvmx=$SEMVMX_REQ" >> $SYSTEM_TEMP
        else
            repl_cmd=`echo "s/\\(set semsys:seminfo_semvmx\\).*/\\1=$SEMVMX_REQ/"`
            /usr/bin/cat $SYSTEM_TEMP | /usr/bin/sed -e "$repl_cmd" > $TEMP_FILE
            if [ $? -eq 0 ]; then
                SYSTEM_NEEDCHANGE="1"
                /usr/bin/mv $TEMP_FILE $SYSTEM_TEMP
            fi
        fi
    fi

    /usr/bin/rm -f ${TEMP_FILE}
}


#  For server and/or agent installation
#  migrate the cfg data, run db-import.sh
#  for server installs
#  Input : none
#  Returns : 1 if previous version files imported
#            else 0
#

import_sunmc_data () {
    exportedDataDir=$VAROPTDIR/upgrade
    return_value=0
    RUN_DB_IMPORT="NO"

    # Data migration from HA node presently disabled .. so return.
    # 
    [ "$setup_HA_flag" = "1" ] && return 0
    
    if [ $no_agent -eq 0 -o $no_server -eq 0 ]; then
       if [ -d /var/opt/SUNWsymon/2x -a ! -f /var/opt/SUNWsymon/2x/db-cfg-import.log ] || [ -d /var/opt/SUNWsymon/2x/db -a ! -f /var/opt/SUNWsymon/2x/db-import.log ]; then
          # The following migration cases are handled here:
          # - 2.1 agent only -> 3.5 server
          # - 2.1 server -> 3.5 server
          # - 3.0 agent only -> 3.5 server

          echolog ''
          READ_RESPONSE_ONCE=0
          fetch_response_yes_no "TAG=IMPORT_PREVIOUS_DATA" 'Do you want to import your previous data '  
          [ $? -gt 0 ] && exit_SunMC_setup "$SUMMARY_READ_ERROR"
          saveAutoConfig "IMPORT_PREVIOUS_DATA" "$answer"
          #echolog ''
          if [ "$answer" = "0" ]; then

	     RUN_DB_IMPORT="NO"
             echologverbose "Setup will not import previous data."
          else
             #  import cfg data if data exists
             #
             if [ -d /var/opt/SUNWsymon/2x/cfg ]; then
                 OLDDATADIR=/var/opt/SUNWsymon/2x
                 migrate_cfg_files
                 return_value=1
             fi

             #  run db-import.sh if only if the following conditions are true
             if [ $no_server -eq 0 ]; then
                if [ -d /var/opt/SUNWsymon/2x/db -a ! -f /var/opt/SUNWsymon/2x/db-import.log ]; then
                   RUN_DB_IMPORT="YES"
                else
                   RUN_DB_IMPORT="NO"
                fi
             else # not server install
                RUN_DB_IMPORT="NO"
             fi
          fi

       elif [ -d "$exportedDataDir" ] ; then
           # The following migration cases are handled here:
           # - 3.5 agent only -> 3.5 server (no metafile, cfg exists)
           # - 3.0 server -> 3.5 server upgrade (metafile and cfg exist)
           # - 3.0 server -> 3.5 server KeepData (NO metafile, SunMCDB02* and
	   #   cfg exist)
           # - 3.5 server -> 3.5 server (metafile and cfg exist)

           if [ -f $exportedDataDir/db/SUNMC_db_upgrade.meta ] ; then
               exportedVersion=`get_value_from_cfgfile $exportedDataDir/db/SUNMC_db_upgrade.meta core_product_version =`
               metafile_exists=1
           else
               metafile_exists=0
           fi

           if [ "$exportedVersion" = "3.0" -o -d "$VAROPTDIR/SunMCDB02.backup" -o -d "$VAROPTDIR/SunMCDB02" ] ; then
               echologverbose "Found previous Sun Management Center data"
               echologverbose "Previous data is from Sun Management Center 3.0"

               echolog ''
               READ_RESPONSE_ONCE=0
               fetch_response_yes_no "TAG=IMPORT_PREVIOUS_DATA" 'Do you want to import your previous data '  
               [ $? -gt 0 ] && exit_SunMC_setup "$SUMMARY_READ_ERROR"
               saveAutoConfig "IMPORT_PREVIOUS_DATA" "$answer"
               if [ "$answer" = "0" ]; then
                   RUN_DB_IMPORT="NO"
                   echologverbose "Setup will not import previous data."
                  
                   # Once user chose not to import previous data, it will be removed.
                   # Database dependant add-on should also clean up their data that 
                   # was not migrated as per MIGRAE_DATA setting.
                   db_migr_cleanup_user_assoc_files SUNMC
                   $CMD_RM -rf "$VAROPTDIR/SunMCDB02.backup" "$VAROPTDIR/SunMCDB02" 
                   $CMD_RM -rf "$VAROPTDIR/upgrade/bin" "$VAROPTDIR/upgrade/cfg" 
   
                   MIGRATE_DATA=0
                   export MIGRATE_DATA

               else
                   migrate_and_import_30_data
                   [ $? -ne 0 ] && exit 1

                   MIGRATE_DATA=1
                   export MIGRATE_DATA
                   return 0
               fi
           elif [ "$exportedVersion" = "3.5" ] ; then
               echologverbose "Found previous Sun Management Center data"
               echologverbose "Exported data is from Sun Management Center 3.5 Update 1"

                   # Remove the db_upgrade directory that belonged to 3.5 GA installation.
                   # Otherwise, db-patch-schema.sh will not be applied, and new PU1
                   # database will not be correclty setup. As noted below, database
                   # needs to be setup in order to run import. If user shose not to
                   # import data, database has to be setup and upgrade scripts applied.

                   $CMD_RM -rf $VAROPTDIR/db_upgrade 
               
               echolog ''
               READ_RESPONSE_ONCE=0
               fetch_response_yes_no "TAG=IMPORT_PREVIOUS_DATA" 'Do you want to import your previous data '  
               [ $? -gt 0 ] && exit_SunMC_setup "$SUMMARY_READ_ERROR"
               saveAutoConfig "IMPORT_PREVIOUS_DATA" "$answer"
               if [ "$answer" = "0" ]; then
                   RUN_DB_IMPORT="NO"
                   echologverbose "Setup will not import previous data."
                  
                   # Clean up the metafiles left over from 3.5 GA, so that
                   # after 3.5 GA to PU1 upgrade re-setup will not think
                   # that there is data to be imported.
                   # Once user chooses not to import the data during the 
                   # initial upgrade setup, the data is lost.
                   # PRM and other database dependant add-ons should also clean up
                   # their data in this case, based on MIGRATE_DATA flag set to 0.

                    db_migr_cleanup_user_assoc_files "$SUNMC_USER"
                    db_migr_cleanup_user_assoc_files "$SUNMC_SCHEMA"

                  # Core cfg and bin directories also need to be cleaned up.
                  # If they remain subsequent re-setups -F will try to import
                  # this previous agent data. This does not affect add-on
                  # configuration files, as thei cgf and bin data is stored
                  # under $VAROPTDIR/upgrade/<add-onn_name>

	          $CMD_RM -rf $VAROPTDIR/upgrade/cfg
                  $CMD_RM -rf $VAROPTDIR/upgrade/bin
 
                  MIGRATE_DATA=0
                  export MIGRATE_DATA 
               else
                   MIGRATE_DATA=1
                   export MIGRATE_DATA

                   # Note: we cannot import 3.5 until database has been
                   # upgraded. So we have to delay the import for now.
                   MIGRATE_SUNMC35=1

                   return 0
               fi
           elif [ "$metafile_exists" -eq 1 ] ; then
               echologverbose 'Unknown version of SunMC export: $2' "$exportedVersion"
               return 1
           elif [ -d "$exportedDataDir/cfg" ] ; then
               # Database metafile doesn't exist.
               # This case happens when there is no server layer in the
               # previous installation (no database metafile). Normally,
               # agent-only migration is done by es-setup; but we can end up
               # here if the user migrated from an agent-only installation to
               # a server installation.

               migrate_agent_data_only
               return 1
           fi
       else
          echologverbose 'Data from previous version is not available or already imported.'
          echologverbose ''
       fi
    fi

    return $return_value
}

# Migrate and import 3.0 or 3.5 cfg files.
# OLDDATADIR should be set to the base upgrade directory ($VAROPTDIR/upgrade)
# CFGDIR should be set to $VAROPTDIR/cfg
migrate_cfg_files () {
    CFGDIR=$VAROPTDIR/cfg
    if [ -d ${OLDDATADIR}/cfg ]; then
        OLDCFG=$OLDDATADIR/cfg
        BINDIR=$VAROPTDIR/bin
        cfg_cnt=`$CMD_LS -1 ${OLDDATADIR}/cfg |/usr/bin/wc -l`
        if [ $cfg_cnt -gt 0 ]; then
            echolog "Migrating configuration files..."

            # Check if this is a server layer cfg migration
            # 
            # - the existence of $OLDCFG/dbase.cfg covers migration from 3.0
            #   or 3.5
            # - the existence of /var/opt/SUNWsymon/2x/db covers migration
            #   from 2.x. We explicitly use /var/opt/SUNWsymon/2x/db here
            #   instead of $OLDDATADIR so that it will not match a false
            #   positive during 3.0 migration.
            if [ -f "$OLDCFG/dbase.cfg" -o -d /var/opt/SUNWsymon/2x/db ] ; then
                is_server_cfg=1
            else
                is_server_cfg=0
            fi

            #
            # Copy old cfg files over
            #
            cfgdirs=`/usr/bin/find $OLDDATADIR/cfg -type d -print`
            if [ "$cfgdirs" != "" ] ; then
                # Exclude all cfgfiles that need to be merged or have been
                # replaced/removed in 3.5.

                exclude_files="\
^deviceinfo\.conf\$|\
^base-config\.x\$|\
-(name2oid|oid2name|oids)\.(pag|dir)\$|\
-oids-d\.dat\$|\
-engine-d\.dat\$|\
-community\.dat\$|\
-community\.dat\.old\$|\
-usmusertbl-d\.dat\$|\
-usmuser-d\.dat\$|\
-usmaclgrps-d\.dat\$|\
^\.license\.packs\$|\
^\.license\$|\
^domain-config\.x\$|\
^base-consoles_3_0_00_00-j\.x\$|\
^base-modules-d\.dat\$|\
^esusers\$|\
^logview-acl\.dat\$|\
^composite-objects-families-j\.x\$|\
^icmp-server-families-j\.x\$|\
^module-module-families-j\.x\$|\
^none-server-families-j\.x\$|\
^snmp-server-families-j\.x\$|\
^dbase\.cfg\$|\
^mib2-system\.dat\$|\
^sfix\.log\$|\
^tools-extension-j\.x\$|\
^symon-help-j\.x\$|\
^server-global-keys\.x\$|\
^auth-suppl\.dat\$|\
^cfgserver-users\.dat\$|\
^config-id\.dat\$|\
^config-diffs\.dat\$|\
^javaserver\.properties\$|\
^discovery-j\.x\$|\
^console-tools\.cfg\$|\
^(cfgserver|event)-modules-d\.dat\$"

                cfgfiles=`/usr/bin/find $OLDDATADIR/cfg -type f | /usr/bin/sed -e "s#$OLDDATADIR/cfg/##" | /usr/bin/egrep -v $exclude_files`
                for file in $cfgfiles ; do
                    dir=$CFGDIR/`/usr/bin/dirname $file`
                    if [ ! -d "$dir" ] ; then
                        $CMD_MKDIR -p "$dir"
                    fi

                    $CMD_CP -p $OLDDATADIR/cfg/$file $CFGDIR/$file 2>>$LOGFILE
                    if [ $? -ne 0 ] ; then
                        echologverbose 'Failed to copy $2 to $3' "$OLDDATADIR/cfg/$file" "$CFGDIR/$file"
                        echolog "Error while migrating configuration files"
                        exit 1
                    fi
                    #
                    # Fix perms for the .dat files as they contain
                    # community string related info. which should be readable/
                    # writable for the owner only
                    #
                    $CMD_ECHO "$CFGDIR/$file" | $CMD_GREP -e '\.dat$' > /dev/null 2>&1
                    if [ $? -eq 0 ]; then
                    	$CMD_CHMOD 600 $CFGDIR/$file
                    fi
                done

                if [ "$is_server_cfg" -eq 1 ] ; then
                    migrate_agent_cfgfiles
                    migrate_server_cfgfiles
                else
                    migrate_agent_cfgfiles
                fi

                #
                # migrate 3.0 or 3.5 platform instances
                #
                migrate_30_platform_instances

                #
                # migrate snmpv1 community string
                #
                migrate_community_string
            fi
        fi
    fi

    if [ -d ${OLDDATADIR}/mcp ]; then
	if [ ! -d $VAROPTDIR/mcp ]; then
	    /usr/bin/mkdir -p $VAROPTDIR/mcp
	fi
	$CMD_MV -f ${OLDDATADIR}/mcp/* $VAROPTDIR/mcp 2>/dev/null
    fi
}

migrate_and_import_30_data () {

    CFGDIR=$VAROPTDIR/cfg
    OLDDBDIR=$VAROPTDIR/SunMCDB02
    OLDDBBAK=$VAROPTDIR/SunMCDB02.backup
    OLDDATADIR=$VAROPTDIR/upgrade

    # Make sure the preserved data directory has right permissions
    chmod -R 777 $OLDDATADIR/db


    # import old cfgfiles
    migrate_cfg_files

    # If there are DB tables leftover, upgrade and export them now
    # (could not during es-inst because database wasn't available)
    if [ -d "$OLDDBBAK" -o -h "$OLDDBBAK" ] ; then
        if [ -d "$OLDDBDIR" -o -h "$OLDDBDIR" ] ; then
            echolog 'Warning: $2 already exists. Assuming it is from previous upgrade attempt.' "$OLDDBDIR"
            echolog 'Upgrade will attempt to proceed from there; to force upgrade to use original backup data in $2, remove $3 first.' "$OLDDBBAK" "$OLDDBDIR"
        else
            $CMD_MV $OLDDBBAK $OLDDBDIR
            if [ $? -ne 0 ] ; then
                echolog 'Unable to move $2 to $3: aborting migration' "$OLDDBBAK" "$OLDDBDIR"
                exit 1
            fi

            # If SunMCDB02 was a symlink, we will need to rename what it
            # links to as well, since es-inst would have rename that as well
            # in order that the 3.0 es-uninst would not destroy the tablespace
            # files.
            if [ -h "$OLDDBDIR" ] ; then
                realpath=`/usr/bin/ls -ld ${OLDDBDIR} | /usr/bin/sed -e 's/^.*-> //' `
                origpath=`/bin/echo $realpath | /usr/bin/sed -e 's/\.backup$//' `
                if [ "$realpath" != "$origpath" ] ; then
                    $CMD_MV $realpath $origpath
                    if [ $? -ne 0 ] ; then
                        echolog 'Unable to rename $2 to $3' "$realpath" "$origpath"
                        exit 1
                    fi
                fi

                # Re-point the symlink to the original location, otherwise
                # anything that still relies on the link will fail.
                $CMD_RM -f $OLDDBDIR
                $CMD_LN -s $origpath $OLDDBDIR
                if [ $? -ne 0 ] ; then
                    echolog 'Unable to recreate symlink $2 -> $3' "$OLDDBDIR" "$origpath"
                    exit 1
                fi
            fi
        fi
    fi
    if [ -d "${OLDDBDIR}/oradata" ] ; then
        # 3.0 data has not yet been exported yet because Oracle 8.1.6 has
        # already been uninstalled when es-inst was run, and the tablespace
        # files have been left behind. Now we need to upgrade these tablespaces
        # to 8.1.7 and perform an export, so that in the next step, we can
        # import the data into the 3.5 database.

        # 3.0 Oracle 8.1.6 tablespace directory should have available
        # at least 51200k (50M) before the upgrade to 8.1.7 is attempted
        # to allow for the system tablespace to autoextend.
        #
        db_check_avail_disk_size "${OLDDBDIR}/oradata" 51200
        rstat=$?
        if [ "$rstat" -ne 0 ] ; then
         if [ "$rstat" -eq 1 ] ; then
          echolog 'The minimum amount of disk space required in $2 is $3' "${OLDDBDIR}/oradata" "50M"
         else
          echolog 'Error encountered identifying the amount of available disk space in $2' "${OLDDBDIR}/oradata"
         fi
          echolog "Exiting..."
          exit 1
        fi

        echolog "Migrating previous data to Sun Management Center 3.5 Update 1 database"
        echolog "Please wait, this may take a while to complete ..."

        ${TOOLS_DIR}/migrate-30-31.sh >> $LOGFILE
        if [ $? -ne 0 ] ; then
            # Rename SunMCDB02 back to .backup, so that user can retry setup
            # later after correcting problem(s).
            $CMD_MV $OLDDBDIR $OLDDBBAK

            echolog 'Migration error -- data NOT migrated.'
            echolog 'Log is in $2' "$LOGFILE"
            exit 1
        fi
    fi

    # Import data
    if [ -d $OLDDATADIR/db ] ; then
        tmplog=$TEMPDIR/import30-log.$$
        $CMD_RM -f $tmplog

        echolog "Importing previous data..."

        # Start database if not already up
        db_start_database

        # Prepare DB for import
        /usr/bin/su - $SMCORAU -c "
            . $BASEDIR/sbin/es-common.sh
            set_db_env
            cd \"$BASEDIR\";
            $ORACLE_HOME/bin/sqlplus /nolog @db/util/drop_sequences.sql $SUNMC_SCHEMA
            $ORACLE_HOME/bin/sqlplus /nolog @db/util/disable_primarykey.sql $SUNMC_SCHEMA
            $ORACLE_HOME/bin/sqlplus /nolog @db/util/clear_table_data.sql $SUNMC_SCHEMA
        " >> $LOGFILE 2>&1
        if [ $? -ne 0 ] ; then
            echolog "Error while preparing for import"
            exit 1
        fi

        db_migr_import_user SUNMC sunmc $tmplog 1
        if [ $? -ne 0 ] ; then
            echolog "Error occurred during import -- NO data imported"
            $CMD_RM -f $tmplog
            exit 1
        else
            $CMD_CAT $tmplog >> $LOGFILE
            $CMD_RM -f $tmplog

            # Clean up imported data and re-enable constraints
            /usr/bin/su - $SMCORAU -c ". $BASEDIR/sbin/es-common.sh; set_db_env;
                cd \"$BASEDIR\";
                $ORACLE_HOME/bin/sqlplus /nolog <<EOF
connect / as sysdba
drop table ${SUNMC_SCHEMA}.FKTEMP1 cascade constraints;
drop table ${SUNMC_SCHEMA}.FKTEMP2 cascade constraints;
EOF
                $ORACLE_HOME/bin/sqlplus /nolog @db/util/enable_primarykey.sql $SUNMC_SCHEMA
                $ORACLE_HOME/bin/sqlplus /nolog @db/util/enable_foreignkey.sql $SUNMC_SCHEMA
            " >> $LOGFILE 2>&1
            if [ $? -ne 0 ] ; then
                echolog "Error while cleaning up old data"
                exit 1
            fi

            # Success, now clean up the temporary junk we made
            echolog "Data successfully imported"

            # Re-create all the synonyms and grants.
            # As db-patch-schema creates synonyms conditionally, based on the
            # MIGRATE_DATA flag, they will not be re-created as part of 
            # patch_database_schema in this case (MIGRATE_DATA is 1).  
            # so 3.0 migration logic has to
            # do it itself in order to complete database setup.
            # Grants are re-runable without harm.

            /usr/bin/su - $SMCORAU -c ". $BASEDIR/sbin/es-common.sh; set_db_env;
            cd \"$BASEDIR\";
            $ORACLE_HOME/bin/sqlplus /nolog <<EOF
connect $SUNMC_SCHEMA/$SUNMC_SCHEMA_PWD
@db/build/grant-object-privs $SUNMC_USER
EOF
        " >> $LOGFILE 2>&1
           if [ $? -ne 0 ] ; then
               echolog "Error running sql: $2" $BASEDIR/db/build/grant-object-privs
               exit 1
           fi

            /usr/bin/su - $SMCORAU -c ". $BASEDIR/sbin/es-common.sh; set_db_env;
            cd \"$BASEDIR\";
            $ORACLE_HOME/bin/sqlplus /nolog <<EOF
connect $SUNMC_USER/$SUNMC_USER_PWD
@db/build/create-synonyms $SUNMC_SCHEMA
EOF
        " >> $LOGFILE 2>&1
           if [ $? -ne 0 ] ; then
               echolog "Error running sql: $2" $BASEDIR/db/build/create-synonyms.sql
               exit 1
           fi


            db_migr_cleanup_user_assoc_files SUNMC
            $CMD_RM -rf $OLDDBDIR $OLDDBBAK $OLDDATADIR/cfg $OLDDATADIR/bin
        fi

        fix_packmodule_table
        [ $? -ne 0 ] && exit 1

    else
        echolog "Could not find Sun Management Center 3.0 database data\!"
    fi

    return 0
}

fix_packmodule_table () {
    db_setupEnvironment
    tmpfile=$TEMPDIR/fixmod.tmp.$$
    /usr/bin/rm -f $tmpfile 2>/dev/null

    . $BASEDIR/db/cfg/dbadmin.cfg
    sql="update pack_module set PACK_ID=1 where MODULE_ID in
         (select module_id from module where name in
           ('kernel-reader-simple', 'a5xxx', 'config-dt')
         )"
    db_runSql "$sql" "$SUNMC_SCHEMA" "$SUNMC_SCHEMA_PWD" $tmpfile

    db_checkErr $tmpfile $LOGFILE
    if [ $? -ne 0 ] ; then
        echolog 'Unable to update pack_module table after migration'
        /usr/bin/rm -f $tmpfile 2>/dev/null
        return 1
    fi
    /usr/bin/rm -f $tmpfile 2>/dev/null
    return 0
}

# Clean up migration dirs after data has been successfully imported.
cleanup_migration_dirs () {
    CFGDIR=$VAROPTDIR/cfg
    CFGBAK=$VAROPTDIR/cfg-new.bak
    OLDDBDIR=$VAROPTDIR/SunMCDB02
    OLDDBBAK=$VAROPTDIR/SunMCDB02.backup

    # Cleanup metafiles that haven't been imported yet
    for metafile in $OLDDATADIR/db/*_db_upgrade.meta ; do
        # Cleanup files associated with metafile
        db_migr_cleanup_assoc_files $metafile
    done

    set_db_env
    $CMD_RM -rf $OLDDBDIR $OLDDBBAK > /dev/null 2>&1
    $CMD_RM -rf $ORACLE_HOME/admin/SunMC30 > /dev/null 2>&1
    $CMD_RM $ORACLE_HOME/dbs/initSunMC30.ora > /dev/null 2>&1
    $CMD_RM -rf $CFGBAK

    # Move old exported data aside for backup purposes
    # This is for diagnostic purposes only; we really don't need to keep
    # this directory there.
    if [ -d "$OLDDATADIR" ] ; then
        $CMD_RM -rf $OLDDATADIR.bak
        $CMD_MV $OLDDATADIR $OLDDATADIR.bak
    fi

}

patch_database_schema() {

# $1 - component. Currently, only "core" is supported.
# DB patching for addons has been deprecated and will probably go away
# in the actual 3.5 release.
#
    TOOLS_DIR=${BASEDIR}/lib/sbin

    . $BASEDIR/db/cfg/dbadmin.cfg

    CORE_UPGRADE_DIR=${BASEDIR}/db/upgrade
    CORE_DB_CFG_FILE=${BASEDIR}/db/cfg/db/dbadmin.cfg
    DB_UPGRADE_STATUS_FILE=${VAROPTDIR}/db_upgrade/upgrade_status
    ADDON_BASEDIR=${BASEDIR}/addons


    export CORE_UPGRADE_DIR
    export CORE_DB_CFG_FILE
    export ADDON_BASEDIR
    export DB_UPGRADE_STATUS_FILE

    # LOGDIR has been set up as LOGDIR=/var/opt/SUNWsymon/install

    if [ "$1" = "core" ] ; then

        #
        # Apply the appropriate core database schema patches
        # Check if the status file and directories exist.

        if [ ! -d ${VAROPTDIR}/db_upgrade ] ; then
            /usr/bin/mkdir ${VAROPTDIR}/db_upgrade
            /usr/bin/chmod -R 700 ${VAROPTDIR}/db_upgrade
            /usr/bin/chown smcorau ${VAROPTDIR}/db_upgrade
            /usr/bin/chgrp smcorag ${VAROPTDIR}/db_upgrade

            if [ $? -ne 0 ] ; then
                echolog 'ERROR creating $2 directory. ' "${VAROPTDIR}/db_upgrade"
                exit 1
            fi
        fi
        if [ ! -f $DB_UPGRADE_STATUS_FILE ] ; then
            /usr/bin/touch $DB_UPGRADE_STATUS_FILE
            /usr/bin/chmod -R 700 $DB_UPGRADE_STATUS_FILE
            /usr/bin/chown smcorau $DB_UPGRADE_STATUS_FILE
            /usr/bin/chgrp smcorag $DB_UPGRADE_STATUS_FILE

            if [ $? -ne 0 ] ; then
                echolog "ERROR setting up upgrade_status file. "
                exit 1
            fi
        fi

        # Get last successfully applied version of patch.

        old_version=`/usr/bin/cat $DB_UPGRADE_STATUS_FILE | /usr/bin/grep core | /usr/bin/cut -f2 -d' '`
        if [ -z "$old_version" ] ; then
            old_version=0
        fi
        component=core
        /usr/bin/su - $SMCORAU -c "${TOOLS_DIR}/db-patch-schema.sh $component $old_version $MIGRATE_DATA $schema_exists_flag" 
        if [ $? -ne 0 ] ; then
            echolog 'Failed to complete database schema upgrade for $2 database. ' "$component"
            exit 1
        fi

        # DB patching is no longer supported for addons.

    fi

}

# recreate_user $user $passwd $create_script
# - recreate SunMC user or schema user using $create_script. This should be
#   one of the build SQL scripts used to create the database schema.
# - aborts if failure detected.
# - this function is for dropping any existing SunMC schemas so that migrated
#   data can be imported. The database users are recreated because the import
#   needs users to import the data into.
recreate_user () {
    tmpfile=$TEMPDIR/recreate_sunmc_users.$$
    /usr/bin/rm -f $tmpfile

    /usr/bin/su - "$SMCORAU" -c ". $BASEDIR/sbin/es-common.sh; set_db_env;
$ORACLE_HOME/bin/sqlplus /nolog" <<EOF >$tmpfile 2>&1
set verify off;
set echo off;
set feedback off;
set serveroutput on;
set heading off;
start $3 $1 $2;
EOF
    if [ $? -ne 0 ] ; then
        /usr/bin/rm -f $tmpfile
        echolog 'Error while preparing for import'
        echologverbose 'Unable to recreate user $2 with script $3.' "$1" "$3"
        exit 1
    fi

    db_checkErr $tmpfile $LOGFILE
    if [ $? -ne 0 ] ; then
        /usr/bin/rm -f $tmpfile
        echolog 'Error while preparing for import'
        echologverbose 'Error while recreating user $2.' "$1"
        exit 1
    fi

    /usr/bin/rm -f $tmpfile
    return 0
}

import_sunmc35_data () {
    CFGDIR=$VAROPTDIR/cfg
    upgrade_dir=$VAROPTDIR/upgrade

    if [ ! -d "$upgrade_dir" ] ; then
        # Nothing to import
        return 0
    fi

    . $BASEDIR/db/cfg/dbadmin.cfg
    db_migr_read_meta $SUNMC_SCHEMA
    rcode=$?
    if [ $rcode -eq 0 ] ; then
        #
        # Import cfg files
        #
        OLDDATADIR=$upgrade_dir
        migrate_cfg_files

        #
        # Import 3.5 data
        #
        tmplog=$TEMPDIR/import35.log.$$
        $CMD_RM -f $tmplog

        # Make sure database is up
        /usr/bin/su - $SMCORAU -c $BASEDIR/sbin/db-start

        set_db_password
        [ $? -ne 0 ] && exit 1

        # Drop SUNMC user schemas
        recreate_user "$SUNMC_SCHEMA" "$SUNMC_SCHEMA_PWD" "$BASEDIR/db/build/create-schema-user"
        recreate_user "$SUNMC_USER" "$SUNMC_USER_PWD" "$BASEDIR/db/build/create-user"

        db_migr_import_user "$SUNMC_SCHEMA" "$SUNMC_SCHEMA_PWD" $tmplog
        if [ $? -ne 0 ] ; then
            echolog 'Error during database import'
            echologverbose 'Failed to import user $2.' "$SUNMC_SCHEMA"
            $CMD_RM -f $tmplog
            exit 1
        fi
        $CMD_CAT $tmplog >>$LOGFILE

        db_migr_import_user "$SUNMC_USER" "$SUNMC_USER_PWD" $tmplog
        if [ $? -ne 0 ] ; then
            echolog 'Error during database import'
            echologverbose 'Failed to import user $2.' "$SUNMC_USER"
            $CMD_RM -f $tmplog
            exit 1
        fi
        $CMD_CAT $tmplog >>$LOGFILE
        $CMD_RM -f $tmplog

        # Recreate constraints and indices 
        # As well re-compile all stored procedures so they are up to day with 
        # latest release.

        /usr/bin/su - $SMCORAU -c ". $BASEDIR/sbin/es-common.sh; set_db_env;
            cd \"$BASEDIR\";
            $ORACLE_HOME/bin/sqlplus /nolog <<EOF
connect $SUNMC_SCHEMA/$SUNMC_SCHEMA_PWD
@db/ddl/sunmc31_ddl.ind
@db/ddl/sunmc31_ddl.con
@db/upgrade/add_indices.sql
@db/upgrade/add_constraints.sql
@db/topology/procedures/topology
@db/eventmanager/procedures/eventmanager
@db/mgmtservice/procedures/mgmtservice
EOF
        " >> $LOGFILE 2>&1
        if [ $? -ne 0 ] ; then
            echolog "Error while recreating database constraints"
            exit 1
        fi

        # Imported successfully, clean up export files.
        db_migr_cleanup_user_assoc_files $SUNMC_SCHEMA
        db_migr_cleanup_user_assoc_files $SUNMC_USER

        $CMD_RM -rf $upgrade_dir/cfg $upgrade_dir/bin

    elif [ $rcode -eq 1 ] ; then
        # No data found for sunmc_owner
        return 0
    else
        # Error occurred
        echolog 'Error occurred while importing previous data'
        exit 1
    fi
}

remove_sql_log_files () {
   /usr/bin/rm -rf ${TMP_SMC_DB_LOGS}/db-start.sql
   /usr/bin/rm -rf ${TMP_SMC_DB_LOGS}/db-start.log
   /usr/bin/rm -rf ${TMP_SMC_DB_LOGS}/db-start-sql.log
   /usr/bin/rm -rf ${TMP_SMC_DB_LOGS}/db-start-sh.log
   /usr/bin/rm -rf ${TMP_SMC_DB_LOGS}/db-start-vinst.sql
   /usr/bin/rm -rf ${TMP_SMC_DB_LOGS}/db-start-vinst.log
   /usr/bin/rm -rf ${TMP_SMC_DB_LOGS}/db-stop.log
   /usr/bin/rm -rf ${TMP_SMC_DB_LOGS}/db-stop-sql.log
   /usr/bin/rm -rf ${TMP_SMC_DB_LOGS}/db-charset-utf8.log
   /usr/bin/rm -rf ${TMP_SMC_DB_LOGS}/db-charset-utf8.sql
   /usr/bin/rm -rf ${TMP_SMC_DB_LOGS}/db-charset-utf8-sql.log
}

check_dir () {
    if [ ! -d $1 ]
    then
       echolog 'the needed $2 directory does not exist' "$1"
       echolog "You must create it manually with at least 777 permissions"
       exit_SunMC "$DIR_NOT_FOUND_ERROR"
    fi
}

check_dir_perm_777 () {
     accessperms=`ls -ld "$1" | awk '{print $1}'`
     retcode=$?
     if [ $retcode -ne 0 ]
     then
	echolog 'es-setup - failed to obtain accessperms from ls command for : $2' "$1"
	exit_SunMC "$DIR_ACCESS_ERROR"
     fi

     #
     # verify at least 777 perms on each file
     # which is:  -rwxrwxrwx
     #
     for item in `echo "2 3 4 5 6 7 8 9 10"`
     do
	tmp=`echo $accessperms | cut -c$item`

	if [ $tmp = "-" ]
	then
	  echolog 'es-setup - changing access perms for $2 to 777' "$1"
	  chmod 777 "$1"

	  retcode=$?

	  if [ $retcode -ne 0 ]
	  then
	     echolog 'es-setup - failed to change permissions from chmod command for : $2' "$1"
	     echolog 'es-setup - access perms for $2 is not at least 777' "$1"
	     multiline_echolog 'You must modify it using chmod to be at least 777\nthen re-start es-setup'
	     exit_SunMC "$CHMOD_ERROR"
	  fi

	  break 1
	fi
     done
     if [ "$2" = "1" ] ; then
	 tmp=`echo $accessperms | cut -c10`
	 if [ $tmp != "t" ]
	 then
	    chmod u+t "$1"
	    if [ $retcode -ne 0 ]
	    then
	       echolog 'es-setup - failed to change permissions from chmod command for : $2' "$1"
	       exit_SunMC "$CHMOD_ERROR"
	    fi
	 fi
     fi
}

#
# This function does the check only for 755 permissions.
# It will not change the permissions on the directory.
# To call use: verify_curr_perm_755 /my_directory
#     0 - permissions are 755 or higher
#     1 - permissions are not 755 or more
#     2 - could not obtain ls output.

verify_dir_perm_only_755 () {

     accessperms=`$CMD_LS -ld "$1" | $CMD_AWK '{print $1}'`
     retcode=$?
     if [ $retcode -ne 0 ]
     then
        return 2
     fi

     #
     # verify at least 755 perms on the directory
     # which is:  -rwxr-xr-x
     #
     for item in `$CMD_ECHO "2 3 4 5 7 8 10"`
     do
        tmp=`$CMD_ECHO $accessperms | $CMD_CUT -c$item`
        if [ "$tmp" = "-" ]
        then
            return 1 
        fi
     done

     return 0

}


check_dir_perm_755 () {
     accessperms=`ls -ld "$1" | awk '{print $1}'`
     retcode=$?
     if [ $retcode -ne 0 ]
     then
	echolog 'es-setup - failed to obtain accessperms from ls command for : $2' "$1"
	exit_SunMC "$DIR_ACCESS_ERROR"
     fi

     #
     # verify at least 755 perms on each file
     # which is:  -rwxr-xr-x
     #
     for item in `echo "2 3 4 5 7 8 10"`
     do
	tmp=`echo $accessperms | cut -c$item`
	if [ $tmp = "-" ]
	then
	  echologverbose 'es-setup - changing access perms for $2 to 755' "$1"
	  chmod 755 "$1"

	  retcode=$?

	  if [ $retcode -ne 0 ]
	  then
	     echolog 'es-setup - failed to change permissions from chmod command for : $2' "$1"
	     echolog 'es-setup - access perms for $2 is not at least 755' "$1"
	     multiline_echolog 'You must modify it using chmod to be at least 755\nthen re-start es-setup'
	     exit_SunMC "$CHMOD_ERROR"
	  fi
	  break 1
	fi
     done
     if [ "$2" = "1" ] ; then
	 tmp=`echo $accessperms | cut -c10`
	 if [ $tmp != "t" ]
	 then
	    chmod u+t "$1"
	    if [ $retcode -ne 0 ]
	    then
	       echolog 'es-setup - failed to change permissions from chmod command for : $2' "$1"
	       exit_SunMC "$CHMOD_ERROR"
	    fi
	 fi
     fi
}

#
# 
#
set_oracle_admin_user_and_group () {
     # This workaround for solaris2.8 or solaris8 multiple path

     groupid=""
     verifyCreateOracleGroup $SMCORAG
     retcode=$?
     if [ $retcode -ne 0 ]; then
	echolog "execution of verifyCreateOracleGroup failed."
        exit_SunMC "$DATABASE_ERROR"
     fi
     
     verifyCreateOracleUser $SMCORAU $SMCORAG $groupid /var/opt/SUNWsymon
     retcode=$?
     if [ $retcode -ne 0 ]; then
	echolog "execution of verifyCreateOracleUser failed."
        exit_SunMC "$DATABASE_ERROR"
     fi
     if [ ! -d /var/opt/SUNWsymon/$SMCORAU ]; then
	echolog 'The admin user $SMCORAU working directory /var/opt/SUNWsymon/$SMCORAU does not exist'
	echolog "You must manually remove the existing admin user before proceeding."
        exit_SunMC "$DATABASE_ERROR"
     fi
     if [ "$setup_HA_flag" != "1" ]; then 
        echo "ORACLE_BASE=$ORACLE_HOME" >> /var/opt/SUNWsymon/$SMCORAU/.profile
        echo "export ORACLE_BASE" >> /var/opt/SUNWsymon/$SMCORAU/.profile
        echo "ORACLE_HOME=$ORACLE_HOME" >> /var/opt/SUNWsymon/$SMCORAU/.profile
        echo "export ORACLE_HOME" >> /var/opt/SUNWsymon/$SMCORAU/.profile
        echo "ORACLE_SID=SunMC" >> /var/opt/SUNWsymon/$SMCORAU/.profile
        echo "export ORACLE_SID" >> /var/opt/SUNWsymon/$SMCORAU/.profile
        echo "ORA_NLS33=$ORACLE_HOME/ocommon/nls/admin/data" >> /var/opt/SUNWsymon/$SMCORAU/.profile
        echo "export ORA_NLS33" >> /var/opt/SUNWsymon/$SMCORAU/.profile
        echo "PATH=$PATH:$ORACLE_HOME/bin" >> /var/opt/SUNWsymon/$SMCORAU/.profile
        echo "export PATH" >> /var/opt/SUNWsymon/$SMCORAU/.profile
     fi
}

get_lsnr_and_ora_proc_count () {

lcnt=0
scnt=0

set_basedir
set_db_env

    lcnt=`/usr/bin/ps -eaf | /usr/bin/grep -i SUNWsymon |/usr/bin/grep -i tnslsnr | /usr/bin/grep -v "grep" | /usr/bin/wc -l`
    scnt=`/usr/bin/ps -eaf | /usr/bin/grep -i "ora_.*$ORACLE_SID" | /usr/bin/grep -v "grep" | /usr/bin/wc -l`

}

check_and_stop_listner () {

    DB_CLEAN_EXPL="FALSE"
    DB_USER_EXIST="TRUE" 
    DB_GROUP_EXIST="TRUE"
    #
    # check if db (listener in particular) is currently executing and stop if so.
    #
    get_lsnr_and_ora_proc_count
    if [ $lcnt -gt 0 -o $scnt -gt 0 ]
    then
       #
       # stop database
       #
       check_db_passwd_group_file 
       retcode=$?
       case $retcode in
           0) 
               DB_USER_EXIST="TRUE"
               DB_GROUP_EXIST="TRUE"
               DB_CLEAN_EXPL="FALSE"
               ;;
           1) 
               DB_USER_EXIST="TRUE"
               DB_GROUP_EXIST="FALSE"
               DB_CLEAN_EXPL="TRUE"
               ;;
           2) 
               DB_USER_EXIST="FALSE"
               DB_GROUP_EXIST="TRUE"
               DB_CLEAN_EXPL="TRUE"
               ;;
           3) 
               DB_USER_EXIST="FALSE"
               DB_GROUP_EXIST="FALSE"
               DB_CLEAN_EXPL="TRUE"
               ;;
       esac

       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
           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..."
            kill_ora_processes
            # "$SMCORAU" and "$SMCORAG" may not be found in the password file 
	    # However the semaphores and shared memory may still be allocated under this user name.
	    # Will still try to remove the shared memory, if users are not available release_shm_sems
	    # will not do anything.
            release_shm_sems "$SMCORAU" "$SMCORAG"
        fi
    fi
}


# Relink database
# 
#
relink_sunmc_database () {
 
   umask 022

   remove_sql_log_files

   check_dir "/tmp"
   check_dir "/var"
   check_dir "/var/tmp"

   #  ensure that /tmp is at least 777 permissions
   #
   check_dir_perm_777 "/tmp"
   check_dir_perm_755 "/var"
   check_dir_perm_777 "/var/tmp" "1"

   set_oracle_admin_user_and_group 
   
   # Match user and group ID's on all the nodes on cluster
   #
   [ "$install_on_cluster" = "1" ] && match_uids_gids
   
   check_and_stop_listner 

   # check if the memory is enough for requirement
   #
   echologverbose ""
   echologverbose "Checking memory available..."
   smcdb_check_memory_available

   # the flag to indicate if /etc/system file has been changed
   #
   SYSTEM_CHANGED="0"

   # Check and change system info
   #
   smcdb_check_system

   if [ $? -ne 0 ]; then
       echolog "Checking /etc/system file error. It can not be updated."
       exit_SunMC "$KERNEL_PARA_UPDATE_ERROR"
   fi

   # Change kernel parameters
   #
   if [ "$SYSTEM_NEEDCHANGE" -eq 1 ]; then
      
      echolog ''
      echolog "The /etc/system file needs to be changed for Sun Management Center DB requirements."
      READ_RESPONSE_ONCE=0
      fetch_response_yes_no "TAG=UPDATE_ETC_SYSTEM" 'Do you wish to update /etc/system file '  
      [ $? -gt 0 ] && exit_SunMC_setup "$SUMMARY_READ_ERROR"
      saveAutoConfig "UPDATE_ETC_SYSTEM" "$answer"

      if [ "$answer" = "1" ]; then
      
         echologverbose "Backing up /etc/system to /etc/system.SunMCDB.backup"
         /usr/bin/cp /etc/system /etc/system.SunMCDB.backup
         /usr/bin/mv $SYSTEM_TEMP /etc/system
         /usr/bin/chgrp sys /etc/system
         SYSTEM_CHANGED="1"

         # keep system boot timestamp in /VAROPTDIR/lastboot file
         #
         temp_file="$VAROPTDIR/cfg/lastboot"
         /usr/bin/who -b > $temp_file

      else

         #echolog "Setup of Sun Management Center may fail if /etc/system is not changed."
	 echologverbose "/etc/system file has not been changed."
         /usr/bin/mv $SYSTEM_TEMP /etc/system_SunMC
         echolog 'The expected changes in /etc/system file are saved as /etc/system_SunMC.'
         echolog ''
      fi
   fi

   /usr/bin/rm -f ${TEMP_FILE}
   /usr/bin/rm -f ${SYSTEM_TEMP}

   # The system need to be reboot when the /etc/system changed
   #
   if [ $SYSTEM_CHANGED -eq 1 ]; then
      # prompt for reboot if the system file has been changed
      #
      echolog ""
      multiline_echolog 'In order for kernel variable changes to take effect, this\nmachine must be rebooted. You must reboot this machine now\nand then run the $2/sbin/es-setup again.' "$BASEDIR"
      echolog ""
      exit_SunMC "$REBOOT_REQUIRED"
   fi

   # Create symbolic link from actual extracted location
   # of the SUNWestbl package and /var/opt/SUNWsymon/db
   # if they are not one in the same.
   #
   
   # ensure proper umask, just in case
   # 
   umask 022
   
   pkgestbl_loc=`/usr/bin/pkginfo -r SUNWestbl`
   
   if [ "$setup_HA_flag" != "1" ] ; then
      if [ "$pkgestbl_loc" != "/var/opt/SUNWsymon" ]; then
   
         if [ -h /var/opt/SUNWsymon/db ]; then
             /usr/bin/rm  /var/opt/SUNWsymon/db
         fi

         if [ -d /var/opt/SUNWsymon/db ]; then
             /usr/bin/mv  /var/opt/SUNWsymon/db /var/opt/SUNWsymon/db.bak
             echolog "the /var/opt/SUNWsymon/db already existed, renaming to /var/opt/SUNWsymon/db.bak"
         fi

         /usr/bin/ln -s $pkgestbl_loc/db /var/opt/SUNWsymon/db >/dev/null 2>&1

         if [ $? -ne 0 ] ; then
             echolog 'Cannot create link $2 to directory $3' "/var/opt/SUNWsymon/db" "$pkgestbl_loc/SUNWsymon/db"
             echolog 'Sun Management Center DB setup cannot continue.'
             exit_SunMC "$DATABASE_ERROR"
         fi
      fi
   fi

   pkgesora_loc=`/usr/bin/pkginfo -r SUNWesora`

   if [ -d $pkgesora_loc/SUNWsymon/oracle ]; then
   
      /usr/bin/chown -Rh root $pkgesora_loc/SUNWsymon/oracle
      if [ $? -ne 0 ] ; then
         echolog 'Error changing ownership of $2 to root.  Installation cannot continue.' "$pkgesora_loc/SUNWsymon/oracle"
         exit_SunMC "$DATABASE_ERROR"
      fi
   fi

   # generate listener and tns files
   #
   echologverbose ""
   echologverbose "Configuring Sun Management Center DB listener and service files..."
   SMCDB_HOST=`/usr/bin/uname -a | /bin/awk '{print $2}'`

   # Fetch listener port for database
   #
   get_dblistener_port

   # configure the listener and tns files
   #
   smcdb_configuration
   if [ $? -ne 0 ]; then
       echolog "Error in resetting the configuration files for Sun Management Center DB."
       exit_SunMC "$DB_PORT_ERROR"
   fi

   # Perform an early check to ensure that the make executable is present
   # in the /usr/ccs/bin directory.  If not then inform user an exit.
   #
   if [ ! -f /usr/ccs/bin/make ] ; then
      multiline_echolog 'The Sun Management Center server setup requires that the make executable\nbe present on the host machine. In particular it looks for this file in the\n/usr/ccs/bin directory. Install the SUNWsprot package before executing\nthe es-setup script again.'
      echolog ""
      exit_SunMC "$MAKE_ERROR"
   fi

   if [ ! -f /usr/ccs/bin/ld ] ; then
      echolog ""
      multiline_echolog 'The Sun Management Center server setup requires that the ld executable\nbe present on the host machine.  In particular it looks for this file in the\n/usr/ccs/bin directory.  Install the SUNWtoo package before executing\nthe es-setup script again.'
      echolog ""
      exit_SunMC "$LINK_EDITOR_ERROR"
   fi

   if [ ! -f /usr/ccs/bin/ar ] ; then
      echolog ""
      multiline_echolog 'The Sun Management Center server setup requires that the ar executable\nbe present on the host machine. In particular it looks for this file in the\n/usr/ccs/bin directory. Install the SUNWbtool package before executing\nthe es-setup script again.'
      echolog ""
      exit_SunMC "$AR_ERROR"
   fi

   echolog ''
   echolog "Configuring the system for setup, please wait..."
   # Add some specific makes to ensure it gets done
   # First make sure that ownership on all database related files is correct.

   /usr/bin/chmod -R 0555 $ORACLE_HOME/bin/*

   if [ -f $ORACLE_HOME/bin/tnslsnr ]; then
      chmod u+s $ORACLE_HOME/bin/tnslsnr
      retcode=$?
      if [ $retcode -ne 0 ]; then
         echolog 'es-setup - chmod u+s $2 failed.' "$ORACLE_HOME/bin/tnslsnr"
         exit_SunMC "$CHMOD_ERROR"
      fi
   fi

   if [ -f $ORACLE_HOME/bin/oracle ]; then
      chmod u+s $ORACLE_HOME/bin/oracle
      retcode=$?
      if [ $retcode -ne 0 ]; then
         echolog 'es-setup - chmod u+s $2 failed.' "$ORACLE_HOME/bin/oracle"
         exit_SunMC "$CHMOD_ERROR"
      fi
      chmod g+s $ORACLE_HOME/bin/oracle
      retcode=$?
      if [ $retcode -ne 0 ]; then
         echolog 'es-setup - chmod g+s $2 failed.' "$ORACLE_HOME/bin/oracle"
         exit_SunMC "$CHMOD_ERROR"
      fi
   fi

   if [ -d $pkgesora_loc/SUNWsymon/oracle ]; then
   
      chown -hR $SMCORAU:$SMCORAG $pkgesora_loc/SUNWsymon/oracle
      retcode=$?
      if [ $retcode -ne 0 ]; then
         echolog 'es-setup - chown -hR $2:$3 $4 failed.' "$SMCORAU" "$SMCORAG" "$pkgesora_loc/SUNWsymon/oracle"
         exit_SunMC "$CHOWN_ERROR"
      fi

   fi
   if [ "$setup_HA_flag" != "1" ]; then
       if [ -d $pkgestbl_loc/SUNWsymon/db ]; then
           chown -hR $SMCORAU:$SMCORAG $pkgestbl_loc/SUNWsymon/db
           retcode=$?
           if [ $retcode -ne 0 ]; then
               echolog 'es-setup - chown -hR $2:$3 $4 failed.' "$SMCORAU" "$SMCORAG" "$pkgestbl_loc/SUNWsymon/db"
               exit_SunMC "$CHOWN_ERROR"
           fi
       fi
   fi

  /usr/bin/rm -rf ${TMP_SMC_DB_LOGS}/make.log
   
   # save current dir
   #
   curr_dir=`/usr/bin/pwd`

   /usr/bin/su - $SMCORAU <<-EOF

   #
   # From here onwards all the previously set variables will not be
   # available in new shell provided by su. New shell will have all
   # the environment variable from new user setings.
   # Here after, if we want to use the variables set before su, we can
   # directly use $VARNAME. If we want to use the variables in new
   # environment, we will have to escape $ from var name, like \$VARNAME.
   #
   . ${BASEDIR}/lib/sbin/script-errors.sh
   . ${BASEDIR}/sbin/es-common.sh
   set_basedir
   set_db_env

   # Since this code is being executed as user "smcorau", it will not have permissions
   # to write to the setup log which is owned by root. Therefore, we can not use echolog,
   # or echologverbose functions as they write to the setup log. Instead, we can echo
   # any relevant messages directly into make.log file which is oened by smcorau.

   # ensure we set the nmliblist file
   echo "\$ORACLE_HOME/rdbms/lib/skgxns.o" > \$ORACLE_HOME/rdbms/lib/nmliblist

   echo "===== ins_rdbms.mk install =========" >> \${TMP_SMC_DB_LOGS}/make.log
   echo " " >> \${TMP_SMC_DB_LOGS}/make.log

   cd \$ORACLE_HOME/rdbms/lib
   unset OPT

   /usr/ccs/bin/make -f ins_rdbms.mk install >> \${TMP_SMC_DB_LOGS}/make.log 2>&1

   retcode=\$?

   if [ \$retcode -ne 0 ]; then
     echo "execution of make -f ins_rdbms.mk install failed" >> \${TMP_SMC_DB_LOGS}/make.log
     exit_SunMC "\$MAKE_ERROR"
   fi

   echo " " >> \${TMP_SMC_DB_LOGS}/make.log
   echo "===== ins_rdbms.mk utilities ========" >> \${TMP_SMC_DB_LOGS}/make.log
   echo " " >> \${TMP_SMC_DB_LOGS}/make.log

   cd \$ORACLE_HOME/rdbms/lib
   unset OPT

   /usr/ccs/bin/make -f ins_rdbms.mk utilities >> \${TMP_SMC_DB_LOGS}/make.log 2>&1
   retcode=\$?
   if [ \$retcode -ne 0 ]; then
      echo "execution of make -f ins_rdbms.mk utilities failed" >> \${TMP_SMC_DB_LOGS}/make.log
      exit_SunMC "\$MAKE_ERROR"
   fi

   # Make partitioning option.
   # This make used to be done as part of PRM setup.

   echo " " >> \${TMP_SMC_DB_LOGS}/make.log
   echo "=====  ins_rdbms.mk part_on =============" >> \${TMP_SMC_DB_LOGS}/make.log
   echo " " >> \${TMP_SMC_DB_LOGS}/make.log

   if [ ! -f \$ORACLE_HOME/rdbms/lib/kkpoban.o ];then
      echo "execution of make -f ins_rdbms.mk part_on failed" >> \${TMP_SMC_DB_LOGS}/make.log
      echo "The database file kkpoban.o is missing" >> \${TMP_SMC_DB_LOGS}/make.log
      exit_SunMC "\$MAKE_ERROR"
   fi

   cd \$ORACLE_HOME/rdbms/lib
   unset OPT

   /usr/ccs/bin/make -f ins_rdbms.mk part_on >> \${TMP_SMC_DB_LOGS}/make.log 2>&1
   retcode=\$?
   if [ \$retcode -ne 0 ]; then
      echo "execution of make -f ins_rdbms.mk part_on failed" >> \${TMP_SMC_DB_LOGS}/make.log
      exit_SunMC "\$MAKE_ERROR"
   fi

   echo " " >> \${TMP_SMC_DB_LOGS}/make.log
   echo "=====  ins_rdbms.mk ioracle =============" >> \${TMP_SMC_DB_LOGS}/make.log
   echo " " >> \${TMP_SMC_DB_LOGS}/make.log

   cd \$ORACLE_HOME/rdbms/lib
   unset OPT

   /usr/ccs/bin/make -f ins_rdbms.mk ioracle >> \${TMP_SMC_DB_LOGS}/make.log 2>&1
   retcode=\$?
   if [ \$retcode -ne 0 ]; then
      echo "execution of make -f ins_rdbms.mk ioracle failed" >> \${TMP_SMC_DB_LOGS}/make.log
      exit_SunMC "\$MAKE_ERROR"
   fi

   echo " " >> \${TMP_SMC_DB_LOGS}/make.log
   echo "=====  ins_otrace.mk  =============" >> \${TMP_SMC_DB_LOGS}/make.log
   echo " " >> \${TMP_SMC_DB_LOGS}/make.log

   cd \$ORACLE_HOME/otrace/lib
   unset OPT

   /usr/ccs/bin/make -f ins_otrace.mk install >> \${TMP_SMC_DB_LOGS}/make.log 2>&1
   retcode=\$?
   if [ \$retcode -ne 0 ]; then
      echo "execution of make -f ins_otrace.mk install failed" >> \${TMP_SMC_DB_LOGS}/make.log
      exit_SunMC "\$MAKE_ERROR"
   fi

   echo " " >> \${TMP_SMC_DB_LOGS}/make.log
   echo "=====  ins_plsql.mk  ==============" >> \${TMP_SMC_DB_LOGS}/make.log
   echo " " >> \${TMP_SMC_DB_LOGS}/make.log

   cd \$ORACLE_HOME/plsql/lib
   unset OPT

   /usr/ccs/bin/make -f ins_plsql.mk install >> \${TMP_SMC_DB_LOGS}/make.log 2>&1
   retcode=\$?
   if [ \$retcode -ne 0 ]; then
      echo "execution of make -f ins_plsql.mk install failed" >> \${TMP_SMC_DB_LOGS}/make.log
      exit_SunMC "\$MAKE_ERROR"
   fi
   
   echo " " >> \${TMP_SMC_DB_LOGS}/make.log
   echo "=====  ins_net_server.mk  ============" >> \${TMP_SMC_DB_LOGS}/make.log
   echo " " >> \${TMP_SMC_DB_LOGS}/make.log

   cd \$ORACLE_HOME/network/lib
   unset OPT

   /usr/ccs/bin/make -f ins_net_server.mk install >> \${TMP_SMC_DB_LOGS}/make.log 2>&1
   retcode=\$?
   if [ \$retcode -ne 0 ]; then
      echo "execution of make -f ins_net_server.mk install failed" >> \${TMP_SMC_DB_LOGS}/make.log
      exit_SunMC "\$MAKE_ERROR"
   fi
   
   echo " " >> \${TMP_SMC_DB_LOGS}/make.log
   echo '=====  ins_net_client.mk  (sharedlib) =============' >> \${TMP_SMC_DB_LOGS}/make.log
   echo " " >> \${TMP_SMC_DB_LOGS}/make.log

   cd \$ORACLE_HOME/network/lib
   unset OPT

   /usr/ccs/bin/make -f ins_net_client.mk client_sharedlib >> \${TMP_SMC_DB_LOGS}/make.log 2>&1
   retcode=\$?
   if [ \$retcode -ne 0 ]; then
      echo "execution of make -f ins_net_client.mk client_sharedlib failed" >> \${TMP_SMC_DB_LOGS}/make.log
      exit_SunMC "\$MAKE_ERROR"
   fi
   
   echo " " >> \${TMP_SMC_DB_LOGS}/make.log
   echo "=====  ins_net_client.mk  ==================" >> \${TMP_SMC_DB_LOGS}/make.log
   echo " " >> \${TMP_SMC_DB_LOGS}/make.log

   cd \$ORACLE_HOME/network/lib
   unset OPT

   /usr/ccs/bin/make -f ins_net_client.mk install >> \${TMP_SMC_DB_LOGS}/make.log 2>&1
   retcode=\$?
   if [ \$retcode -ne 0 ]; then
      echo "execution of make -f ins_net_client.mk install failed" >> \${TMP_SMC_DB_LOGS}/make.log
      exit_SunMC "\$MAKE_ERROR"
   fi

   echo " " >> \${TMP_SMC_DB_LOGS}/make.log
   echo "======  ins_sqlplus.mk  =============" >> \${TMP_SMC_DB_LOGS}/make.log
   echo " " >> \${TMP_SMC_DB_LOGS}/make.log

   cd \$ORACLE_HOME/sqlplus/lib
   unset OPT

   /usr/ccs/bin/make -f ins_sqlplus.mk install >> \${TMP_SMC_DB_LOGS}/make.log 2>&1
   retcode=\$?
   if [ \$retcode -ne 0 ]; then
      echo "execution of make -f ins_sqlplus.mk install failed" >> \${TMP_SMC_DB_LOGS}/make.log
      exit_SunMC "\$MAKE_ERROR"
   fi

   # return to current dir
   #
   cd $curr_dir

   # set admin password after re-building orapwd util
   #
   echo "Create ora passord file" >> \${TMP_SMC_DB_LOGS}/make.log
   /usr/bin/rm -rf \$ORACLE_HOME/dbs/orapw\$ORACLE_SID
   
   \$ORACLE_HOME/bin/orapwd file=\$ORACLE_HOME/dbs/orapw\$ORACLE_SID password=oracle entries=1
   if [ \$? -ne 0 ]; then
      echo "failed to create internal user password file" >> \${TMP_SMC_DB_LOGS}/make.log
      exit_SunMC "\$ORAPWD_ERROR"
   fi

EOF

# if the internal shell (created by su command) had exited with a $MAKE_ERROR or 
# $ORAPWD_ERROR code, check this code and based on that either continue with the 
# rest of the setup or exit

retcode=$?
if [ $retcode -ne 0 ] ; then
   echolog "execution of database make failed"
   echolog 'see $2 file for details' "${TMP_SMC_DB_LOGS}/make.log"
   exit_SunMC_setup $retcode
fi

}


# This reads database listener port from user if default is busy.
# Input  : None
# Retuns : sets SMCDB_PORT
# 
get_dblistener_port () {

   # check and change listener port
   #
   SMCDB_PORT="2521"
   smcdb_check_port_number "$SMCDB_PORT"

   retcode=$?
   READ_RESPONSE_ONCE=0
   while [ $retcode -ne 0 ]; do

      echolog ''
      echolog 'The Port $2 for Sun Management Center DB has already been used.' "$SMCDB_PORT"
      
      SMCDB_PORT=`/usr/bin/expr $SMCDB_PORT + "1"`
      question="Enter another port for Sun Management Center DB listener [ $SMCDB_PORT-default ]" 
      fetch_response_text "TAG=OPTIONAL_DB_PORT" "$question"

      if [ $? -gt 0 ] ; then
            exit_SunMC "$DB_PORT_ERROR"          
      fi
      
      if [ -n "$answer" ]; then
         #checking for the validity of the port number
         #
         /usr/bin/expr $answer + 1  1> /dev/null  2>&1
         if [ $? -ne 0 ] ; then
            echolog 'Port $2 is not a valid port number.' "$answer"
            continue
         fi
         SMCDB_PORT=$answer
      fi

      smcdb_check_port_number "$SMCDB_PORT"
      retcode=$?
   done

   saveAutoConfig "OPTIONAL_DB_PORT" "$SMCDB_PORT"

   unset retcode           
}

# Input: 
#
#
get_seed_after_upgrade () {
   if [ "$UPGRADE_DONE" != "YES" ]; then
      $CMD_RM -f $VAROPTDIR/cfg/cfgserver-engines.dat
      get_security_key 0
   fi
}

create_dbase_cfg () {

    DBASE_CFG=$VARDIR/dbase.cfg

    if [ ! -f "$DBASE_CFG" ]; then
      echo "user=${SUNMC_USER}" > $DBASE_CFG
      echo "password=${SUNMC_USER_PWD}" >> $DBASE_CFG
      echo "database=${SUNMC_DATABASE}" >> $DBASE_CFG
      echo "host=${SMCDB_HOST}" >> $DBASE_CFG
      echo "port=${SMCDB_PORT}" >> $DBASE_CFG
      echo "driver=${JDBC_DRIVER}" >> $DBASE_CFG
      echo "url=${JDBC_URL}" >> $DBASE_CFG
      echo "minConnections=${MGMTSERVICE_MINCONN}" >> $DBASE_CFG
      echo "maxConnections=${MGMTSERVICE_MAXCONN}" >> $DBASE_CFG
      chmod go-wr $DBASE_CFG
    fi
}


check_db_space_availability () {
    # get tbl package location again, just in case pkgestbl_loc var has been modified
    pkgestbl_loc=`/usr/bin/pkginfo -r SUNWestbl`

    numLines=`/usr/bin/df -k $pkgestbl_loc | wc | awk '{print $1}'`
    numLines=`expr $numLines - 1`
    available_db_loc=`/usr/bin/df -k $pkgestbl_loc | tail -$numLines | awk '{print $4}'`
    db_partition=`/usr/bin/df -k $pkgestbl_loc | tail -$numLines | awk '{print $1}'`


    # make sure at least 150 MB (153600 KB) is available for DB setup
    # in addition to  the disk space needed for the 3 database redolog files which  have their size
    # configurable by the db-memconfig.cfg ==> [db_redolog_file_size].size entry 
    #  

    SMC_CONFIG_FILE="$ESROOT/db/cfg/db-memconfig.cfg"
    if [ ! -f "$SMC_CONFIG_FILE" ]; then 
      echologverbose "Error, configuration file db-memconfig.cfg missing"
      exit_SunMC "$DISK_SPACE_ERROR"
    fi

    SMC_REDOLOG_SIZE=0
    smc_get_config_section_key_value $SMC_CONFIG_FILE db_redolog_file size SMC_REDOLOG_SIZE 
    if [ $? -ne 0 ]; then
      echologverbose "Error retrieving standard redolog size for SunMC server"
      exixt_SunMC "$DISK_SPACE_ERROR" 
    fi

    # The redolog information kept in the dbase.cfg is per redolog.
    #
    max_available_db_loc=`/usr/bin/expr 153600 + $SMC_REDOLOG_SIZE \* 3 \* 1024`

    if  [ $available_db_loc -lt $max_available_db_loc ]; then
       echolog ""
       echolog 'Insufficient disk space \\\($2 kb avaliable\\\) for database setup to proceed \\\($3 kb needed\\\)' "$available_db_loc" "$max_available_db_loc"
       echolog 'Cleanup disk partition \\\($2\\\), then re-run $ESROOT/sbin/es-setup' "$db_partition"
       echolog ""
       exit_SunMC "$DISK_SPACE_ERROR"
    fi
}

check_db_passwd_group_file () {
    USER_EXIST="TRUE"
    GROUP_EXIST="TRUE"

    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"
        USER_EXIST="FALSE"
    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"
        GROUP_EXIST="FALSE"
    fi

    if [ "$USER_EXIST" = "TRUE" ]
    then
        if [ "$GROUP_EXIST" = "TRUE" ]
        then
            # user exists and group exists
            return 0
        else
            # user exists and group do not exist 
            return 1
        fi
    else
        if [ "$GROUP_EXIST" = "TRUE" ]
        then
            # user do not exist and group exist
            return 2
        else
            # user do not exist and group do not exist
            return 3
        fi
    fi

}

db_start_database () {
    
    
    
    if [ "VERBOSE" = "ON" ] ; then
	su - $SMCORAU -c $BASEDIR/sbin/db-start -v
	retcode=$?
    else
        su - $SMCORAU -c $BASEDIR/sbin/db-start
        retcode=$?
    fi
    if [ $retcode -ne 0 ]; then
	echolog "Database setup failed : db-start failed"
	exit_SunMC "$DB_START_ERROR"
    fi

}

db_stop_database () {
    if [ "$VERBOSE" = "ON" ] ; then
	su - $SMCORAU -c $BASEDIR/sbin/db-stop -v
	retcode=$?
    else
	su - $SMCORAU -c $BASEDIR/sbin/db-stop
	retcode=$?
    fi
    if [ $retcode -ne 0 ]; then
	echolog "Database setup failed : db-stop failed"
	exit_SunMC "$DB_STOP_ERROR"
    fi
}


update_db_password_info_working() {

   su - $SMCORAU -c "$BASEDIR/lib/sbin/sm_setup_db.sh -p" >/dev/null 2>&1 
   retcode=$?
   
   if [ $retcode -ne 0 ]; then
      echolog "FAILED to change passwords."
      exit_SunMC "$DATABASE_ERROR"
   fi
}

update_db_password_info() {
   old_sunmc_version="3.x"
   if [ -f /var/opt/SUNWsymon/2x/db-export.log ]; then
      /usr/bin/cat /var/opt/SUNWsymon/2x/db-export.log | /usr/bin/grep "Symon 2" 
      [ $? -eq 0 ] && old_sunmc_version="2.x"
   fi      

   su - $SMCORAU -c "$BASEDIR/lib/sbin/sm_setup_db.sh -p" >/dev/null 2>&1
   retcode=$?
   if [ $retcode -ne 0 ]; then
        echolog "FAILED to change passwords."
        exit_SunMC "$DATABASE_ERROR"
   fi
}

db_change_charset () {
    su - $SMCORAU -c $BASEDIR/lib/sbin/db-charset-utf8
    retcode=$?
    if [ $retcode -ne 0 ]; then
	echolog "Change charset to UTF8 failed : db-charset-utf8 failed"
	exit_SunMC "$DB_UTF8_ERROR"
    fi
}

check_sm_setup_db_error() {


    case $1 in
	0)
	    ;;
	1)
	    echolog 'Database setup report warning: check the logfile $DB_LOGFILE'
	    ;;
	2)
	    echolog 'Database setup failed : See the logfile $DB_LOGFILE'
	    exit $DATABASE_ERROR
	    ;;
    esac

}

db_import_previous_data () {
    if [ "$RUN_DB_IMPORT" = "YES" ]
    then
       if [ -f $ESROOT/lib/sbin/db-import.sh ]
       then
          cd $ESROOT/sbin
          if [ "$VERBOSE" = "ON" ] ; then
              $ESROOT/lib/sbin/db-import.sh -v
          else
              $ESROOT/lib/sbin/db-import.sh
          fi
       else
         echolog 'cannot find the import script file $2' "$ESROOT/lib/sbin/db-import.sh"
       fi
  
    fi
}

db_post_database_setup () {

    db_start_database

    # Add DE addon modules to database
    $BASEDIR/lib/sbin/es-add-addon-modules

    #
    #  Run the db import for db only
    #

    if [ "$RUN_DB_IMPORT" = "YES" ]
    then
       if [ -f $ESROOT/lib/sbin/db-import.sh ]
       then
          cd $ESROOT/sbin
          if [ "$VERBOSE" = "ON" ] ; then
              $ESROOT/lib/sbin/db-import.sh -v
          else
              $ESROOT/lib/sbin/db-import.sh
          fi

	  if [ "$?" -eq 0 ]; then 
	      /usr/bin/rm -rf /var/opt/SUNWsymon/2x
	  fi
       else
         echolog 'cannot find the import script file $2' "$ESROOT/lib/sbin/db-import.sh"
       fi
  
    fi

    if [ "$MIGRATE_DATA" -eq 1 ]; then
 
    # Apply all the between version deltas for the data-load
    # Has to be called after all the data is setup and imported.
    # no changes will be applied if the script internally detects that 
    # there are already entries in the database.

    /usr/bin/su - $SMCORAU -c ". $BASEDIR/sbin/es-common.sh; set_db_env;
            cd \"$BASEDIR\";
            $ORACLE_HOME/bin/sqlplus /nolog <<EOF
connect $SUNMC_SCHEMA/$SUNMC_SCHEMA_PWD
@db/topology/data/migrate-data-load.sql
EOF
        " >> $LOGFILE 2>&1
        if [ $? -ne 0 ] ; then
            echolog "Error running sql: $2" $BASEDIR/db/topology/data/migrate-data-load.sql
        fi
    fi

    #
    # execute script for suggested fix
    #
    if [ "$VERBOSE" = "ON" ] ; then
	( $BASEDIR/lib/sbin/es-sfix.sh )
    else
	( $BASEDIR/lib/sbin/es-sfix.sh > /dev/null 2>&1 )
    fi

   db_stop_database

   #echolog ''
   echolog 'Setup of Sun Management Center database is successful.'

   return 0
}

create_db_logfile() {

   LOGDIR=$VAROPTDIR/install

    if [ -z "$DB_LOGFILE" ] ; then
        [ ! -d "$LOGDIR" ] && /usr/bin/mkdir -p "$LOGDIR"
        DATE_FORMAT=`eval echo "+\\\%y\\\%m\\\%d\\\%H\\\%M\\\%S"`
        TIMESTAMP=`/usr/bin/date $DATE_FORMAT`
        HOST=`/usr/bin/hostname`
        DB_LOGFILE="$LOGDIR/core-db-setup_$HOST.$TIMESTAMP.$$"
    fi

    if [ ! -f "$DB_LOGFILE" ] ; then
        /usr/bin/touch "$DB_LOGFILE" >/dev/null 2>&1
        /usr/bin/chmod 640 "$DB_LOGFILE"
        if [ $? -ne 0 ] ; then
            echo ""
            eval echo `/usr/bin/gettext 'Unable to create logfile $DB_LOGFILE.'`
            echo ""
            [ -z "$LOGFILE_ERROR" ] && LOGFILE_ERROR=12
            exit_SunMC "$LOGFILE_ERROR"
        fi
    fi

        export DB_LOGFILE

    eval echo `/usr/bin/gettext "Started $0 at"` '`/usr/bin/date`'. >> "$DB_LOGFILE"
    eval echo `/usr/bin/gettext "Running on"` `/usr/bin/uname -a`. >> "$DB_LOGFILE"

}

setup_sunmc_database () {
   
    echolog 'Starting Sun Management Center database setup...'


    # Ensure ${TMP_SMC_DB_LOGS} is writable by smcorau to allow logging
    #
    /usr/bin/chown -R $SMCORAU:$SMCORAG ${TMP_SMC_DB_LOGS} >/dev/null
    /usr/bin/chmod 744 ${TMP_SMC_DB_LOGS} >/dev/null

    . $BASEDIR/db/cfg/dbadmin.cfg
    create_db_logfile
    create_dbase_cfg

    #
    # Check enough disk space is available IF THE DATABASE HAS NOT BEEN SETUP YET
    # Otherwise SKIP
    #
    database_setup_flag=0
    database_setup_flag=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "database_setup"  2> /dev/null `
    if [ -z "$database_setup_flag" -o "$database_setup_flag" = "0" ]; then 
       check_db_space_availability
    fi

    check_db_passwd_group_file
    retcode=$?
    case $retcode in
        0)
            # user and group exist
            ;;
        1)
            # group do not exist
            echolog 'the group $2 was not found by a getgrnam system call ,not in /etc/group, nis, nis+, etc..' "$SMCORAG"
            echolog 'user must manually deal with group issues before continuing'
            exit_SunMC "$DB_GROUP_ERROR"
            ;;
        2)
            # user do not exist
            echolog 'the user $2 was not found by a getpwnam system call ,not in /etc/passwd, nis, nis+, etc..' "$SMCORAU"
            echolog 'user must manually deal with user issues before continuing'
            exit_SunMC "$DB_USER_ERROR"
            ;;
        3)
            # user and group do not exist
            echolog 'the user $2 was not found by a getpwnam system call ,not in /etc/passwd, nis, nis+, etc..' "$SMCORAU"
            echolog 'user must manually deal with user issues before continuing'
            echolog 'the group $2 was not found by a getgrnam system call ,not in /etc/group, nis, nis+, etc..' "$SMCORAG"
            echolog 'user must manually deal with group issues before continuing'
            exit_SunMC "$DB_USER_GROUP_ERROR"
            ;;
    esac    

    #
    # Start the database server and build tables
    #
    check_dir_perm_755 "$VAROPTDIR/db"
    kill_ora_processes
    release_shm_sems "$SMCORAU" "$SMCORAG"
    db_start_database
    
    # Update db_password info
    #
    update_db_password_info

    #
    #  The script below will changes the charset from us7ascii  
    #  to utf8.  It expects to see the listener and database
    #  already executing, otherwise will report error and
    #  return a value of 1.
    #
    #  This logic is re-runnable without harm.
    #
    #
    db_change_charset

    # 
    #
    smcdb_configure_initora
    [ $? -ne 0 ] && exit_SunMC "$DATABASE_ERROR"
    db_start_database
 
    #
    # Build the SunMC oracle database
    #
    cd $BASEDIR/db/build

    PATH=$PATH:$ORACLE_HOME/bin
    export PATH
    
    if [ "$setup_HA_flag" != "1" ]; then
        #
        # If 'dbreconfigure' exists, current schema shall be dropped
        #
        if [ -f $VARDIR/dbreconfigure ] ; then
            echolog "Dropping the Sun Management Center database schema"
            /usr/bin/su - $SMCORAU -c "$BASEDIR/lib/sbin/sm_setup_db.sh -d" >> $DB_LOGFILE 2>&1
            /usr/bin/rm -f $VARDIR/dbreconfigure
            remove_dat_files
        fi

        #
        #  First test whether or not the sunmc schema already
        #  exists, if so, then we can ask the user whether or not
        #  to clean the previous installation.
        #
        su - $SMCORAU -c "$BASEDIR/lib/sbin/sm_setup_db.sh -c" >> $DB_LOGFILE 2>&1
        status=$?

        # This global is an interface for add-on setup.
        # During setup time, Add-on with database should check this flag to find if 
        # old data was preserved for base product or not. If this flag is set then it should 
        # preserve add-on data.
        #
        CORE_DATA_PRESERVED=1

        if [ $status -eq 0 ] ; then
            schema_exists_flag=1
            export schema_exists_flag

            if [ "$UPGRADE_DONE" = "YES" ]; then
                preserve_data_flag=1
            else
                READ_RESPONSE_ONCE=0
                while :
                do
                   fetch_response_yes_no "TAG=PRESERVE_DATA" "Do you want to preserve your existing data:"  
                   [ $? -gt 0 ] && exit_SunMC_setup  "$SUMMARY_READ_ERROR"
                   preserve_data_flag=$answer
                   if [ "$AUTOCONFIG_RUNFILE" ]; then
                       break
                   else
                       if [ $preserve_data_flag -eq 1 ]; then
                           break
                       else
                           echolog ''
                           multiline_echolog 'This will remove all the existing data. If you wish to keep a copy of your\ndata, manually run es-backup script before proceeding.'
                           fetch_response_yes_no "Do you wish to continue with the removal of the existing data"
                           [ $answer -eq 0 ] && continue
                           CORE_DATA_PRESERVED=0
                           break
                       fi
                   fi
               done
               echolog ''
           fi
       else
           preserve_data_flag=0
           schema_exists_flag=0
       fi
 
       export CORE_DATA_PRESERVED
       saveAutoConfig "PRESERVE_DATA" "$preserve_data_flag"
    
       #echolog ''
       echolog "Please wait, Sun Management Center database setup in progress. It may take 10 minutes..."
    

       if [ "$schema_exists_flag" = "1" ]; then
           if [ $preserve_data_flag -eq 0 ] ; then
               remove_db_data
               remove_dat_files
           fi
 
           # Only Verify database
           su - $SMCORAU -c "$BASEDIR/lib/sbin/sm_setup_db.sh -v" >> $DB_LOGFILE 2>&1
           check_sm_setup_db_error $?

       else 
           # Since database doesn't exist, just create it
           su - $SMCORAU -c "$BASEDIR/lib/sbin/sm_setup_db.sh -b" >> $DB_LOGFILE 2>&1
           check_sm_setup_db_error $?
       fi

       #
       # Generate report about current database  
       #
       su - $SMCORAU -c "$BASEDIR/lib/sbin/sm_setup_db.sh -r" >> $DB_LOGFILE 2>&1
       check_sm_setup_db_error $?

       #  Run the db import for db only
       #
       db_import_previous_data 
   else
       # Update logical hostname in dbase.cfg 
       #
       if [ -f $VARDIR/dbase.cfg ] ; then
           echologverbose 'Updating dbase.cfg for logical hostname...'
           /usr/bin/chmod u+w ${VAROPTDIR}/cfg/dbase.cfg
           mv -f ${VAROPTDIR}/cfg/dbase.cfg ${VAROPTDIR}/cfg/dbase.cfg.non_HA
           /usr/bin/cat ${VAROPTDIR}/cfg/dbase.cfg.non_HA | grep -v "host=" >> ${VAROPTDIR}/cfg/dbase.cfg
           /usr/bin/echo  "host=$HA_SERVER\n" >> ${VAROPTDIR}/cfg/dbase.cfg
       else
           echolog 'dbase.cfg does not exist. You must perform setup on primary node first.'
           exit_SunMC "$DATABASE_ERROR"
       fi
   fi

   #
   # Generate report about current database  
   #
   su - $SMCORAU -c "$BASEDIR/lib/sbin/sm_setup_db.sh -r" >> $DB_LOGFILE 2>&1
   check_sm_setup_db_error $?

   #  Run the db import for db only
   #
   db_import_previous_data 
   db_stop_database 
   
   #echolog ''

   return 0
}

# Match user and group ID's on all the nodes on cluster
#
match_uids_gids() {
 
 match_failed=0
 chown_failed=0
 if [ "$setup_HA_flag" != "1" ]; then
    # Put the gid/uid in a file - overwrite old one
    #
    SMCORAU_ID=`/usr/bin/cat /etc/passwd | /usr/bin/grep "smcorau:" 2> /dev/null `
    [ -z "$SMCORAU_ID" ] && echolog 'Failed to collect user and group IDs for usr smcorau.' exit_SunMC "$DATABASE_ERROR"
    [ -f "$VARDIR/HAServer.properties" ] && /usr/bin/mv "$VARDIR/HAServer.properties" "$VARDIR/HAServer.properties.old"
    /usr/bin/echo $SMCORAU_ID  > "$VARDIR/HAServer.properties"
 else
    if [  ! -f "$VARDIR/HAServer.properties" ] ; then
       echolog ''
       echolog 'Could not find HA configuration file:$2' "$VARDIR/HAServer.properties"
       echolog 'Ensure that setup is complete on primary node.'
       exit_SunMC "$DATABASE_ERROR"
    else
       echologverbose  'Matching UID and GID of user smcorau with Primary server...'
       ORACLE_ID=`/usr/bin/cat "$VARDIR/HAServer.properties" | /usr/bin/grep "smcorau:" 2> /dev/null `
       [ -z "$ORACLE_ID" ] && echolog 'Bad HA configuration file:$2' "$VARDIR/HAServer.properties" && exit_SunMC "$DATABASE_ERROR"
       NEW_ORA_GID=`/usr/bin/echo $ORACLE_ID | /usr/bin/cut -d: -f4 2> /dev/null  `
       NEW_ORA_UID=`/usr/bin/echo $ORACLE_ID | /usr/bin/cut -d: -f3 2> /dev/null  `
       
       ORACLE_ID=`/usr/bin/cat /etc/passwd | /usr/bin/grep "smcorau:" 2> /dev/null `
       [ -z "$ORACLE_ID" ] && echolog 'Can not find oracle user - smcorau' && exit_SunMC "$DATABASE_ERROR"
       OLD_ORA_GID=`/usr/bin/echo $ORACLE_ID | /usr/bin/cut -d: -f4 2> /dev/null  `
       OLD_ORA_UID=`/usr/bin/echo $ORACLE_ID | /usr/bin/cut -d: -f3 2> /dev/null  `
     
       [ "$OLD_ORA_GID" = "$NEW_ORA_GID" ] && echologverbose 'GID of smcorau is already matched.'
       [ "$OLD_ORA_UID" = "$NEW_ORA_UID" ] && echologverbose 'UID of smcorau is already matched.'
      
       ret_code=0
       [ "$OLD_ORA_GID" != "$NEW_ORA_GID" ] && /usr/sbin/groupmod -g $NEW_ORA_GID smcorag 2> /dev/null && ret_code=$?
       if [ $ret_code -eq 0 ] ; then
          ret_code=0
          [ "$OLD_ORA_UID" != "$NEW_ORA_UID" ] && /usr/sbin/usermod -u $NEW_ORA_UID -g $NEW_ORA_GID smcorau 2> /dev/null && ret_code=$?
          [ $ret_code -gt 0 ] && match_failed=1
       else
          match_failed=1
       fi

       if [ "$match_failed" = "1" ] ; then
          echolog ''
          echolog 'Failed to match oracle UID and GID with primary node.'
          echolog 'UID and GID for user smcorau must be same on all cluster nodes.'
          echolog 'You must change them manually and re-run es-setup.'
          exit_SunMC "$REBOOT_REQUIRED"
       else
          pkgesora_loc=`/usr/bin/pkginfo -r SUNWesora  2> /dev/null `
          if [ -d "$pkgesora_loc/SUNWsymon/oracle" ] ; then
             /usr/bin/chown -hR $SMCORAU $pkgesora_loc/SUNWsymon/oracle 2> /dev/null
             [ $? -gt 0 ] && chown_failed=1
             /usr/bin/chgrp -hR $SMCORAG $pkgesora_loc/SUNWsymon/oracle 2> /dev/null
             [ $? -gt 0 ] && chown_failed=1
          fi
         
          if [ -d "$pkgestbl_loc/SUNWsymon/db" ]; then
             /usr/bin/chown -hR $SMCORAU $pkgestbl_loc/SUNWsymon/db 2> /dev/null
             [ $? -gt 0 ] && chown_failed=1
             /usr/bin/chgrp -hR $SMCORAG $pkgestbl_loc/SUNWsymon/db 2> /dev/null
             [ $? -gt 0 ] && chown_failed=1
          fi

          if [ -d "/var/opt/SUNWsymon/SUNWsymon/db" ]; then
             /usr/bin/chown -hR $SMCORAU "/var/opt/SUNWsymon/SUNWsymon/db" 2> /dev/null
             [ $? -gt 0 ] && chown_failed=1
             /usr/bin/chgrp -hR $SMCORAG "/var/opt/SUNWsymon/SUNWsymon/db" 2> /dev/null
             [ $? -gt 0 ] && chown_failed=1
          fi
          
          if [ -d "/var/opt/SUNWsymon/smcorau" ]; then
             /usr/bin/chown -Rh $SMCORAU "/var/opt/SUNWsymon/smcorau" 2> /dev/null
             [ $? -gt 0 ] && chown_failed=1
             /usr/bin/chgrp -Rh $SMCORAG "/var/opt/SUNWsymon/smcorau" 2> /dev/null
             [ $? -gt 0 ] && chown_failed=1
          fi

          if [ "$chown_failed" = "1" ] ; then
             echolog ''
             echolog 'chown failed after changing the UID ansd GID of user - smcorau.'
             echolog 'UID and GID for user smcorau must be same on all cluster nodes.'
             echolog 'You must change them manually and re-run es-setup.'
             exit_SunMC "$REBOOT_REQUIRED"
          else
             echologverbose  'Matching UID and GID of user - smcorau with primary server successful.'
          fi
          
       fi
    fi
 fi

 unset match_failed chown_failed

}

kill_ora_processes() {
# Kill SunMC DB processes explicitly
# Either 3.0 or 3.5

    pids=`/usr/bin/ps -eaf |/usr/bin/grep -i SUNWsymon | /usr/bin/grep -i tnslsnr | /usr/bin/grep -v "grep" | /usr/bin/awk '{print $2}'`

    for each_pid in $pids
    do
            /usr/bin/kill -9 "$each_pid" >/dev/null 2>&1
    done

    pids=`/usr/bin/ps -eaf | /usr/bin/grep -i "ora_.*$ORACLE_SID" | /usr/bin/grep -v "grep" | /usr/bin/awk '{print $2}'`

    for each_pid in $pids
    do
            /usr/bin/kill -9 "$each_pid" >/dev/null 2>&1
    done

    return 0
}


release_shm_sems() {
# Release shared memory and semaphores taken by Sun Management Center DB processes explicitly
#
#  $1 = unique string used to identify the user that owns the resource
#  $2 = unique string used to identify the group that owns the resource
#
    # remove shared memory taken by Sun Management Center for Oracle database
    # if entries only contain the user name and the group has been
    # accidently removed, then check for such entries

    shmids=`/usr/bin/ipcs -m | grep "$1" | awk '{print $2}'`

    for each_shmid in $shmids
    do
        /usr/bin/ipcrm -m $each_shmid >/dev/null 2>&1
    done

    # if entries only contain the group name and the user has been
    # accidently removed, then check for such entries

    shmids=`/usr/bin/ipcs -m | grep "$2" | awk '{print $2}'`

    for each_shmid in $shmids
    do
        /usr/bin/ipcrm -m $each_shmid >/dev/null 2>&1
    done

    # remove semaphores taken by Sun Management Center for Oracle database
    # if entries only contain the user name and the group has been
    # accidently removed, then check for such entries

    semids=`/usr/bin/ipcs -s | grep "$1" | awk '{print $2}'`

    for each_semid in $semids
    do
        /usr/bin/ipcrm -s $each_semid >/dev/null 2>&1
    done

    # if entries only contain the group name and the user has been
    # accidently removed, then check for such entries

    semids=`/usr/bin/ipcs -s | grep "$2" | awk '{print $2}'`

    for each_semid in $semids
    do
        /usr/bin/ipcrm -s $each_semid >/dev/null 2>&1
    done

    # if both user smcorau and group smcorag is removed manually,
    # the shared memory and semaphores will not be released as in that case
    # we cann't make out if Sun Management Center created them or some other process did.
    # keys of shared memory and semaphores is not stored in some file
    # so ipcrm cann't be used to kill based on key. If keys can be located
    # removing ipc structures based on keys can be a safe method.

    return 0
}




#
# Check if any Oracle processes are running
#

check_Oracle_running() {

    # This is to fix the minor message problem introduced in es-stop script -
    # ver 1.52 by Cirba
    # It must be ensured that all oracle related tasks called only in case if
    # server is present.
    #
    [ "$no_server" = "1" ] && return 0

    get_lsnr_and_ora_proc_count
    if [ $lcnt -eq 0 -a $scnt -eq 0 ]; then
        return 0
    else
        return 1
    fi
}



# db_setupEnvironment
#  DESCRIPTION:  initializes database specific environment 
#
#  Returns: 0 - success
#           1 - failure
#
db_setupEnvironment () {

    # Various Oracle utilities
    SQLPLUS=${ORACLE_HOME}/bin/sqlplus
    if [ ! -f "$SQLPLUS" ] ; then
        echolog 'FATAL: core database utilities missing.'
        exit 1
    fi

    #
    # Check current Sun Management Center version. Some variables may be different depending
    # on this.
    #
    /usr/bin/pkginfo -q SUNWescom 1>/dev/null 2>&1
    if [ $? -ne 0 ] ; then
        echolog 'Sun Management Center missing or not properly installed. Aborting.'
        exit 1
    fi

    SUNMC_VERSION=`/usr/bin/pkgparam SUNWescom SUNW_PRODVERS | /usr/bin/awk -F_ '{ print substr($1,0,3) }'`
    majver=`/bin/echo "$SUNMC_VERSION" | /usr/bin/cut -f1 -d.`

    ESTBL_BASEDIR=`/usr/bin/pkginfo -r SUNWestbl`
    if [ $? -ne 0 ] ; then
       echolog 'Unable to determine current database data directory'
       return 1
    fi
    if [ ! -d "$ESTBL_BASEDIR" ] ; then
       echolog 'SUNWestbl base directory is invalid: $2' "$ESTBL_BASEDIR"
       return 1
    fi
    ORA_DATADIR=$ESTBL_BASEDIR/db/oradata/SunMC
    ORA_INITFILE=$ORACLE_HOME/admin/$ORACLE_SID/pfile/initSunMC.ora
    NLS_LANG=AMERICAN_AMERICA.UTF8; export NLS_LANG
    VAR_ORA_DATADIR=$ESDIR/db/oradata/SunMC
    SMC_CONFIG_FILE=$ESROOT/db/cfg/db-memconfig.cfg
    if [ ! -f "$SMC_CONFIG_FILE" ] ; then
	echolog '$2 does not exist. Aborting.' "$SMC_CONFIG_FILE"
        return 1
    fi

    TEMPDIR=/tmp
    if [ ! -d "$TEMPDIR" ] ; then
        echolog '$2 does not exist. Aborting.' "$TEMPDIR"
        return 1
    fi

    return 0
}

#db_dropTblsp $tblsp_name $sys_usr $sys_pwd $log_file
# DESCRIPTION: drops any ORACLE tablespace and removes any associate files
#
# Returns:  0 - success
#           1 - error - running SQL
#           2 - error - removing tablespace file
#           3 - error - tablespace file not found
#
db_dropTblsp () {

    tblsp_name=$1; sys_usr=$2; sys_pwd=$3; log_file=$4; 

    tmp_file="/tmp/tmp_file.$$"
    /usr/bin/rm -f $tmp_file

    old_text_domain="ES_SCRIPTS"
    [ ! -z "$TEXTDOMAIN" ] && old_text_domain="$TEXTDOMAIN"

    setup_textdomain ES_SCRIPTS
    echolog "";
    echolog 'Dropping old database device $2' "$tblsp_name"
    echolog "";
    
    sqlcom="";
    sqlcom="SELECT file_name FROM dba_data_files WHERE tablespace_name = UPPER('$tblsp_name')";
    db_runSql "$sqlcom" $sys_usr $sys_pwd $tmp_file;
    db_checkErr $tmp_file $log_file;
    if [ $? -ne 0 ];then
        echolog "";
        echolog 'Error encountered selecting old database device $2 location' "$tblsp_name"
        setup_textdomain "$old_text_domain"
        /usr/bin/rm -f $tmp_file
        return 1;
    fi
    ts_files=`/usr/bin/cat $tmp_file|/usr/bin/xargs echo`

    sqlcom="DROP TABLESPACE $tblsp_name INCLUDING CONTENTS";
    db_runSql "$sqlcom" $sys_usr $sys_pwd $tmp_file;
    db_checkErr $tmp_file $log_file;
    if [ $? -ne 0 ];then

        echolog "";
        echolog 'Error encountered dropping old database device $2' "$tblsp_name"
        setup_textdomain "$old_text_domain"
        /usr/bin/rm -f $tmp_file
        return 1;
    fi
    for tblsp_file_name in $ts_files ; do
        [ "$tblsp_file_name" = "" ] && continue;
        if [ -f "$tblsp_file_name" ];then
            /usr/bin/rm -f "$tblsp_file_name" > /dev/null;
            if [ $? -ne 0 ];then

                echolog "";
                echolog 'Error dropping database device file: $2' "$tblsp_file_name"
                setup_textdomain "$old_text_domain"
                /usr/bin/rm -f $tmp_file
                return 2;
            fi
        else
            echolog "";
            echolog 'Database device file: $2 not found to drop.Exiting...' "$tblsp_file_name"
            setup_textdomain "$old_text_domain"
            /usr/bin/rm -f $tmp_file
            return 3;
        fi
    done

    /usr/bin/rm -f $tmp_file
    setup_textdomain "$old_text_domain"
    return 0
}

# db_runSqlSpool $sql $spool $type $login $passwd $log_file
# DESCRIPTION: spools any sql/PlSql output to a given file
#    NOTE: type = SQL or type = PL/SQL
#
# Returns:  0 - success
#           1 - error running sql/PlSql command
#           2 - error spooling to $spool file
#
db_runSqlSpool () {
    sql="$1"; spool="$2"; type=$3; login=$4; passwd=$5; log_file=$6
    [ $type != "SQL" -a $type != "PL/SQL" ] && return 3

    tmp_file="/tmp/tmp_file.$$"
    /usr/bin/rm -f $tmp_file

    if [ $type = "SQL" ];then
        db_runSql "$sql" $login $passwd $tmp_file
        db_checkErr $tmp_file $log_file
        if [ $? -ne 0 ];then
            echologverbose 'Error encountered running SQL $2' "$sql"
            /usr/bin/rm -f $tmp_file
            return 1
        fi
    else
        db_runPlSql "$sql" $login $passwd $tmp_file
        db_checkErr $tmp_file $log_file
        if [ $? -ne 0 ];then
            echologverbose 'Error encountered running PL/SQL $2' "$sql"
            /usr/bin/rm -f $tmp_file
            return 1
        fi
    fi
  
    /usr/bin/cp $tmp_file $spool
    if [ $? -ne 0 ];then
        echologverbose 'Error encountered spooling file: $2' "$spool"
        /usr/bin/rm -f $tmp_file
        return 2
    fi

    /usr/bin/rm -f $tmp_file
    return 0
}

#db_runPlSql $sql $login $passwd $outfile 
#  DESCRIPTION: Runs any Pl/Sql statement passed in 
#
#  Returns: 0 - success
#           1 - error sqlplus
#
db_runPlSql ()
 {
    sql="$1"; username=$2; passwd=$3; outfile=$4;
    $ORACLE_HOME/bin/sqlplus -s ${username}/${passwd}<<-EOF>$outfile 2>/dev/null
        set verify off;
        set echo off;
        set serveroutput on;
        set heading off;
        set feedback off;
        set pagesize 1024;
        $sql;
	/
EOF
    [ $? -ne 0 ] && return 1
    return 0;
}

#db_revSqlTblsp $tblsp_name $spool $login $passwd $log_file
# DESCRIPTION: Reverse engineers CREATE statement for a tablespace
#
#  Returns: 0 - success
#           1 - failure
#
db_revSqlTblsp () {
    tblsp_name=$1; spool="$2"; login=$3; passwd=$4; log_file=$5

    sqlcom="
DECLARE
  CURSOR get_ts
  IS
  SELECT *
  FROM   dba_tablespaces
  WHERE  tablespace_name != 'SYSTEM'
  AND    tablespace_name LIKE UPPER('$tblsp_name');
  CURSOR get_df (p_ts VARCHAR2)
  IS
  SELECT *
  FROM   dba_data_files
  WHERE  tablespace_name = p_ts;
  l_str  VARCHAR2(10);
  l_dbb  INTEGER;
  l_maxe VARCHAR2(10);
BEGIN
SELECT value INTO l_dbb
FROM v\$parameter
WHERE name = 'db_block_size';
FOR ts_rec IN get_ts LOOP
  dbms_output.put_line ('CREATE TABLESPACE '||ts_rec.tablespace_name);
  FOR df_rec IN get_df (ts_rec.tablespace_name) LOOP
    IF get_df%ROWCOUNT = 1 THEN
       l_str := 'DATAFILE';
    ELSE
       l_str := ',';
    END IF;
    dbms_output.put_line (l_str||' '||chr(39)||df_rec.file_name||chr(39));
    dbms_output.put_line ('SIZE '||df_rec.bytes);
    IF df_rec.autoextensible = 'YES' THEN
     dbms_output.put_line (' AUTOEXTEND ON NEXT '||df_rec.increment_by*l_dbb/1024||'k'
                 ||' MAXSIZE '||df_rec.maxblocks*l_dbb/1024||'k');
    END IF;
  END LOOP;
  IF ts_rec.max_extents IS NULL THEN
    l_maxe := 'UNLIMITED';
  ELSE
    l_maxe := TO_CHAR(ts_rec.max_extents);
  END IF;
   dbms_output.put_line ('DEFAULT STORAGE (INITIAL '||ts_rec.initial_extent
        ||' NEXT '||ts_rec.next_extent
        ||' MINEXTENTS '||ts_rec.min_extents
        ||' MAXEXTENTS '||l_maxe
        ||' PCTINCREASE '||ts_rec.pct_increase||' ) ONLINE;');
   dbms_output.new_line;
END LOOP;
END"
    db_runSqlSpool "$sqlcom" "$spool" "PL/SQL" $login $passwd $log_file
    [ $? -ne 0 ] && return 1 
    return 0
}

#db_shrinkTblsp $tbsname $new_size $login $passwd $log_file
#  DESCRIPTION: shrinks all the tablespace datafiles to the same size
#     NOTE: It is specifically meant for TEMP and RBS tablespaces
#           For RBS the rollback segments have to be dropped first
#           More than likely it will fail for regular tablespaces
#
#   Returns: 0 - success
#            1 - failure
#
db_shrinkTblsp () {
    tbsname=$1; new_size=$2; login=$3; passwd=$4; log_file=$5
    tmp_file=/tmp/tmp_file.$$
    /usr/bin/rm -f $tmp_file

    sql="SELECT pct_increase 
FROM   dba_tablespaces
WHERE  tablespace_name = UPPER('$tbsname')" 

    db_runSql "$sql" $login $passwd $tmp_file $log_file
    db_checkErr $tmp_file $log_file
    if [ $? -ne 0 ];then
        echologverbose 'Error processing sql: $2' "$sql"
        /usr/bin/rm -f $tmp_file
        return 1
    else
        pct_increase=`cat $tmp_file`
    fi

    sql="
ALTER TABLESPACE $tbsname default storage(pctincrease 1);
ALTER TABLESPACE $tbsname default storage(pctincrease $pct_increase)"

    db_runSql "$sql" $login $passwd $tmp_file $log_file
    db_checkErr $tmp_file $log_file
    if [ $? -ne 0 ];then
        echologverbose 'Error processing sql: $2' "$sql"
        /usr/bin/rm -f $tmp_file
        return 1
    fi
    sql="SELECT file_name FROM dba_data_files 
WHERE tablespace_name = UPPER('$tbsname')" 
    db_runSql "$sql" $login $passwd $tmp_file $log_file
    db_checkErr $tmp_file $log_file
    if [ $? -ne 0 ];then
        echologverbose 'Error processing sql: $2' "$sql"
        /usr/bin/rm -f $tmp_file
        return 1
    fi

    ts_datafiles=`/usr/bin/cat $tmp_file|/usr/bin/xargs echo`
    for datafile in "$ts_datafiles";do 
        # (Ignore blank lines)
        if [ "$datafile" != "" ] ; then
            sql="ALTER DATABASE DATAFILE '$datafile' RESIZE $new_size"
            db_runSql "$sql" $login $passwd $tmp_file $log_file
            db_checkErr $tmp_file $log_file
            if [ $? -ne 0 ];then
                echologverbose 'Error processing sql: $2' "$sql"
                /usr/bin/rm -f $tmp_file
                return 1
            fi
        fi
    done

    /usr/bin/rm -f $tmp_file
    return 0
}

# db_revRbsSeg $tsname $login $passwd $log_file
#  DESCRIPTION: It reverse engineers a 'CREATE ROLLBACK SEGMENT' script
#               based on the current ORACLE settings 
#
#   Returns: 0 - success
#            1 - failure
#    
db_revRbsSeg () {
    tsname=$1; spool=$2; login=$3; passwd=$4; log_file=$5
    tmp_file=/tmp/tmp_file.$$
    /usr/bin/rm -f $tmp_file

    sql="
SELECT  'CREATE PUBLIC ROLLBACK SEGMENT '||rn.name||' TABLESPACE '||rs.tablespace_name||chr(10)||
 'STORAGE '||chr(10)||
 '(INITIAL '||rs.initial_extent||chr(10)||
 'NEXT '||rs.next_extent||chr(10)||
 'MINEXTENTS '||rs.min_extents||chr(10)||
 'MAXEXTENTS '||rs.max_extents||chr(10)||
 'OPTIMAL '
  ||DECODE(r.optsize,null,rs.initial_extent+rs.next_extent,r.optsize)||')'||chr(10)||
 '/'||chr(10)
FROM dba_rollback_segs rs, v\$rollstat r, v\$rollname rn
WHERE rs.tablespace_name LIKE UPPER('RBS')
AND rn.name = rs.segment_name
AND rn.usn = r.usn
AND rn.name != 'SYSTEM'"
    db_runSqlSpool "$sql" $spool "SQL" $login $passwd $log_file
    [ $? -ne 0 ] && return 1 
    return 0
}

# db_setRbsOpt $tsname $opt $login $passwd $log_file
#  DESCRIPTION: Sets rollback segments off/on
#
#   Returns: 0 - success
#            1 - failure
#
db_setRbsOpt () {
    tsname=$1; opt=$2; login=$3; passwd=$4; log_file=$5 
    [ $opt != "offline" -a $opt != "online" ] && return 2

    tmp_file=/tmp/tmp_file.rbs.$$
    /usr/bin/rm -f $tmp_file

    sql="
DECLARE
  CURSOR get_rbs
  IS
  SELECT segment_name
  FROM   dba_rollback_segs
  WHERE  segment_name != 'SYSTEM'
   AND   status != UPPER('$opt')
   AND   tablespace_name = UPPER('$tsname');
  l_command VARCHAR2(64);
BEGIN
 FOR rbs_rec IN get_rbs LOOP
  l_command := 'alter rollback segment '||rbs_rec.segment_name||' $opt';
  execute immediate l_command;
 END LOOP;
END"
    db_runPlSql "$sql" $login $passwd $tmp_file 
    db_checkErr $tmp_file $log_file
    if [ $? -ne 0 ];then
        echologverbose 'Error running sql: $2' "$sql"
        /usr/bin/rm -f $tmp_file
        return 1
    fi
    /usr/bin/rm -f $tmp_file
    return 0
}

#db_dropRbs $tsname $login $passwd $log_file
#
db_dropRbs () {
    tsname=$1; login=$2; passwd=$3; log_file=$4 
    tmp_file=/tmp/tmp_file.rbs.$$
    /usr/bin/rm -f $tmp_file

    sql="
DECLARE
  CURSOR get_rbs
  IS
  SELECT segment_name
  FROM   dba_rollback_segs
  WHERE  segment_name != 'SYSTEM'
   AND   tablespace_name = UPPER('$tsname');
  l_command VARCHAR2(64);
BEGIN
  FOR rbs_rec IN get_rbs LOOP
    BEGIN
      l_command := 'alter rollback segment '||rbs_rec.segment_name||' offline';
      execute immediate l_command;
    EXCEPTION
      WHEN OTHERS THEN NULL;
    END;
    BEGIN
      l_command := 'drop rollback segment '||rbs_rec.segment_name;
      execute immediate l_command;
    EXCEPTION
      WHEN OTHERS THEN NULL;
    END;
  END LOOP;
END"
    db_runPlSql "$sql" $login $passwd $tmp_file 
    db_checkErr $tmp_file $log_file
    if [ $? -ne 0 ];then
        echologverbose 'Error running sql: $2' "$sql"
        /usr/bin/rm -f $tmp_file
        return 1
    fi

    /usr/bin/rm -f $tmp_file
    return 0
}


#db_tblspFile $tsname $login $passwd $logfile
# DESCRIPTION: populate a global variable called GLOBAL_DIR_NAME with all the files making up the tablespace  
#
#  Returns: 0 - success
#           1 - failure
#
db_tblspFile () {
    tsname=$1; login=$2; passwd=$3; logfile=$3
    tmp_file=/tmp/tmp_file.$$
    /usr/bin/rm -f $tmp_file

    sql="SELECT file_name FROM dba_data_files WHERE tablespace_name = UPPER('$tsname')"
    db_runSql "$sql" $login $passwd $tmp_file
    db_checkErr $tmp_file $log_file
    if [ $? -ne 0 ];then
        echologverbose 'Error processing sql: $2' "$sql"
        /usr/bin/rm -f $tmp_file
        return 1
    fi

    GLOBAL_DIR_NAME=`/usr/bin/cat $tmp_file | /usr/bin/xargs echo`
    /usr/bin/rm -f $tmp_file
    return 0
}

set_db_password() {

    CRYPTPASS=09124q67i9

    SYS_LOGIN=sys
    SYSPWD=unknown

    SYSTEM_LOGIN=system
    SYSTEMPWD=unknown

    #
    # if BASEDIR not set determine using
    # location of SUNWescom package
    #
    if [ -z "$BASEDIR" ] ; then
        BASEDIR=`/usr/bin/pkginfo -r SUNWescom`/SUNWsymon
    fi

    PASSWORDFILE=$BASEDIR/db/build/adminpasswd
    if [ -r "$PASSWORDFILE" ] ; then

        tvar1=`/usr/bin/crypt $CRYPTPASS < $PASSWORDFILE | /usr/bin/grep '^SYSPWD='`
        tvar2=`/usr/bin/crypt $CRYPTPASS < $PASSWORDFILE | /usr/bin/grep '^SYSTEMPWD='`
        SYSPWD=`echo $tvar1 | /usr/bin/sed 's/[ 	]*//g' | /usr/bin/sed 's/^SYSPWD=//g'`
        SYSTEMPWD=`echo $tvar2 | /usr/bin/sed 's/[ 	]*//g' | /usr/bin/sed 's/^SYSTEMPWD=//g'`
        if [ -z "$SYSPWD" ] ; then
            echolog "Unable to determine SYSPWD"
            return 1
        fi
        if [ -z "$SYSTEMPWD" ] ; then
            echolog "Unable to determine SYSTEMPWD"
            return 2
        fi
    else
        echolog "Unable to determine SYSPWD or SYSTEMPWD"
        return 3
    fi

    return 0
}

#db_runProc $procname $username $passwd $tmpfile 
#  DESCRIPTION:  runs any procedure passed in 
#   
#    Returns: 0 - success
#             1 - failure sqlplus
#  
db_runProc () {
    procname=$1; username=$2; passwd=$3; tmpfile=$4;
    $ORACLE_HOME/bin/sqlplus -s ${username}/${passwd}<<-EOF>$tmpfile 2>/dev/null
	set verify off;
	set echo off;
        set serveroutput on;
	exec $procname;
EOF
    [ $? -ne 0 ] && return 1
    return 0;
}

#db_runSql  $sql $username $passwd $outfile
# DESCRIPTION: runs any SQL (not PL/SQL) statement passed in
#
# Returns: 0 - success
#          1 - error sqlplus
#
db_runSql () {
    sql="$1"; username=$2; passwd=$3; outfile=$4
    $ORACLE_HOME/bin/sqlplus -s ${username}/${passwd}<<-EOF>$outfile 2>/dev/null
	set verify off;
	set echo off;
        set serveroutput on;
	set heading off;
	set feedback off;
	set pagesize 1024;
	set linesize 2047;
	$sql;
EOF
    retstat=$?
    [ $retstat -ne 0 ] && return 1 
    return 0
}

#db_runDbScript $sqlscript $username $passwd $outfile
# DESCRIPTION: runs any SQL script passed in
#
#   Returns: 0 - success
#            1 - failure sqlplus
#
db_runDbScript () {
    sqlscript="$1"; username=$2; passwd=$3; outfile=$4
    $ORACLE_HOME/bin/sqlplus -s ${username}/${passwd}<<-EOF>$outfile 2>/dev/null
	set verify off;
	set echo off;
	set feedback off;
        set serveroutput on;
	set heading off;
	start ${sqlscript};
EOF
    [ $? -ne 0 ] && return 1
    return 0;
}

#db_checkErr $outfile $logfile
# DESCRIPTION: checks an outfile for any flagrant ORACLE errors
#
#  Returns:  0 - success
#            1 - failure
# 
db_checkErr () {
    outfile=$1; logfile=$2

    retstat=0
    /usr/bin/touch $TEMPDIR/oraErr.$$
    while read errLine; do
        lerora=`/usr/bin/echo $errLine|/usr/bin/egrep "ORA-|PLS-|SP2-"|/usr/bin/egrep -v "ORA-01434|ORA-00942|ORA-04043|ORA-01418|ORA-02443|ORA-0001|ORA-01918"|/usr/bin/awk '{ print $1; }'`
        if [ $lerora ]; then 
            retstat=1
            /usr/bin/echo $retstat > $TEMPDIR/oraErr.$$
            echologverbose "Database Error Encountered..."
            /usr/bin/cat $outfile >> $LOGFILE
            continue 2000
        fi
    done<$outfile
  
    if [ -s "$TEMPDIR/oraErr.$$" ];then
        retstat="`/usr/bin/expr $retstat + 1`"
    fi
    /usr/bin/rm -f $TEMPDIR/oraErr.$$ >/dev/null
    return $retstat
}

#db_runRecompInv $username $passwd $tmpfile $logfile
# DESCRIPTION: recompiles all invalid PL/SQL objects 
#
#      Returns: 0 - success
#               1 - failure to successfully recompile
#
db_runRecompInv () {
    username=$1; passwd=$2; tmpfile=$3; logfile=$4
    retstat=0

    $ORACLE_HOME/bin/sqlplus -s ${username}/${passwd}<<-EOF>$tmpfile 2>/dev/null
        set verify off;
        set echo off;
        set serveroutput on;
        set heading off;
        set feedback off;
	@${ORACLE_HOME}/rdbms/admin/utlrp.sql
EOF
    db_checkErr $tmpfile $logfile
    return $?
}


#db_start
# DESCRIPTION: starts ORACLE
#
# RETURNS: 0 - success
#   NOTE: or exists upon failure
#
db_start () {
    echologverbose 'Starting database...'
    /usr/bin/su - $SMCORAU -c "$BASEDIR/sbin/db-start -v" >>$LOGFILE 2>&1
    if [ $? -ne 0 ] ; then
        echolog 'Failed to start database.'
        exit 1
    fi
    return 0
}

#db_stop
# DESCRIPTION: stops ORACLE
#
#  Returns: 0 - success
#    NOTE: or exists upon failure
#
db_stop () {
    echologverbose 'Stopping database...'
    /usr/bin/su - $SMCORAU -c "$BASEDIR/sbin/db-stop -v" >>$LOGFILE 2>&1
    if [ $? -ne 0 ] ; then
        echolog 'Failed to stop database.'
        exit 1
    fi
    return 0
}


# db_checkUser $user $passwd $user $logfile
#  DESCRIPTION: checks the existence of the user $user
#
#  Returns: 0 - success (user found)
#           1 - user not found
#           2 - error 
#
db_checkUser () {
    login=$1
    passwd=$2
    user=$3 
    logfile=$4

    tmpfile=/tmp/prm-common-ckuser.$$
    /usr/bin/rm -f $tmpfile

    sql="SELECT 1 FROM dba_users WHERE username = UPPER('$user')"
    db_runSql "$sql" $login $passwd $tmpfile
    db_checkErr $tmpfile $logfile
    if [ $? -ne 0 ] ; then
        echolog 'Error while checking for reference user'
        /usr/bin/rm -f $tmpfile
        return 2
    fi

    /usr/bin/egrep -i " 1" $tmpfile >/dev/null
    if [ $? -eq 0 ] ; then
        echologverbose 'Found previous reference schema'
        /usr/bin/rm -f $tmpfile
        return 0
    fi

    /usr/bin/rm -f $tmpfile
    return 1
}

#db_checkTablespace $tsname $user $passwd $logfile
#  DESCRIPTION: Checks for the existence tablespace $tsname
# 
#   Returns: 0 - true  (tablespace exists)
#            1 - false (not...)
#            2 - error
db_checkTablespace () {
    tsname=$1
    user=$2
    passwd=$3
    logfile=$4

    tmpfile=/tmp/prm-chkts.$$
    /usr/bin/rm -f $tmpfile

    sql="SELECT 1 FROM dba_tablespaces WHERE tablespace_name=UPPER('$tsname')"
    db_runSql "$sql" $user $passwd $tmpfile
    db_checkErr $tmpfile $logfile
    if [ $? -ne 0 ] ; then
        echolog 'Error while checking for tablespaces'
        /usr/bin/rm -f $tmpfile
        return 2
    fi

    # Check if SELECT returned 1 or not
    /usr/bin/egrep -i " 1" $tmpfile >/dev/null
    if [ $? -eq 0 ] ; then
        /usr/bin/rm -f $tmpfile
        return 0
    fi

    /usr/bin/rm -f $tmpfile
    return 1
}

# db_dropUser $user $login $passwd $logfile
#  DESCRIPTION:  drops any database user
#
#   Returns: 0 - success
#            1 - failure
#
db_dropUser () {
    user=$1
    login=$2
    passwd=$3
    logfile=$4
 
    tmpfile=/tmp/prm-dropuser.$$
    /usr/bin/rm -f $tmpfile
 
    sql="DROP USER $user CASCADE"
    db_runSql "$sql" $login $passwd $tmpfile
    db_checkErr $tmpfile $logfile
    if [ $? -ne 0 ] ; then
        /usr/bin/rm -f $tmpfile
        return 1
    fi
    /usr/bin/rm -f $tmpfile
    return 0
}

#db_changeRestrictedSession $change $logfile
# DESCRIPTION: Sets database restricted session to ENABLE/DISABLE
#    NOTE: $change can be either ENABLE or DISABLE
#
#   Returns: 0 - success
#            1 - failure to setup the option
#            2 - change error (not ENABLE or DISABLE)
#
db_changeRestrictedSession () {
    change=$1; logfile=$2
    [ $change -ne "enable" -a $change -ne "disable" ] && return 2

    tmp_file="/tmp/tmp_file.$$"
    /usr/bin/rm -f $tmp_file

    sqlcom="alter system $change  restricted session"
    db_runSql "$sqlcom" $SYS_LOGIN $SYSPWD $tmp_file
    db_checkErr $tmp_file $logfile
    if [ $? -ne 0 ];then 
        echolog 'Error setting database to restricted mode: $2. Exiting...'  "$change" 
        /usr/bin/rm -f $tmp_file
        return 1
    fi
    /usr/bin/rm -f $tmp_file
    return 0
}

# db_getRedoNo 
#  DESCRIPTION: gets the current active logfile 
#  
#     Returns:  0 - success
#               1 - failure
#
#        DB_REDO_NO env. variable will contain the actual
#           current active logfile
#
db_getRedoNo () {

    oratmp=/tmp/db_unsetup.$$
    /usr/bin/rm -f $oratmp
   
    sqlcom="select GROUP# from v\$log where status = 'CURRENT'"
    db_runSql "$sqlcom" $SYS_LOGIN $SYSPWD $oratmp
    db_checkErr $oratmp $LOGFILE

    if [ $? -ne 0 ] ; then
        echolog 'Unable to get the active redolog file...'
        /usr/bin/rm -f $oratmp
        return 1
    fi

    DB_REDO_NO=`/usr/bin/cat $oratmp|/usr/bin/xargs echo`
    /usr/bin/rm -f $oratmp
    return 0
}

# db_dropRedoLog $no 
#   DESCRIPTION: Drops redolog# $no and file associated with it
#       NOTE:  good for redo logfiles 1-9
#
#    Returns: 0 - success
#             1 - failure
#
db_dropRedoLog () {
    no=$1;
    
    oratmp=/tmp/db-unsetup.$$
    /usr/bin/rm -f $oratmp

    sqlcom="alter database drop logfile group $no"
    db_runSql "$sqlcom" $SYS_LOGIN $SYSPWD $oratmp 
    db_checkErr $oratmp $LOGFILE

    if [ $? -ne 0 ] ; then
        echologverbose 'Unable to drop logfile: $2' "$no"
        /usr/bin/rm -f $oratmp
        return 1
    fi

    logfile="$ORA_DATADIR/redo0${no}.log"
    /usr/bin/rm -f "$logfile" 1>/dev/null 2>&1
    if [ $? -ne 0 ];then
        echologverbose 'Error removing redo logfile $2' "$logfile"
        /usr/bin/rm -f $oratmp
        return 1
    fi

    /usr/bin/rm -f $oratmp
    return 0
} 


# db_checkExistRedoLog $no $size
#   DESCRIPTION: checks the existence of the redolog $no
#       NOTE:  good for redo logfiles 1-9
#              size can be either "500k" or "xxxM"
#
#    Returns: 0 - redo found (needs resizing)
#             1 - redo found (doesn't need resizing)
#             2 - redo not found 
#             3 - error 
#
#
db_checkExistRedoLog () {
    no=$1; size3=$2
    
    oratmp=/tmp/db-unsetup.$$
    /usr/bin/rm -f $oratmp

    if [ "$size3" = "500k" ];then
        size33="512000"
    else
        size33=`/usr/bin/echo "$size3" | /usr/bin/sed -n 's/M//p'`
        if [ $? -ne 0 ];then
            echolog 'Illegal size $2' "$size3"
            return 3
        fi
        size33=`/usr/bin/expr $size33 \* 1024 \* 1024`
        if [ $? -ne 0 ];then
            echolog 'Illegal size $2' "$size33"
            return 3
        fi
    fi

    sqlcom="select ltrim(rtrim(decode(bytes,${size33},1,0)))  from v\$log where group# = ${no}"
    db_runSql "$sqlcom" $SYS_LOGIN $SYSPWD $oratmp
    db_checkErr $oratmp $LOGFILE

    if [ $? -ne 0 ];then 
        echolog 'Error checking the existence of redo no: $2' "$no"
        /usr/bin/rm -f $oratmp
        return 3
    fi
    if [ -f "$oratmp" ];then
        if [ -s "$oratmp" ];then
            f_size=`/usr/bin/cat "$oratmp"`
            if [ $f_size -ne 0 -a $f_size -ne 1 ];then
                echolog 'Error checking redo logfile size' 
                /usr/bin/rm -f $oratmp
                return 1
            fi
            /usr/bin/rm -f $oratmp
            return $f_size
        else
            /usr/bin/rm -f $oratmp
            return 2
        fi
    else
        echolog 'Error retrieving information for redo no: $2' "$no"
        /usr/bin/rm -f $oratmp
        return 3
    fi
    return 0
}

# db_createRedoLog $no $size
#   DESCRIPTION: creates redolog# $no with $size
#       NOTE:  size includes unit (ex: 512k|1024M)
#       NOTE:  good for redo logfiles 1-9
#
#    Returns:
#
#
db_createRedoLog () {
    no=$1; size=$2;
    
    oratmp=/tmp/db-unsetup.$$
    /usr/bin/rm -f $oratmp

    logfile=$ORA_DATADIR/redo0${no}.log
    sqlcom="alter database add logfile group $no '${logfile}' size $size"
    db_runSql "$sqlcom" $SYS_LOGIN $SYSPWD $oratmp
    db_checkErr $oratmp $LOGFILE

    if [ $? -ne 0 ];then 
        echolog 'Unable to add logfile no: $2' "$no"
        /usr/bin/rm -f $oratmp
        return 1
    fi
    /usr/bin/rm -f $oratmp
    return 0
}

# db_switchRedoLog 
#    DESCRIPTION: performs a switch logfile command
#
#    Returns: 0 - success
#             1 - failure
#
db_switchRedoLog () {
    
    oratmp=/tmp/db-unset.$$
    /usr/bin/rm -f $oratmp

    sqlcom="alter system switch logfile"
    db_runSql "$sqlcom" $SYS_LOGIN $SYSPWD $oratmp
    db_checkErr $oratmp $LOGFILE

    if [ $? -ne 0 ];then
        echolog 'Unable to switch logfile'
        /usr/bin/rm -f $oratmp
        return 1
    fi

    /usr/bin/rm -f $oratmp
    return 0
} 

# db_checkpoint 
#    DESCRIPTION: performs a checkpoint command
#
#    Returns: 0 - success
#             1 - failure
#
db_checkpoint () {
    
    oratmp=/tmp/db-unset.$$
    /usr/bin/rm -f $oratmp

    sqlcom="alter system checkpoint"
    db_runSql "$sqlcom" $SYS_LOGIN $SYSPWD $oratmp
    db_checkErr $oratmp $LOGFILE

    if [ $? -ne 0 ];then
        echolog 'Unable to checkpoint the database'
        /usr/bin/rm -f $oratmp
        return 1
    fi

    /usr/bin/rm -f $oratmp
    return 0
} 

# db_replaceRedoLogs  $size
#   DESCRIPTION:  replaces existing redo logfiles with new ones
#                 with $size
#     NOTE: size = 500k means we restore to original Sun Management Center size
#     NOTE: currently only 3 redo log files
#           we don't handle multiple files in redo groups
# 
#      Returns:  0 - success
#                1 - failure
#
db_replaceRedoLogs () {
    size=$1

    redo_no="1 2 3"

    for reno in ${redo_no};do

        #Check the existence of the redo logfile
        db_checkExistRedoLog $reno $size
        redo_check=$?
        if [ $redo_check -eq 0 ];then 
            db_getRedoNo
            [ $? -ne 0 ] && return 1
            if [ $reno -eq $DB_REDO_NO ];then
                db_checkpoint
                [ $? -ne 0 ] && return 1
                db_switchRedoLog
                [ $? -ne 0 ] && return 1 	
                sleep 4
            fi
            #redo  found drop it and clean-up the space 
            db_dropRedoLog $reno
            if [ $? -ne 0 ]; then
                db_checkpoint
                [ $? -ne 0 ] && return 1 	
                db_switchRedoLog
                [ $? -ne 0 ] && return 1 	
                sleep 4
                db_dropRedoLog $reno
                [ $? -ne 0 ] && return 1 	
            fi
        elif [ $redo_check -eq 1 ];then

            #redo has required size do nothing 
            echologverbose 'Logfile $2 has already size $3' "$redofile" "$size"
            continue
        elif [ $redo_check -eq 2 ];then 

            #redo doesn't exist, how about the file?
            redofile="$ORA_DATADIR/redo0${reno}.log"
            if [ -f "$redofile" ];then
                /usr/bin/rm -f "$redofile" 1>/dev/null 2>&1
                if [ $? -ne 0 ];then
                    echologverbose 'Error removing logfile: $2' "$redofile"
                    return 1
                fi
            fi
        else
            echologverbose 'Unknown error returned by db_checkExistRedoLog: $2' "$redo_check"
            return 1
        fi 

        #check the existence of the size space
        if [ "$size" != "500k" ];then
            size_k=`/usr/bin/echo "$size" | /usr/bin/sed -n 's/M//p'`
            if [ $? -ne 0 ];then
                echologverbose 'Illegal redo size'
                return 1
            fi
            gen_checkDirSpace $ORA_DATADIR $size_k 
            retstat=$?
            if [ $retstat -eq 1 ];then
                echologverbose 'Not enough space available to replace redo logfile: $2' "$reno"
                return 0
            elif [ $retstat -eq 2 ];then
                return 1
            fi 
        fi

        #recreate redo logfile 
        db_createRedoLog $reno $size
        [ $? -ne 0 ] && return 1
        echologverbose 'Successfully resized redo logfile number: $2' "$reno"
    done

    return 0
}


# db_mountDb
#    DESCRIPTION: performs a mount database
#
#    Returns: 0 - success
#             1 - failure
#
db_mountDb () {
    
    oratmp=/tmp/db-unset.$$
    /usr/bin/rm -f $oratmp

    /usr/bin/su - $SMCORAU  -c ". $BASEDIR/sbin/es-common.sh; set_db_env;
			$ORACLE_HOME/bin/sqlplus -s /nolog<<EOF>$oratmp 2>/dev/null
connect / as sysdba;
set verify off;
set echo off;
set feedback off;
startup mount;
EOF"
    db_checkErr $oratmp $LOGFILE

    if [ $? -ne 0 ];then
        echolog 'Unable to mount the database'
        /usr/bin/rm -f $oratmp
        return 1
    fi

    /usr/bin/rm -f $oratmp
    return 0
}

# db_openDb
#    DESCRIPTION: performs an open database
#
#    Returns: 0 - success
#             1 - failure
#
db_openDb () {
    
    oratmp=/tmp/db-unset.$$
    /usr/bin/rm -f $oratmp

    /usr/bin/su - $SMCORAU -c ". $BASEDIR/sbin/es-common.sh; set_db_env;
			$ORACLE_HOME/bin/sqlplus -s /nolog<<EOF>$oratmp 2>/dev/null
connect / as sysdba;
set verify off;
set echo off;
set feedback off;
alter database open;
EOF"
    db_checkErr $oratmp $LOGFILE

    if [ $? -ne 0 ];then
        echolog 'Unable to open the database'
        /usr/bin/rm -f $oratmp
        return 1
    fi

    /usr/bin/rm -f $oratmp
    return 0
}

# db_renameFile $fileFrom $fileTo
#    DESCRIPTION: renames file $fileFrom to $fileTo 
#
#    Returns: 0 - success
#             1 - failure
#
db_renameFile () {
    fileFrom=$1; shift
    fileTo=$1;
    
    oratmp=/tmp/db-unset.$$
    /usr/bin/rm -f $oratmp

    /usr/bin/su - $SMCORAU -c ". $BASEDIR/sbin/es-common.sh; set_db_env;
			$ORACLE_HOME/bin/sqlplus -s /nolog<<EOF>$oratmp 2>/dev/null
connect / as sysdba;
set verify off;
set echo off;
set feedback off;
alter database rename file '$fileFrom' to '$fileTo';
EOF"
    db_checkErr $oratmp $LOGFILE

    if [ $? -ne 0 ];then
        echolog 'Unable to rename file: $2 to $3' "$fileFrom" "$fileTo"
        /usr/bin/rm -f $oratmp
        return 1
    fi

    /usr/bin/rm -f $oratmp
    return 0
}


# db_moveDbFile "$fileOld" "$fileNew"
#    DESCRIPTION: renames a file  
#
#    Returns: 0 - success
#             1 - failure
#
db_renameDbFile () {
    fileOld=$1; shift
    fileNew=$1;
    
    db_mountDb
    [ $? -ne 0 ] && return 1
 
    db_renameFile "$fileOld" "$fileNew"
    [ $? -ne 0 ] && return 1
    
    db_openDb
    [ $? -ne 0 ] && return 1

    return 0
}

#
# Database API's added to support Core/AddOn migration
#

#db_setStatusTblsp $tblspace_name $status $log_file
# DESCRIPTION: Sets tablespace status to R  - read only
#                                        RW - read write
# NOTE: the only acceptable statuses are R or RW
# RETURNS: 0 - success
#          1 - failure
#          2 - wrong status
#
db_setStatusTblsp () {
    tblspace_name=$1
    status=$2
    log_file=$3
  
    tmp_file=$TEMPDIR/setStatusTblsp.$$
    /usr/bin/rm -f $tmp_file
  
    if [ "$status" = "R" ] ; then
        tblspace_status="READ ONLY"
    elif [ "$status" = "RW" ] ; then
        tblspace_status="READ WRITE"
    else
        /usr/bin/rm -f $tmp_file
        return 2
    fi

    sqlcom="ALTER TABLESPACE $tblspace_name $tblspace_status"
    db_runSql "$sqlcom" $SYS_LOGIN $SYSPWD $tmp_file
    db_checkErr $tmp_file $log_file

    if [ $? -ne 0 ];then
        echolog 'Unable to alter status for tablespace: $2' "$tblspace_name"
        /usr/bin/rm -f $tmp_file
        return 1
    else
        /usr/bin/rm -f $tmp_file
        return 0
    fi
}

#db_expDataTt $tblsp_names $exp_meta_file $log_file
# DESCRIPTION: create the export meta file associated
#              with transportable tablepspace $tblsp_names
#              and store it in $exp_meta_file
# NOTE: $tblsp_names represents a list of one or more
#       tablespaces to be transported (ex: "tblsp1 tblsp2...")
#
# RETURNS: 0 - success
#          1 - failure
#
db_expDataTt () {
    tblsp_names=$1
    exp_meta_file=$2
    log_file=$3

    tmp_file=$TEMPDIR/expDataTt.$$
    /usr/bin/rm -f $tmp_file
    par_file=$TEMPDIR/db_expDataTt.par.$$
    /usr/bin/rm -f $par_file

    if [ -f "$log_file" ] ; then
        /usr/bin/rm -f $log_file
    fi

    #Change status to R for tablespaces
    for tblspace in $tblsp_names ; do
        db_setStatusTblsp $tblspace "R" $log_file
        if [ $? -ne 0 ] ; then
            /usr/bin/rm -f $tmp_file
            return 1
        fi
    done

    #create the export parfile
    #userid has to include "as sysdba" condition which
    #cannot be passed in on the command line

    /usr/bin/touch $par_file
    /bin/echo "userid=\"$SYS_LOGIN/$SYSPWD as sysdba\"" >> $par_file
    /bin/echo "transport_tablespace=y"                  >> $par_file
    /bin/echo "tablespaces=($tblsp_names)"              >> $par_file

    #Export the transportable tablespaces metadata file
    /usr/bin/su - $SMCORAU -c ". $BASEDIR/sbin/es-common.sh; set_db_env;  ORACLE_SID=$ORACLE_SID; export ORACLE_SID;
			$ORACLE_HOME/bin/exp parfile=\\\"$par_file\\\" file=\\\"$exp_meta_file\\\"" 2>$tmp_file 1>&2
    retstatus=$?
    /usr/bin/rm -f $par_file
    if [ $retstatus -ne 0 ] ; then
        /usr/bin/rm -f $tmp_file
        return 1
    else
        db_checkErr $tmp_file $log_file
        if [ $? -ne 0 ];then
            echolog 'Unable to extract metadata file for tablespaces $2' "$tblsp_names"
            /usr/bin/rm -f $tmp_file
            return 1
        fi
    fi

    /usr/bin/rm -f $tmp_file 
    return 0
}


#db_prepPlugOutTt $user_name $user_passwd $out_file $exp_meta_file $log_file
#  DESCRIPTION: prepares schema $user_name, extracts
#               its data into transportable tablespaces,
#               drops the tablespaces and the user 
#  NOTE:    populates GLOBAL_TBLSP_NAMES with all the tablespaces associated
#           with schema $user_name and GLOBAL_TBLSP_FILES with all the datafiles
#           associated with the tablespaces above              
#  RETURNS: 0 - success
#           1 - failure
#
db_prepPlugOutTt () {
    user_name=$1
    user_passwd=$2
    out_file=$3
    exp_meta_file=$4
    log_file=$5

    GLOBAL_TBLSP_NAMES=""
    db_getTblspNames  $user_name $user_passwd $log_file
    [ $? -ne 0 ] && return 1

    GLOBAL_TBLSP_FILES=""
    db_getTblspFiles "$GLOBAL_TBLSP_NAMES" $log_file
    [ $? -ne 0 ] && return 1

    db_prepSchemaMigrate $out_file $user_name $user_passwd $log_file
    [ $? -ne 0 ] && return 1

    if [ ! -z "$GLOBAL_TBLSP_NAMES" ] ; then
        db_expDataTt "$GLOBAL_TBLSP_NAMES" $exp_meta_file $log_file
        [ $? -ne 0 ] && return 1

        # drop all tablespaces "including contents" associated with schema name
        for tblsp_name in $GLOBAL_TBLSP_NAMES ; do
            sqlcom="
DROP TABLESPACE $tblsp_name INCLUDING CONTENTS"

            db_runSql "$sqlcom" $SYS_LOGIN $SYSPWD $tmp_file
            db_checkErr $tmp_file $log_file
            if [ $? -ne 0 ];then
                echolog 'Unable to run sql $2 ' "$sqlcom" 
                /usr/bin/rm -f $tmp_file
                return 1
            fi
        done

        # drop user_name "cascade"
        sqlcom="
DROP USER $user_name CASCADE"

        db_runSql "$sqlcom" $SYS_LOGIN $SYSPWD $tmp_file
        db_checkErr $tmp_file $log_file
        if [ $? -ne 0 ];then
            echolog 'Unable to run sql $2 ' "$sqlcom" 
            /usr/bin/rm -f $tmp_file
            return 1
        fi
    fi

    /usr/bin/rm -f $tmp_file
    return 0
}

#db_getTblspNames $user_name $user_passwd $log_file
# DESCRIPTION: populates GLOBAL_TBLSP_NAMES with a list
#              of all tablespaces associated with a user
#              schema
#
# RETURNS: 0 - success
#          1 - failure
#  NOTE: GLOBAL_TBLSP_NAMES="tablespace1 tablespace2 ..."
#
db_getTblspNames () {
    user_name=$1
    user_passwd=$2
    log_file=$3

    tmp_file=$TEMPDIR/getTblspNames.$$
    /usr/bin/rm -f $tmp_file

    sqlcom="
SELECT DISTINCT tablespace_name FROM user_tables
UNION
SELECT DISTINCT tablespace_name FROM user_indexes
UNION 
SELECT DISTINCT def_tablespace_name FROM user_part_tables
UNION
SELECT DISTINCT def_tablespace_name FROM user_part_indexes"

    db_runSql "$sqlcom" $user_name $user_passwd $tmp_file
    db_checkErr $tmp_file $log_file
    if [ $? -ne 0 ];then
        echolog 'Unable to run sql $2' "$sqlcom" 
        /usr/bin/rm -f $tmp_file
        return 1
    fi

    GLOBAL_TBLSP_NAMES=`/usr/bin/cat $tmp_file|/usr/bin/xargs echo`
    /usr/bin/rm -f $tmp_file
    return 0
} 



#db_plug_in_tt $user_name $user_passwd  $data_files $tblsp_names $tt_metadata_dump_file $log_file
# DESCRIPTION: plugs in the datafiles defined by $data_files
#              into the tablespaces $tblsp_names
#              for user $user_name  with $user_passwd password
#              The metafile is $tt_metadata_dump_file
#
# RETURNS:  0 - success
#           1 - failure
#
db_plug_in_tt () {
    user_name=$1
    user_passwd=$2
    data_files="$3"
    tblsp_names=$4
    imp_meta_file=$5
    log_file=$6

    tmp_file=$TEMPDIR/plugInTt.$$
    /usr/bin/rm -f $tmp_file
    par_file=$TEMPDIR/plugInTt.par.$$
    /usr/bin/rm -f $par_file

    # drop user before (re-) creating it.
    # Exit code is not checked deliberately.
    # db_dropUser may be run if the user is not yet created.
    # Error messages are not indicative of any actual problem in this case.
    db_dropUser "$user_name" "$SYS_LOGIN" "$SYSPWD" "$log_file"

    #create database user
    sqlcom="CREATE USER $user_name IDENTIFIED BY $user_passwd"
    db_runSql "$sqlcom" $SYS_LOGIN $SYSPWD $tmp_file
    db_checkErr $tmp_file $log_file
    if [ $? -ne 0 ];then
        echolog 'Unable to create user $2 ' "$user_name" 
        /usr/bin/rm -f $tmp_file
        return 1
    fi
    sqlcom="GRANT CREATE SESSION TO $user_name"
    db_runSql "$sqlcom" $SYS_LOGIN $SYSPWD $tmp_file
    db_checkErr $tmp_file $log_file
    if [ $? -ne 0 ];then
        echolog 'Unable to grant session to user $2' "$user_name"
        /usr/bin/rm -f $tmp_file
        return 1
    fi

    #Create the import parfile
    #for the same reason as export above
    #
    /usr/bin/touch $par_file
    /bin/echo "userid=\"$SYS_LOGIN/$SYSPWD as sysdba\"" >> $par_file
    /bin/echo "transport_tablespace=y"              >> $par_file
    /bin/echo "datafiles=($data_files)"             >> $par_file

    # Fix file permissions
    for fname in $data_files $imp_meta_file ; do
        parentdir=`/usr/bin/dirname $fname`
        /usr/bin/chown $SMCORAU:$SMCORAG $fname $parentdir
        if [ $? -ne 0 ] ; then
            echolog 'Unable to fix permissions for export files'
            echolog ''
            echolog 'Please check the contents of $2 file.' $VAROPTDIR/upgrade/db/${user_name}_db_upgrade.meta
            echolog 'Please check that the directories and files specified'
            echolog 'against tt_data_files tag exist on your system.'
            echolog 'If the filenames are truncated in the metafile,'
            echolog 'please fix them manually and re-run setup for this component.'
            echolog ''
            return 1
        fi
    done

    #Import the transportable tablespaces metadata file
    /usr/bin/su - $SMCORAU -c ". $BASEDIR/sbin/es-common.sh; set_db_env; ORACLE_SID=$ORACLE_SID; export ORACLE_SID;
			$ORACLE_HOME/bin/imp parfile=\\\"$par_file\\\" file=\\\"$imp_meta_file\\\"" 2>$tmp_file 1>&2
    retstatus=$?
    /usr/bin/rm -f $par_file
    if [ $retstatus -ne 0 ] ; then
        echolog 'Unable to plug in datafiles $2' "$data_files"
        /usr/bin/rm -f $tmp_file
        return 1
    else
        db_checkErr $tmp_file $log_file
        if [ $? -ne 0 ];then
            echolog 'Unable to plug in datafiles $2' "$data_files"
            /usr/bin/rm -f $tmp_file
            return 1
        fi
    fi

    /usr/bin/rm -f $tmp_file

    #Change status to RW for plugged-in tablespaces
    for tblspace in $tblsp_names ; do
        db_setStatusTblsp $tblspace "RW" $log_file
        if [ $? -ne 0 ] ; then
            return 1
        fi
    done

    return 0
}

#db_dropSchemaConst $login $passwd $log_file
#  DESCRIPTION: will drop all constraints
#               associated with a schema
#            in the order R,C,U,P
#  
#  RETURNS:  0 - success
#            1 - failure
#
db_dropSchemaConst () {
    login=$1
    passwd=$2
    log_file=$3

    tmp_file=$TEMPDIR/dropSchemaConst.$$
    /usr/bin/rm -f $tmp_file

    sqlcom="
DECLARE
  CURSOR get_schemaConst
  IS
  SELECT constraint_name, table_name, constraint_type
  FROM   user_constraints 
  WHERE  constraint_name not like 'SYS%'
  ORDER BY DECODE(constraint_type,'R',1,'C',2,'U',3,4); 

  l_command VARCHAR2(256);
BEGIN
  FOR v_rec IN get_schemaConst LOOP
    BEGIN
      l_command := 'ALTER TABLE '||v_rec.table_name||' DROP CONSTRAINT '||v_rec.constraint_name;
      execute immediate l_command;
    EXCEPTION
      WHEN OTHERS THEN NULL;
    END;
  END LOOP;
END"
 
    db_runPlSql "$sqlcom" $login $passwd $tmp_file
    db_checkErr $tmp_file $log_file
    if [ $? -ne 0 ];then
        echologverbose 'Error running sql $2' "$sql"
        /usr/bin/rm -f $tmp_file
        return 1
    else
        /usr/bin/rm -f $tmp_file 
        return 0
    fi
}

#db_dropSchemaObj $object_type $login $passwd $log_file
#  DESCRIPTION: drops all Pl/Sql objects (procs/functions/packages/triggers)
#               indexes or synonyms associated with schema $login
#   NOTE: object_type could be PLS(ql Object)
#                           or IND(ex)
#                           or SYN(onym)
#  RETURNS: 0 - success
#           1 - failure
#           2 - wrong object_type
#
db_dropSchemaObj () {
    object_type=$1
    login=$2
    passwd=$3
    log_file=$4 

    tmp_file=$TEMPDIR/dropSchemaObj.$$
    /usr/bin/rm -f $tmp_file

    if [ "$object_type" = "PLS" ] ; then
        object_clause="'PROCEDURE','PACKAGE','FUNCTION','TRIGGER','TYPE'"
    elif [ "$object_type" = "IND" ] ; then
        object_clause="'INDEX'"
    elif [ "$object_type" = "SYN" ] ; then 
        object_clause="'SYNONYM'"
    else
        /usr/bin/rm -f $tmp_file
        return 2
    fi

    sqlcom="
DECLARE
  CURSOR get_schemaPls
  IS
  SELECT object_name, object_type
  FROM   user_objects 
  WHERE  object_type in ($object_clause);

  l_command VARCHAR2(256);
BEGIN
  FOR v_rec IN get_schemaPls LOOP
    BEGIN
      l_command := 'DROP '||v_rec.object_type||' '||v_rec.object_name;
      execute immediate l_command;
    EXCEPTION
      WHEN OTHERS THEN NULL;
    END;
  END LOOP;
END"

    db_runPlSql "$sqlcom" $login $passwd $tmp_file
    db_checkErr $tmp_file $log_file
    if [ $? -ne 0 ];then
        echologverbose 'Error running sql $2' "$sql"
        /usr/bin/rm -f $tmp_file
        return 1
    else
        /usr/bin/rm -f $tmp_file
        return 0
    fi
}

#db_revSequences  $user_name $user_passwd $file_to_save $log_file
#  DESCRIPTION: extracts sequences associated
#               with schema_name into file_to_save
#  RETURNS: 0 - success
#           1 - failure
#
db_revSequences () {
    user_name=$1
    user_passwd=$2
    file_to_save=$3
    log_file=$4

    sqlcom="select 'CREATE SEQUENCE '||sequence_name||' START WITH '||last_number||
' INCREMENT BY '||increment_by||' '||chr(10)||
DECODE(max_value,999999999999999999999999999,'NOMAXVALUE','MAXVALUE '||max_value)||' '||chr(10)||
DECODE(min_value,1,'NOMINVALUE','MINVALUE '||min_value)||' '||
DECODE(cycle_flag,'Y','CYCLE','NOCYCLE')||' '||chr(10)||
DECODE(cache_size,0,'NOCACHE','CACHE '||cache_size)||' '||DECODE(order_flag,'Y','ORDER','NOORDER')||';'
from user_sequences"

    db_runSqlSpool "$sqlcom" $file_to_save "SQL" $user_name $user_passwd $log_file
    [ $? -ne 0 ] && return 1
    return 0
}

#db_prepSchemaMigrate $out_file $login $passwd $log_file
#  DESCRIPTION: prepares schema $login for migration 
#               extracting the sequence definition to $out_file 
#               dropping PlSql objects, Synonyms, Indexes
#               and Constraints
#
#  RETURNS: 0 - success
#           1 - failure
#
db_prepSchemaMigrate () {
    out_file=$1
    login=$2
    passwd=$3
    log_file=$4
 
    if [ -f "$out_file" ] ; then
        /usr/bin/rm -f $out_file
    fi
    db_revSequences $login $passwd $out_file $log_file
    [ $? -ne 0 ] && return 1

    for obj_type in 'PLS' 'SYN' 'IND' ; do
        db_dropSchemaObj $obj_type $login $passwd $log_file
        [ $? -ne 0 ] && return 1
    done

    db_dropSchemaConst $login $passwd $log_file
    [ $? -ne 0 ] && return 1

    return 0
}

#db_getTblspFiles $tblsp_names $log_file
# DESCRIPTION: populates a global variable GLOBAL_TBLSP_FILES
#              with all the tablespace files associated with the tablespaces
#              found in $tblsp_names
#   RETURNS: 0 - success
#            1 - failure
#
db_getTblspFiles () {
    tblsp_names=$1
    log_file=$2

    for tsname in $tblsp_names ; do
        db_tblspFile $tsname $SYS_LOGIN $SYSPWD $log_file
        [ $? -ne 0 ] && return 1
        GLOBAL_TBLSP_FILES="$GLOBAL_TBLSP_FILES $GLOBAL_DIR_NAME"
    done

    return 0
} 

# db_do_export $db_username $passwd $type $logfile
# General database export function.
#	$username = database username to export
#	$passwd   = password for username
#	$type     = regular_export | transportable_tablespaces
#	$logfile  = log file
#
db_do_export () {
    user=$1; passwd=$2; exptype=$3; logfile=$4
    metafile=$VAROPTDIR/upgrade/db/${user}_db_upgrade.meta

    # Make sure database export directories are present
    if [ ! -d "$VAROPTDIR/upgrade/db" ] ; then
        /usr/bin/mkdir -p $VAROPTDIR/upgrade/db
        /usr/bin/chown $SMCORAU $VAROPTDIR/upgrade/db
        # (We need the chown otherwise smcorau will not be able to write the
        # export file to it.)
    fi

    # Determine core Sun Management Center version from Solaris package info
    version="$SUNMC_VERSION"

    if [ "$exptype" = "regular_export" ] ; then
        db_do_regular_export $user $passwd $metafile "$version" $logfile
        return $?
    elif [ "$exptype" = "transportable_tablespaces" ] ; then
        db_do_transportable_export $user $passwd $metafile "$version" $logfile
        return $?
    else
        # Error - bad export type
        echologverbose 'Unknown export type: $2' "$exptype"
        return 1
    fi
}

# do_regular_export $db_username $passwd $metafile $version $logfile
db_do_regular_export () {
    user=$1; passwd=$2; metafile=$3; version="$4"; logfile=$5

    DBEXP=$ORACLE_HOME/bin/exp
    destfile=$VAROPTDIR/upgrade/db/${user}_re.dmp

    set_db_password
    [ $? -ne 0 ] && return 1

    $DBEXP $SYS_LOGIN/$SYSPWD owner=$user direct=y file=$destfile log=$logfile rows=y consistent=y constraints=n indexes=n grants=y >> $logfile 2>&1
    if [ $? -ne 0 ] ; then
        echolog 'Error occurred while exporting data for $2' "$user"
        return 1
    fi

    # create metafile
    /usr/bin/cat <<EOF >$metafile
core_product_version=$version
export_option=regular_export
re_dump_file=$destfile
EOF

    return $?
}

# db_determine_regular_export_size $db_username $logfile
#
# Returns: size - [Kb] for the compressed export file  
#            1  - error
#
db_determine_regular_export_size () {
    user=$1; logfile=$2

    sizeK=1
    pipe=$TEMPDIR/re_export_sock.$$
    /usr/bin/rm -f $pipe
    tmpfile=$TEMPDIR/dd_output.$$
    /usr/bin/rm -f $tmpfile
    expfile=$TEMPDIR/exp_output.$$
    /usr/bin/rm -f $expfile

    DBEXP=$ORACLE_HOME/bin/exp
    set_db_password
    if [ $? -ne 0 ] ; then
      return 1
    fi

    /usr/sbin/mknod $pipe p
    if [ $? -ne 0 ] ; then 
     /usr/bin/rm -f $pipe
     return 1
    fi

    # changing locale to english in order to run dd and get the proper
    # output (f+p records in/out). This output seems to be different
    # between different Chinese locales, Koreean and Japanese so in order
    # to get the proper output the calculation needs to be done using "C"
    # once that is complete the locale will be reverted to the original
    # one
    [ -n "$LANG" ] && dd_temp_lang=$LANG
    [ -n "$LC_ALL" ] && dd_temp_lc=$LC_ALL
    LANG=C; export LANG
    LC_ALL=C; export LC_ALL

    # attach compress and dd to $pipe
    /usr/bin/cat $pipe | /usr/bin/compress | /usr/bin/dd bs=1024 of=/dev/null 2>$tmpfile &
    pipepid=$!

    # export into pipe
    $DBEXP $SYS_LOGIN/$SYSPWD owner=$user direct=y file=$pipe rows=y consistent=y constraints=n indexes=n grants=y 1>$expfile 2>&1
    retstatus=$?

    if [ $retstatus -ne 0 ] ; then
       # revert the locale to the original one in order for the messages
       # to be printed properly before returning from function
       #
       LANG=${dd_temp_lang:-""}; export LANG
       LC_ALL=${dd_temp_lc:-""}; export LC_ALL
       echolog 'Unable to pseudo_export data for user $2' "$user"
       /usr/bin/rm -f $pipe; /usr/bin/rm -f $expfile; /usr/bin/rm -f $tmpfile
       kill $pipepid >/dev/null 2>&1
       return 1
    else 
      db_checkErr $expfile $logfile
      if [ $? -ne 0 ];then
        LANG=${dd_temp_lang:-""}; export LANG
        LC_ALL=${dd_temp_lc:-""}; export LC_ALL
        echolog 'Unable to pseudo_export data for user $2' "$user"
        /usr/bin/rm -f $pipe; /usr/bin/rm -f $tmpfile; /usr/bin/rm -f $expfile
        kill $pipepid >/dev/null 2>&1
        return 1
      fi
    fi

    kill $pipepid >/dev/null 2>&1

    sizeK=`/usr/bin/cat $tmpfile|/usr/bin/sed -n '1p'|/usr/bin/awk -F+ '{ print $1; }'`
    sizeK=`/usr/bin/expr $sizeK + 2 2>/dev/null`

    # revert the locale to the original one in order for the messages
    # to be printed properly before returning from function
    #
    LANG=${dd_temp_lang:-""}; export LANG
    LC_ALL=${dd_temp_lc:-""}; export LC_ALL
    if [ $? -ne 0 ] ; then
     echolog 'Error calculating the export size for user $2' "$user"
     /usr/bin/rm -f $pipe; /usr/bin/rm -f $tmpfile; /usr/bin/rm -f $expfile 
     return 1
    fi 

    /usr/bin/rm -f $pipe; /usr/bin/rm -f $tmpfile; /usr/bin/rm -f $expfile 
    return $sizeK
}

# db_determine_export_size  $smc_ver (3.0|3.5)
#
# It  will calculate the amount of space required by all addons 
# to be migrated calling the db_determine_regular_export_size for 
# each of them + a predetermined amount of space for PRM (10M) + 
# a buffer for all the aditional migration files (10M).
# 
#  Returns: 0 - success
#           1 - failure
#
#   Log the amount of space required in $VAROPTDIR for migration 
#
db_determine_export_size()
{
  smc_ver=$1
  sch_user=SUNMC_OWNER
  exp_size=0
  save_dir=$VAROPTDIR
  avail_space=0
  add_space=0
  retsize=0

  # transportable buffer size = 10240k
  tr_buffer=10240
  # file buffer size = 10240k
  file_buffer=10240
  
  if [ "$smc_ver" = "3.5" ] ; then
    db_determine_regular_export_size $sch_user $LOGFILE
    retsize=$?
    [ $retsize -eq 1 ] && return 1
    exp_size=`/usr/bin/expr $exp_size + $retsize`
  fi

  for namecfg in `/usr/bin/find $VAROPTDIR/cfg -name \*dbase.cfg` ; do
    name_user=`/usr/bin/egrep '^user=' $namecfg | /usr/bin/cut -f2 -d=`
    name_passwd=`/usr/bin/egrep '^password=' $namecfg | /usr/bin/cut -f2 -d=`
    name_type=`/usr/bin/egrep '^export_option=' $namecfg | /usr/bin/cut -f2 -d=`

    if [ -z "$name_user" -o -z "$name_passwd" ] ; then
        echologverbose 'Error: unable to parse $2' "$namecfg"
        return 1
    fi

    if [ -z "$name_type" ] ; then
      if [ "$name_user" = "report" ] ; then
        name_type=transportable_tablespaces
      else
        name_type=regular_export
      fi
    fi

    if [ "$name_type" = "regular_export" ] ; then
      db_determine_regular_export_size $name_user $LOGFILE
      retsize=$?
      [ $retsize -eq 1 ]  && return 1
      exp_size=`/usr/bin/expr $exp_size + $retsize`
    elif [ "$name_type" = "transportable_tablespaces" ] ; then
      exp_size=`/usr/bin/expr $exp_size + $tr_buffer`
    fi 
  done
  
  exp_size=`/usr/bin/expr $exp_size + $file_buffer`
  exp_size_Mb=`/usr/bin/expr $exp_size / 1024`

  #available space calculated in Kb
  if [ -d "$VAROPTDIR/upgrade" ] ; then
    save_dir="$VAROPTDIR/upgrade" 
  fi
  avail_space=`/usr/bin/df -k $save_dir | /usr/bin/sed -e '1d' | /usr/bin/awk '{print $4}'`

  add_space=`/usr/bin/expr $avail_space - $exp_size`

  #the amount of required disk space needs to be logged in Mb
  if [ $add_space -lt 0 ] ; then
    add_space=`/usr/bin/expr $add_space \* -1 / 1024`
    add_space=`/usr/bin/expr $add_space + 2`

    echolog 'Not enough disk space available in $2 to migrate your data' "$VAROPTDIR"
    echolog 'The amount of space required is $2 Mb' "$exp_size_Mb"
    return 1
  else
    return 0
  fi
}

# do_transportable_export $db_username $passwd $metafile $version $logfile
db_do_transportable_export () {
    user=$1; passwd=$2; metafile=$3; version="$4"; logfile=$5

    export_meta=$VAROPTDIR/upgrade/db/${user}_tt.dmp
    seq_script=$VAROPTDIR/upgrade/db/${user}_sequences.sql

    # export
    db_prepPlugOutTt $user $passwd $seq_script $export_meta $logfile
    if [ $? -ne 0 ] ; then
        echologverbose 'Error occurred while doing transportable export for $2' "$user"
        return 1
    fi

    # create metafile
    /usr/bin/cat <<EOF >$metafile
core_product_version=$version
export_option=transportable_tablespaces
seq_script=$seq_script
tt_dump_file=$export_meta
tt_tablespaces=$GLOBAL_TBLSP_NAMES
tt_data_files=$GLOBAL_TBLSP_FILES
EOF

    return $?
}

# db_migr_export_present $db_username
# Checks if there is exported data for $user to be imported.
# This is determined by whether an export metafile is present for the given
# user.
# Sets $metafile to be the path of the metafile, if it exists.
db_migr_export_present () {
    user=$1
    metafile=$VAROPTDIR/upgrade/db/${user}_db_upgrade.meta

    [ -f "$metafile" ]
}

# db_migr_read_meta $db_username
# Read metafile for database user $user. Sets the following environment
# variables:
#	MIGR_EXPORT_TYPE	"regular_export" or "transportable_tablespaces"
#	MIGR_CORE_PRODUCT_VER	Version of core product when export
#				was made
#	MIGR_SEQ_FILE		Location of SQL script to re-create sequences
#	MIGR_ADDITIONAL_FILES	List of additional files to be cleaned up if
#				the addon associated with the user was not
#				installed after the migration.
#
# For regular_export:
#	MIGR_RE_DUMPFILE	Location of database export dump file
#
# For transportable_tablespaces:
#	MIGR_TT_DUMPFILE	Location of database export metafile
#	MIGR_TT_TABLESPACES	List of space-separated tablespace names
#				associated with $user
#	MIGR_TT_DATAFILES	List of tablespace files associated with $user
#
# Returns:
#	0 - successful
#	1 - no export data found for $dbuser
#	2 - error occurred
#
db_migr_read_meta () {
    dbuser=$1

    # Check if we have data for given $user
    db_migr_export_present $dbuser
    if [ $? -ne 0 ] ; then
        # No metafile found for $dbuser
        return 1
    fi
    db_migr_read_meta__real
    return $?
}
# Internal convenience function, separated from db_migr_read_meta so we can
# call it with a pathname instead of a username. $metafile should be set
# before calling this function.
db_migr_read_meta__real () {
    MIGR_CORE_PRODUCT_VER=`get_value_from_cfgfile $metafile core_product_version =`
    MIGR_EXPORT_TYPE=`get_value_from_cfgfile $metafile export_option =`
    MIGR_SEQ_FILE=`get_value_from_cfgfile $metafile seq_script =`
    MIGR_ADDITIONAL_FILES=`get_value_from_cfgfile $metafile additional_files =`

    export MIGR_CORE_PRODUCT_VER
    export MIGR_EXPORT_TYPE
    export MIGR_SEQ_FILE

    if   [ "$MIGR_EXPORT_TYPE" = "regular_export" ] ; then
        #
        # Regular export
        #

        MIGR_RE_DUMPFILE=`get_value_from_cfgfile $metafile re_dump_file =`
        export MIGR_RE_DUMPFILE

        return 0

    elif [ "$MIGR_EXPORT_TYPE" = "transportable_tablespaces" ] ; then
        #
        # Transportable tablespaces
        #

        MIGR_TT_DUMPFILE=`get_value_from_cfgfile $metafile tt_dump_file =`
        MIGR_TT_TABLESPACES=`get_value_from_cfgfile $metafile tt_tablespaces =`
        MIGR_TT_DATAFILES=`get_value_from_cfgfile $metafile tt_data_files =`

        export MIGR_TT_DUMPFILE
        export MIGR_TT_TABLESPACES
        export MIGR_TT_DATAFILES

        return 0

    else
        # Error: unknown export type
        unset MIGR_EXPORT_TYPE
        return 2
    fi
}


# db_do_re_import $user_name $user_passwd $dmpfile $logfile
# - do a regular import of exported data for $user_name
# - NOTE: for importing 3.0 sunmc schema, pass in an additional argument "1"
#   to cause SUNMC to be imported into SUNMC_OWNER.
db_do_re_import () {
    user=$1; passwd=$2; dmpfile=$3; logfile=$4; is30=$5

    set_db_password
    [ $? -ne 0 ] && return 1

    fromuser=$user
    touser=$user

    # Special case: 3.0 export will be under "sunmc", whereas 3.5 needs to be
    # under "sunmc_owner". We check for that here.
    if [ "$is30" -eq 1 -a "$fromuser" = "SUNMC" ] ; then
        touser=SUNMC_OWNER
    fi

    NLS_LANG=AMERICAN_AMERICA.UTF8; export NLS_LANG

    $ORACLE_HOME/bin/imp $SYS_LOGIN/$SYSPWD fromuser=$fromuser touser=$touser \
		file=$dmpfile ignore=y indexes=n grants=y constraints=n \
		log=$logfile >> $logfile 2>&1
    [ $? -ne 0 ] && return 1

    return 0;
}

# db_do_tt_import $user_name $user_passwd $logfile
# DESCRIPTION: retrieves data from the user-associated
#              mgration metadata file and plugs in the 
#              tablespaces associated with it.
#
db_do_tt_import () {
   
    user_name=$1
    user_passwd=$2
    logfile=$3

    db_migr_read_meta $user_name
    [ $? -ne 0 ] && return 1

    db_plug_in_tt $user_name $user_passwd "$MIGR_TT_DATAFILES" "$MIGR_TT_TABLESPACES" $MIGR_TT_DUMPFILE $logfile
    [ $? -ne 0 ] && return 1
    
    return 0
}

# db_migr_import_user $dbuser $passwd $logfile
# Reads export file for $dbuser and performs a basic database import of the
# data described by the export file. Note that the caller will still need to
# handle other addon/core-specific stuff such as re-creating SQL objects,
# massaging the imported data to work with the new database schema, etc..
#
# NOTE: the caller is responsible for preparing the existing database for the
# import, such as disabling constraints, starting the database in restricted
# mode, etc.. It is not done here because the caller potentially needs to do
# additional stuff before/after the import, and may want the database to remain
# in restricted mode throughout the operation.
#
# - NOTE: for importing 3.0 sunmc schema, pass in an additional argument "1"
#   to cause SUNMC to be imported into SUNMC_OWNER.
#
# Returns:
#	0 - successful
#	1 - no export data found for $dbuser
#	2 - error occurred
db_migr_import_user () {
    dbuser=$1; passwd="$2"; logfile=$3; sunmc30_flag=$4

    # Get export information for $dbuser
    db_migr_read_meta $dbuser
    rcode=$?
    if [ $rcode -ne 0 ] ; then
        return $rcode
    fi

    if [ "$MIGR_EXPORT_TYPE" = "regular_export" ] ; then
        #
        # Do regular import
        #

        db_do_re_import $dbuser $passwd $MIGR_RE_DUMPFILE $logfile $sunmc30_flag
        [ $? -ne 0 ] && return 1

    elif [ "$MIGR_EXPORT_TYPE" = "transportable_tablespaces" ] ; then
        #
        # Do transportable import
        #

        db_plug_in_tt $dbuser "$passwd" "$MIGR_TT_DATAFILES" "$MIGR_TT_TABLESPACES" $MIGR_TT_DUMPFILE $logfile
        [ $? -ne 0 ] && return 1
    else
        echologverbose 'Unknown export type: $2 for user $3' "$2" "$dbuser"
        echolog 'Internal error while attempting to import old data'
        return 2
    fi

    return 0
}

# db_migr_cleanup_user_assoc_files $username
# - same as db_migr_cleanup_assoc_files except that the argument is the
#   database username.
db_migr_cleanup_user_assoc_files () {
    db_migr_cleanup_assoc_files $VAROPTDIR/upgrade/db/${1}_db_upgrade.meta
}

# db_migr_cleanup_assoc_files $metafile
# - Removes all migration data files referenced by $metafile.
db_migr_cleanup_assoc_files () {
    metafile=$1
    [ ! -f "$metafile" ] && return 1

    # Extract filenames from metafile
    db_migr_read_meta__real $metafile
    [ $? -ne 0 ] && return 1

    # Clean up all files referenced by metafile
    [   -f "$MIGR_SEQ_FILE" ]         && /usr/bin/rm -f  $MIGR_SEQ_FILE
    [ ! -z "$MIGR_ADDITIONAL_FILES" ] && /usr/bin/rm -rf $MIGR_ADDITIONAL_FILES
    [   -f "$MIGR_RE_DUMPFILE" ]      && /usr/bin/rm -f  $MIGR_RE_DUMPFILE
    [   -f "$MIGR_TT_DUMPFILE" ]      && /usr/bin/rm -f  $MIGR_TT_DUMPFILE
    [ ! -z "$MIGR_TT_DATAFILES" ]     && /usr/bin/rm -f  $MIGR_TT_DATAFILES

    # Finally, clean up metafile
    /usr/bin/rm -f $metafile

    return 0
}

migrate_agent_data_only () {

   [ "$OLDDATADIR" = "" ] && return

   OLDCFG=$OLDDATADIR/cfg
   CFGDIR=$VAROPTDIR/cfg
   cfg_cnt=0
   [ -d "$OLDCFG" ] && cfg_cnt=`$CMD_LS -1 $OLDCFG |/usr/bin/wc -l`

   if [ $cfg_cnt -gt 0 ] ; then
      # Migrate the agent data.
      echolog ''
      READ_RESPONSE_ONCE=0
      fetch_response_yes_no "TAG=IMPORT_PREVIOUS_DATA" 'Do you want to import your previous data '
      [ $? -gt 0 ] && exit_SunMC_setup "$SUMMARY_READ_ERROR"
      saveAutoConfig "IMPORT_PREVIOUS_DATA" "$answer"
         if [ "$answer" = "0" ]; then
              echolog "Setup will not import previous data."
              # Explicitly export MIGRATE_DATA flag if it is 0,
              # So that addons can pick it up.
              MIGRATE_DATA=0
              export MIGRATE_DATA
         else
              migrate_cfg_files
              /usr/bin/rm -rf "$OLDCFG" $OLDDATADIR/bin
	      MIGRATE_DATA=1
	      export MIGRATE_DATA
         fi
   fi

}

#db_simpleValidSetup $username $dbcfg
#
# DESCRIPTION: simple setup validation for a database $username
#              and $dbcfg
#
#   RETURNS: 0 - success (both present)
#            1 - failure (either of the one not present)
#
db_simpleValidSetup () {

  username=$1; dbcfg=$2

  db_checkUser $SYS_LOGIN $SYSPWD $username $LOGFILE
  if [ $? -ne 0 ] ; then
    return 1
  fi
  if [ -f "$dbcfg" ] ; then
    tempuser=`/usr/bin/egrep '^user=' $dbcfg | /usr/bin/cut -f2 -d=`
    tempasswd=`/usr/bin/egrep '^password=' $dbcfg | /usr/bin/cut -f2 -d=`
    temptype=`/usr/bin/egrep '^export_option=' $dbcfg | /usr/bin/cut -f2 -d=`

    if [ -z "$tempuser" -o -z "$tempasswd" ] ; then
        return 1
    fi
  else
      return 1
  fi

  return 0
}

# db_migr_meta_add_addf $mmaa_dbuser $mmaa_listoff
#  Adds the additional entry ADDITIONAL_FILES to the 
# migration metadatafile associated with "$mmaa_dbuser"
#
# Returns:
#	0 - successful
#	1 - no export data found for $mmaa_dbuser
#	2 - error occurred
#
db_migr_meta_add_addf () {
    mmaa_dbuser=$1
    mmaa_listoff="$2"

    # Check if we have data for given $user
    db_migr_export_present $mmaa_dbuser
    if [ $? -ne 0 ] ; then
        # No metafile found for $mmaa_dbuser
        return 1
    fi
    db_migr_meta__add_addf "additional_files" "$mmaa_listoff"
    return $?
}

# db_migr_meta__add_addf $mmaa_entry $mm_aa_files 
#  Adds the "$mm_aa_entry"="$mm_aa_files" to the metadata file 
# initialized by the db_migr_meta_add_addf(), $metafile.
#
# NOTE: This function ONLY adds an entry to the $metafile
#       Its invocation should be preceded by the removal of 
# the same entry if it exists (TO BE DONE) 
# 
#
#  Returns: 0 - success
#           2 - error occurred
#
db_migr_meta__add_addf () {
 mm_aa_entry=$1
 mm_aa_files="$2"

 echo "$mm_aa_entry=$mm_aa_files" >> "$metafile" 

 [ $? -ne 0 ] && return 2
 return 0
}

# db_check_avail_disk_size $dirname $availsize
# 
# NOTE: $availsize [Kb]
#
# Returns:  0 - at list $availsize available   
#           1 - less than $availsize available 
#	    2 - error
#
db_check_avail_disk_size () {
    dir=$1 
    size=$2

    retstat=0

    avail_space=`/usr/bin/df -k $dir | /usr/bin/sed -e '1d' | /usr/bin/awk '{print $4}'`
    
    # Making sure the avail_space is a number indeed.
    # If not the following expr evaluation will return non-zero.
    #
    avail_space=`/usr/bin/expr $avail_space + 1 - 1 2>/dev/null`

    if [ $? -lt 0 ] ; then
       retstat=2
    elif [ "$avail_space" -lt "$size" ] ; then
       retstat=1
    fi

    return $retstat
}

#smc_get_physical_memory
#
# RETURNS: 0 - success
#          1 - failure
#
# NOTE: It sets the environment variable SMC_MEMSIZE to the 
#       amount of physical memory installed.
#
smc_get_physical_memory() {

    # the prtconf output seems to be slightly different between various locales
    # get the report out in "C" and revert it back at the end.
    #
    [ -n "$LANG" ] && smc_gpm_lang=$LANG
    [ -n "$LC_ALL" ] && smc_gpm_lcall=$LC_ALL
    LANG=C; export LANG
    LC_ALL=C; export LC_ALL

    SMC_MEMSIZE=`/usr/sbin/prtconf | $CMD_GREP "Memory size: " | $CMD_CUT -f3 -d' '`
    retstat=$?

    LANG=${smc_gpm_lang:-""}; export LANG
    LC_ALL=${smc_gpm_lcall:-""}; export LC_ALL

    if [ $retstat -ne 0 ] ; then
     echolog 'Error calculating the amount of phsycal memory installed'
     return 1
    fi

    return 0
}

# smc_get_config_all_section $config_file
#
# Populates the global SMC_ALL_SECTIONS with a '\n' separated
# list of configuration entries (section_no:line_no:section_name\n)
# like:
# 1:20:section_1
# 2:40:section_2
# ...
# n:mm:section_x
# n+1:no_lines_config_file:config_file_name
#  (last entry contains the total number of lines in the file:file_name)
#
# RETURNS: 0 - success
#          1 - config_file doesn't exist
#          2 - config_file not a config_file
#
smc_get_config_all_section () {
  config_file=$1

  retstat=0; i=0; nlines=0
  SMC_ALL_SECTIONS=""

  [ ! -f "$config_file" ] && return 1
  /usr/bin/egrep -i "^\[.*\]" $config_file > /dev/null 
  [ $? -eq 1 ] && return 2

  for sect_name in `/usr/bin/egrep -n "^\[.*\]" $config_file`; do
        i=`/usr/bin/expr $i + 1`
	SMC_ALL_SECTIONS="$SMC_ALL_SECTIONS $i:$sect_name \n"
  done
  i=`/usr/bin/expr $i + 1`
  nlines=`/usr/bin/wc -l $config_file|/usr/bin/sed 's/[ 	]*//'|/usr/bin/nawk '{ print $1 }'`
  SMC_ALL_SECTIONS="$SMC_ALL_SECTIONS $i:$nlines:[`/usr/bin/basename ${config_file}`]"

  return 0
}

# smc_get_config_info_section $config_file $section
# Populates two globals SECT_BLINE and SECT_ELINE
# with the section line limits.
#
# RETURNS: 0 - success
#          1 - config_file not found
#          2 - config_file not config_file
#          3 - section not found
#
smc_get_config_info_section () {
  config_file=$1
  section=$2

  retstat=0; i=0; nlines=0
  sect_pos=0; sect_bline=0
  retstat=0;

  SMC_ALL_SECTIONS=" "
  smc_get_config_all_section $config_file
  retstat=$?
  [  "$retstat" -ne  0 ] && return $retstat

  sect_tot=`echo "$SMC_ALL_SECTIONS"|/usr/bin/wc -w`
 # the last line is not a real section but the file total
  sect_tot=`/usr/bin/expr $sect_tot - 1`

  sect_pos=`echo "$SMC_ALL_SECTIONS"|/usr/bin/egrep "${section}"|/usr/bin/nawk -F: '{ print $1 }'`
  [ ! -n "$sect_pos" ] && return 3

  SECT_BLINE=`echo "$SMC_ALL_SECTIONS"|/usr/bin/egrep "${section}"|/usr/bin/nawk -F: '{ print $2 }'`
  SECT_BLINE=`/usr/bin/expr $SECT_BLINE + 1`

  # if not the last section...
  if [ $sect_pos -lt $sect_tot ]; then
    next_sect_pos=`/usr/bin/expr $sect_pos + 1`
    SECT_ELINE=`echo "$SMC_ALL_SECTIONS"|/usr/bin/egrep " ${next_sect_pos}:.*"|/usr/bin/nawk -F: '{ print $2 }'`
    SECT_ELINE=`/usr/bin/expr $SECT_ELINE - 1`
  else
    sect_tot=`/usr/bin/expr $sect_tot + 1`
    next_sect_pos=`echo "$SMC_ALL_SECTIONS"|/usr/bin/egrep " ${sect_tot}:.*"|/usr/bin/nawk -F: '{ print $2 }'`
    SECT_ELINE=`/usr/bin/expr $next_sect_pos - 1`
 fi

  return 0
}

# smc_get_config_sect $config_file $section $var_store
#
# Retrieves the entire content of the $config_file $section
# into the environment variable $var_store
# It is meant for Oracle constant sections which go "as is"
# into orainit
#
# Returns: 0 - success
#          1 - config_file not found
#          2 - config_file not config_file
#          3 - section not found
#
smc_get_config_sect () {
  config_file=$1
  section=$2
  var_store=$3

  retstat=0
  section_store=""
  tmp_file="$TEMPDIR/smc_get_config_sect.$$"
  /usr/bin/rm -f $TEMPDIR/smc_get_config_sect.* 

  SECT_BLINE=0
  SECT_ELINE=0

  smc_get_config_info_section $config_file $section
  retstat=$?
  [ "$retstat" -ne 0 ] && return $retstat

  /usr/bin/sed -n "${SECT_BLINE},${SECT_ELINE}"p $config_file > $tmp_file
  section_store=`cat $tmp_file`
  eval $var_store='$section_store'

  /usr/bin/rm -f $tmp_file
  return 0
}

# smc_get_section_entry $config_file $section $entry $entry_store
#
# Returns: 0 - success
#          1 - config_file not found
#          2 - config_file not config_file
#          3 - section not found
#          4 - entry  not found
#
smc_get_section_entry () {
  config_file=$1
  section=$2
  entry=$3
  entry_store=$4

  retstat=0

  SMC_GET_SECTION_TMP=""
  smc_get_config_sect $config_file $section SMC_GET_SECTION_TMP 
  retstat=$?
  [ "$retstat" -ne 0 ] && return $retstat

  unset tmp_entry
  tmp_entry=`echo "$SMC_GET_SECTION_TMP"|/usr/bin/egrep "${entry}[ 	]*="`
  [ ! -n "$tmp_entry" ] && return 4
  eval $entry_store='$tmp_entry'
 
  return 0
}

# smc_get_section_key_value $config_file $section $section_key $key_store
#
# Returns: 0 - success
#          1 - config_file not found
#          2 - config_file not config_file
#          3 - section not found
#          4 - entry  not found
#
smc_get_config_section_key_value () {
  config_file=$1
  section=$2
  section_key=$3
  key_store=$4

  retstat=0

  SMC_GET_ENTRY_TMP=""
  smc_get_section_entry $config_file $section $section_key SMC_GET_ENTRY_TMP 
  retstat=$?
  [ "$retstat" -ne 0 ] && return $retstat

  unset tmp_entry 
  tmp_entry=`echo "$SMC_GET_ENTRY_TMP"|/usr/bin/sed -e "s/${section_key}[ 	]*=[ 	]*//"`
  [ ! -n "$tmp_entry" ] && return 4
  eval $key_store='$tmp_entry'

  return 0
}

#smc_get_current_memconfig $config_file $memsize
#   NOTE: The $memsize passed in represents the total amount of physical memory
#         found on the machine
#
# sets the env variables:
#         SMC_CONFIG="small|medium|large" & SMC_MEM_CONFIG=<value in Mb>
#
# Returns: 0 - success
#          1 - config_file not found
#          2 - config_file not config_file
#          3 - section not found
#          4 - entry  not found
#          5 - unexpected error
#
smc_get_current_memconfig () {
  config_file=$1
  sgcm_memsize=$2

  smc_retstat=0; SMC_ENTRY=0; SMC_CONFIG=""; SMC_MEM_CONFIG=0
  smc_entry_l=0; smc_entry_h=0

  for config_type in small medium large; do
    smc_get_config_section_key_value $config_file db_standard_config $config_type SMC_ENTRY
    smc_retstat=$?
    [ "$smc_retstat" -ne 0 ] && return $smc_retstat

    SMC_ENTRY=`/usr/bin/echo "$SMC_ENTRY"|/usr/bin/sed -e 's/(//' -e 's/)//'` 
    smc_entry_l=`/usr/bin/echo "$SMC_ENTRY"|/usr/bin/nawk -F"-" '{ print $1 }'`
    smc_entry_h=`/usr/bin/echo "$SMC_ENTRY"|/usr/bin/nawk -F"-" '{ print $2 }'`

    # If upper limit not set as in "large = (2048-)" set to a huge number
    # In this case upper limit set to ~ 1000 G
    #
    smc_entry_h=${smc_entry_h:=1000000}

    if [ "$sgcm_memsize" -ge "$smc_entry_l" -a  "$sgcm_memsize" -le "$smc_entry_h" ]; then
      SMC_CONFIG=$config_type 
      SMC_MEM_CONFIG="$smc_entry_l"
      return 0
    fi
  done

  return 5
}

# gen_checkDirSpace $dirname $size
#     NOTE: size is in Kb
#
#   DESCRIPTION: checks if enough space is available
#
#     Returns:  0 - space available
#               1 - space not available
#               2 - error
#
gen_checkDirSpace () {
   dirname=$1; size2=$2;

   avail=`/usr/bin/df -k "$dirname" | /usr/bin/tail -1 | /usr/bin/awk '{ print $4 }'`
   if [ $? -ne 0 ] ; then
       echolog 'Failed to check the available free space on $2' "$dirname"
       return 2
   fi

   if  [ "$size2" -gt "$avail" ];then
       return 1
   fi
   return 0
}

#smc_verify_current_setup 
#
# RETURNS: 0 - success (setup not required)
#          1 - cfgfile missing
#          2 - initOra missing 
#          3 - cksum(s) not found in the cfg file 
#          4 - cksum(s) found and different
#
smc_verify_current_setup () {

  dbase_cfg="${VAROPTDIR}/cfg/dbase.cfg"
  initfile_ora="$ORA_INITFILE"

  #dbase_cfg file not found 
  #
  [ ! -f "$dbase_cfg" ] && return 1

  #initfile_ora not found
  #
  [ ! -f "$initfile_ora" ] && return 2

  # entries not found in dbase_cfg
  #
  initCksumValOld=`/usr/bin/egrep '^initCksum=' $dbase_cfg | /usr/bin/cut -f2 -d=`

  [ -z "$initCksumValOld" ] && return 3

  # cksum for initfile_ora diff
  #
  initCksumValNew=`/usr/bin/cksum "$initfile_ora"|/usr/bin/awk '{ print $1 ":" $2 }'`
  [ "$initCksumValNew" != "$initCksumValOld" ] && return 4

  return 0
}

# smc_get_core_config
#
# Returns: 1  - small configuration
#          2  - medium
#          3  - large
#          4  - error|unknown configuration
#
#  NOTE: This function will return the standard memory configuration
#        the core server belongs to (small, medium or large) regardless
#        of the actual configuration (which could be custom).
#
smc_get_core_config () {

    SMC_CONFIG_MEMSIZE=0

    dbase_cfg="${VAROPTDIR}/cfg/dbase.cfg"
    SMC_CONFIG_MEMSIZE=`/usr/bin/egrep '^physicalMemory=' $dbase_cfg | /usr/bin/cut -f2 -d=` 
    
    smc_get_memory_config "$SMC_CONFIG_MEMSIZE"
    return $?
}


# smc_get_memory_config "$memconfig"
#
# Returns: 1  - small configuration
#          2  - medium
#          3  - large
#          4  - error|unknown configuration
#
#  NOTE: This function will return the standard memory configuration
#        coresponding to a particular $memconfig memory size.
#
smc_get_memory_config () {
 
    memconfig=$1    

    SMC_MEM_CONFIG=0; SMC_CONFIG=""
    smc_get_current_memconfig "$SMC_CONFIG_FILE" "$memconfig"	
    [ $? -ne 0 ] && return 4 

    [ "$SMC_CONFIG" = "small" ]  && return 1
    [ "$SMC_CONFIG" = "medium" ] && return 2
    [ "$SMC_CONFIG" = "large" ]  && return 3

    # we should not get here.
    # 
    return 4
}

# smc_get_addon_memory_config $addon_name
#
# Returns: 0  - type information missing
#	   1  - small configuration
#          2  - medium
#          3  - large
#          4  - error|unknown configuration
#
#  NOTE: This function will return the standard memory configuration
#        for the addon $addon_name (small, medium or large)
#
smc_get_addon_memory_config () {

    addon_name=$1
    SMC_CONFIG_MEMSIZE=0

    addon_cfg="${VAROPTDIR}/cfg/${addon_name}-dbase.cfg"
    SMC_CONFIG_MEMSIZE=`/usr/bin/egrep '^type=' $addon_cfg | /usr/bin/cut -f2 -d=` 

    [ -z "$SMC_CONFIG_MEMSIZE" ] && return 0
    [ "$SMC_CONFIG_MEMSIZE" = "small" ]  && return 1
    [ "$SMC_CONFIG_MEMSIZE" = "medium" ] && return 2
    [ "$SMC_CONFIG_MEMSIZE" = "large" ]  && return 3

    # we should not get here.
    # 
    return 4
}

# Oracle delivers patches in the form of tar file and certain
# Some directory / filesystem / permission related settings are
# required before applying the patch.
#
# This function calls a pre patch script which will take care of
# all such settings before applying an oracle patch.
# 
# Arguments: $1 Patch directory name
#               The function looks for prepatch.sh script in 
#               this directory and executes it before applying
#               the patch. 
#
# The function expects the script with name prepatch.sh to be 
# available in the $patch_dir
#
# The script is run as root. If something needs to be done as smcorau
# the script should take care of it.

setenv_for_oracle_patch () {
    ora_patch_dir="$1"
    patch_dir="${ORACLE_HOME}/admin/SunMC/patches/${ora_patch_dir}"
    if [ -x "$patch_dir/prepatch.sh" ]; then
        # run the script.
        /usr/bin/sh $patch_dir/prepatch.sh >> $ORA_PATCH_LOG 2>&1
    fi
}

# The function calls a patch installer script
# that runs the installer provided by oracle to apply the patch
# Arguments: $1 Patch directory name
#
# The script is run as smcorau in order to have the right env settings
# and right permissions for the source and destination files.

apply_oracle_patch () {
    ora_patch_dir="$1"

    patch_dir="${ORACLE_HOME}/admin/SunMC/patches/${ora_patch_dir}"
    patch_script="${patch_dir}/install-patch.sh"

    # come out silently in case the patch dir or the script 
    # does not exist, We don't want to add l10n msgs here.

    [ ! -x "${patch_script}" ] && return

    # now run the patch installer.
    /usr/bin/su - $SMCORAU -c "cd $patch_dir; $patch_script" >> $ORA_PATCH_LOG 2>&1
}

# This function calls a post patch script which will take care of
# any post patch processing such as running sql command etc.
# 
# Arguments: $1 Patch directory name
#               The function looks for prepatch.sh script in 
#               this directory and executes it after applying
#               the patch. 
#
# The function expects the script with name postpatch.sh to be 
# available in the $patch_dir
#
# The script is run as root. If something needs to be done as smcorau
# the script should take care of it.
#

post_oracle_patch () {
    ora_patch_dir="$1"
    patch_dir="${ORACLE_HOME}/admin/SunMC/patches/${ora_patch_dir}"
    if [ -x "$patch_dir/postpatch.sh" ]; then
        # run the script.
        cd $patch_dir
        /usr/bin/sh $patch_dir/postpatch.sh >> $ORA_PATCH_LOG 2>&1
    fi
}
# This script is called by the main es-setup of sunmc
# The script goes thru the patches directory 
# and installs each patch using the above functions
#

install_oracle_patches () {
    curr_dir=`pwd`

    ORA_PATCH_LOG="$VAROPTDIR/install/ora-patch.$$"
    $CMD_TOUCH "$ORA_PATCH_LOG"

    [ ! -d "${ORACLE_HOME}/admin/SunMC/patches/" ] && return
    cd "${ORACLE_HOME}/admin/SunMC/patches/"
    all_patches=`$CMD_LS -1`

    for each_patch in $all_patches
    do
        setenv_for_oracle_patch $each_patch
        apply_oracle_patch $each_patch
        post_oracle_patch $each_patch
    done

    cd $curr_dir
}


