#!/bin/sh
# Copyright 02/14/01 Sun Microsystems, Inc. All Rights Reserved.
#pragma ident  "@(#)es-uninst	1.65 01/02/14 Sun Microsystems"


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

remove_os_links() 
{
    links_to_delete="$1/base/bin/sparc-sun-solaris$2 $1/base/lib/sparc-sun-solaris$2 $1/base/sbin/sparc-sun-solaris$2 $1/util/bin/sparc-sun-solaris$2 $1/util/lib/sparc-sun-solaris$2 $1/util/sbin/sparc-sun-solaris$2"
    dirs_to_delete="$1/base/bin $1/base/lib $1/base/sbin $1/util/bin $1/util/lib $1/util/sbin $1/base $1/util $1"
    for each_link in $links_to_delete
    do
        if [ -h "$each_link" ] ; then
            /usr/bin/rm -f $each_link
        fi
    done
    for each_dir in $dirs_to_delete
    do
        if [ -d "$each_dir" ] ; then
            contents=`/usr/bin/ls -1 "$each_dir"`
            if [ "$contents" = "" ] ; then
                /usr/bin/rm -rf "$each_dir"
            fi
        fi
    done
}

###########################################
#
#  Main entry point
#
prog_base=`/usr/bin/basename $0`
common_cmd=`echo $0 | /usr/bin/sed s/$prog_base/es-common.sh/`
. $common_cmd
PROGNAME=$0;

# remove any crontab entry added by Sun MC
TMPCRONTAB=/tmp/crontab$$

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

# is the crontab file populated for this user?

/usr/bin/crontab -l 1>/dev/null 2>/dev/null

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

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



java_cmd=`echo $0 | /usr/bin/sed s/$prog_base/install-java.sh/`
. $java_cmd

BASEDIR=""
PRODUCTION_SYSTEM=0
set_basedir
set_db_env
/usr/bin/mkdir -p $VAROPTDIR/install/
/usr/bin/locale > $VAROPTDIR/install/env_file

check_development_env
[ $? -eq 1 ] && PRODUCTION_SYSTEM=1


echo ""
/usr/bin/gettext "       ------------------------------------ \n"
/usr/bin/gettext "       Sun Management Center Uninstallation \n"
/usr/bin/gettext "       ------------------------------------ \n"
echo ""

PKGLIST=""

#If the class for SDK packages is also symon then it will
#work good, other wise add SDK packages also into the list

PKGLIST=`/usr/bin/pkginfo -c symon | /usr/bin/awk '{print $2}'`

if [ -z "$PKGLIST" ] ; then
    /usr/bin/gettext "No Sun Management Center packages installed.\n"
    exit 1
fi

force_flag=0
stop_components=1
while getopts fF OPT
do
    case $OPT in
        f)
            force_flag=1
            ;;
        F)
            force_flag=1
            stop_components=0
            ;;
        *)
            ;;
    esac
done

check_root
check_osver
rm_options=" -n -A"
[ $OSVERS = "2.5" ] && rm_options=" -n"
set_inst_flags
keepDB="false"
# in the case of console-only uninstall, do not ask question to save data
# but clean-up /var/opt/SUNWsymon. Therefore, initialize keepVarOpt to false
keepVarOpt="false"

if [ $force_flag -eq 0 ] ; then
    echo ""
    echo ""
    /usr/bin/gettext "This utility removes all the Sun Management Center packages. \n"
    echo ""
    ask_user "      Would you like to continue?"
    do_it=$answer

    if [ $do_it -eq 0 ] ; then
        echo ""
        /usr/bin/gettext "Exiting uninstall utility.\n"
        echo ""
        /usr/bin/sleep 2
        exit 0
    fi

    if [ $no_agent -eq 0 -o $no_server -eq 0 ] ; then
        echo ""
        /usr/bin/gettext "If you are upgrading Sun Management Center, you may want to save your existing data.\n"
        preserve_data_answered=0
        while [ $preserve_data_answered -eq 0 ]; do
            echo ""
            ask_user "Do you want to preserve your existing data"
            do_it=$answer

            if [ $do_it -eq 1 ] ; then
                echo ""
                /usr/bin/gettext "Will not remove the existing data\n"
                keepDB="true"
                keepVarOpt="true"
                preserve_data_answered=1
            else
                echolog ""
                echolog 'This will remove all files under /var/opt/SUNWsymon. If you have any custom'
                echolog 'scripts under this directory, please move them to an alternate location'
                echolog 'before proceeding.'
                echo ""

                ask_user "Do you wish to continue with the removal of the existing data"
                remove_it=$answer

                if [ $remove_it -eq 0 ] ; then
                    preserve_data_answered=0
                else
                    preserve_data_answered=1
                    /usr/bin/gettext "Will remove the existing data\n"
                    keepDB="false"
                    keepVarOpt="false"
                fi
            fi
        done
    fi
fi





ADMIN=/tmp/adminfile$$
cat << !EOF > $ADMIN
mail=
instance=overwrite
partial=nocheck
runlevel=nocheck
idepend=quit
space=nocheck
setuid=nocheck
conflict=nochange
action=nocheck
basedir=default
!EOF


#
#  Issue the command to stop all Sun Management Center processes if the
#  package SUNWesagt (shared by agent and server) is installed.
#  stop_components is added to be able to uninstall SunMC even if user
#  has upgraded the OS.
#

if [ $no_agent -eq 0 -a $stop_components -eq 1 ] ; then
    echo ""
    if [ -n "$BASEDIR" ]; then
        /usr/bin/gettext "Stopping all Sun Management Center processes.  This may take a few moments...\n"
        numproc=0
        numproc=`/usr/bin/ps -aef | /usr/bin/grep "esd - init" | /usr/bin/grep -v "grep" | /usr/bin/wc -l`
        if [ $numproc -gt 0 ] ; then
            $BASEDIR/sbin/es-stop -A
        else
            if [ $no_server -eq 0 ] ; then
                #
                #Stop server
                #
                $BASEDIR/classes/base/server/bin/es-server-stop.sh


                #
                # stop database
                #
    
                lcnt=0
                scnt=0
                lcnt=`/usr/ucb/ps -ww -gax | /usr/bin/grep -i "tnslsnr smcdblistener" | /usr/bin/grep -v "grep" | /usr/bin/wc -l`
                scnt=`/usr/ucb/ps -ww -gax | /usr/bin/grep -i "ora_.*$ORACLE_SID" | /usr/bin/grep -v "grep" | /usr/bin/wc -l`

                if [ $lcnt -gt 0 -o $scnt -gt 0 ]
                then

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

                   retcode=$?

                   if [ $retcode = 2 ]
                   then
                      echolog 'the user $2 was not found by a getpwnam system call ,not in /etc/passwd, nis, nis+, etc..' "$SMCORAU"
                      echolog 'user must manually deal with user issues before continuing'
                      echolog 'cannot perform a db-stop, exiting.............................'
                      exit 1
                   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"
                      echolog 'user must manually deal with group issues before continuing'
                      echolog 'cannot perform a db-stop, exiting.............................'
                      exit 1
                   fi

                   if [ ! -f $BASEDIR/sbin/db-stop ]
                   then
                      echolog 'the $2 file does not exist, exiting..............' "$BASEDIR/sbin/db-stop"
                      exit 1
                   fi

                   su - $SMCORAU -c $BASEDIR/sbin/db-stop

                fi
 	       	  
                #
                #stop any scheduled discovery request
                #

                kill_processes "discover"
            fi
        fi
    fi
fi

#
#  If console was installed, kill any console processes
#
[ $no_console -eq 0 ] && kill_processes ConsoleMain

# it has been decided that we will never remove java installation
# at the time of SunMC uninstall. This is irrespective of whether 
# java was pre-installed on the user machine previously or was
# installed by SunMC installation. Therefore remove_java function 
# will not be called.

#
# Talked to raju and chandra about java uninstallation. Finaly
# it was decided that java installed in non default location
# will be uninstalled at the time of uninstallation. Any java
# installed or overwritten in default location by SunMC will
# not be uninstalled. 01-08-2001.
#

remove_java

[ -f "$BASEDIR/sbin/.cfginfo" ] && /usr/bin/rm -f $BASEDIR/sbin/.cfginfo
[ -f "$BASEDIR/sbin/.cfginfo.old" ] && /usr/bin/rm -f $BASEDIR/sbin/.cfginfo.old
[ -f "$BASEDIR/sbin/sqlnet.log" ] && /usr/bin/rm -f $BASEDIR/sbin/sqlnet.log

[ -f "$VARDIR/.sdklicense" ] && /usr/bin/rm -f $VARDIR/.sdklicense
[ -f "$VARDIR/.license" ] && /usr/bin/rm -f $VARDIR/.license

#
#  Get a sorted list of packages to be uninstalled.
#  Sort by reverse timestamp
#

#  Build a list of the pkginfo files for each package
INFOLIST=""
for each_pkg in $PKGLIST
do
    INFOLIST="$INFOLIST /var/sadm/pkg/$each_pkg/pkginfo"
done

#  Sort the file list using ls -t
SORTEDLIST=`/usr/bin/ls -t $INFOLIST`

#  Turn the file list back into a package list
PKGLIST=""
for each_file in $SORTEDLIST
do
    pkgname=`echo $each_file | /usr/bin/cut -f5 -d\/`
    PKGLIST="$PKGLIST $pkgname"
done

PKGS_FAILED=""


#
#  cleanup oracle build related files in /tmp 
#

if [ -x $BASEDIR/db/build/cleanup-tmp.sh ]
then
  $BASEDIR/db/build/cleanup-tmp.sh
  /usr/bin/rm -f $BASEDIR/db/build/cleanup-tmp.sh
fi


cd /

orabasedir=""
tblbasedir=""

for each_pkg in $PKGLIST
do
    /usr/bin/pkginfo -q $each_pkg
    if [ $? -eq 0 ] ; then
       uninst_flag=1
      
       if [ "$each_pkg" != "SUNWestbl" ]; then
          if [ "$each_pkg" = "SUNWesora" ]; then
             orabasedir=`/usr/bin/pkgparam -f /var/sadm/pkg/SUNWesora/pkginfo BASEDIR`
      
             get_dependent_pkgs "SUNWesora"
             if [ -z "$dependent_pkgs" ] ; then
                uninst_flag=1
             else
                echolog 'Some packages installed on your system are dependent on SUNWesora.'
                echolog 'Preserving SUNWesora package...'
                SUNWesora_preserved=1
                uninst_flag=0
             fi
          fi
         
          if [ "$uninst_flag" = "1" ]; then
             echolog ""
             echolog 'Removing $2' "$each_pkg"
             echolog ""
             /usr/sbin/pkgrm $rm_options -a $ADMIN $each_pkg
             retcode=$?
             if [ $retcode -ne 0 ] ; then
                echolog 'Package Removal: Failed for $2' "$each_pkg"
                PKGS_FAILED="$PKGS_FAILED $each_pkg"
             fi
          fi
      else
         if [ "$keepDB" != "true" ]; then
            if [ $each_pkg = "SUNWestbl" ]; then
               tblbasedir=`/usr/bin/pkgparam -f /var/sadm/pkg/SUNWestbl/pkginfo BASEDIR`
            fi
            echo ""
            echolog 'Removing $2' "$each_pkg"
            echo ""
            /usr/sbin/pkgrm $rm_options -a $ADMIN $each_pkg
            retcode=$?
            if [ $retcode -ne 0 ] ; then
               echolog 'Package Removal: Failed for $2' "$each_pkg"
               PKGS_FAILED="$PKGS_FAILED $each_pkg"
            fi
         fi
      fi
   fi
done

CANNOT_REMOVE=""

if [ "$PKGS_FAILED" != "" ] ; then
    echo ""
    echolog 'Reattempting to uninstall the package\\\(s\\\): $2' "$PKGS_FAILED"
    echo ""
    for each_pkg in $PKGS_FAILED
    do
        /usr/sbin/pkgrm $rm_options -a $ADMIN $each_pkg
        return_val=$?
        if [ $return_val -ne 0 ] ; then
            CANNOT_REMOVE="$CANNOT_REMOVE $each_pkg"
        fi
    done
fi


if [ "$CANNOT_REMOVE" != "" ] ; then
    echo ""
    echolog 'Please remove the following packages manually.'
    echo "        $CANNOT_REMOVE"
    echo ""
fi




#
#  Ensure we cleanup any oracle related sql and log files
#  used by the smcorau user
#

if [ -f /tmp/db-start.sql ]
then
  /usr/bin/rm -f /tmp/db-start.sql
fi

if [ -f /tmp/db-start.log ]
then
  /usr/bin/rm -f /tmp/db-start.log
fi

if [ -f /tmp/db-start-sql.log ]
then
  /usr/bin/rm -f /tmp/db-start-sql.log
fi

if [ -f /tmp/db-start-sh.log ]
then
  /usr/bin/rm -f /tmp/db-start-sh.log
fi

if [ -f /tmp/db-start-vinst.sql ]
then
  /usr/bin/rm -f /tmp/db-start-vinst.sql
fi

if [ -f /tmp/db-start-vinst.log ]
then
  /usr/bin/rm -f /tmp/db-start-vinst.log
fi

if [ -f /tmp/db-stop.log ]
then
  /usr/bin/rm -f /tmp/db-stop.log
fi

if [ -f /tmp/db-stop-sql.log ]
then
  /usr/bin/rm -f /tmp/db-stop-sql.log
fi

if [ -f /tmp/db-charset-utf8.log ]
then
  /usr/bin/rm -f /tmp/db-charset-utf8.log
fi

if [ -f /tmp/db-charset-utf8.sql ]
then
  /usr/bin/rm -f /tmp/db-charset-utf8.sql
fi

if [ -f /tmp/db-charset-utf8-sql.log ]
then
  /usr/bin/rm -f /tmp/db-charset-utf8-sql.log
fi


if [ -f /tmp/make.log ]
then
  /usr/bin/rm -f /tmp/make.log
fi

if [ -f /tmp/system ]
then
  /usr/bin/rm -f /tmp/system
fi

if [ -f /tmp/smcdb_db* ]
then
  /usr/bin/rm -f /tmp/smcdb_db*
fi

if [ -d /tmp/sunmclog ]         
then                             
  /usr/bin/rm -rf /tmp/sunmclog
fi                               
                                 


if [ "$keepDB" != "true" -a "$CANNOT_REMOVE" = "" ]
then

    ORATABLOC=/var/opt/oracle
    ORATAB=${ORATABLOC}/oratab
    TMPORATB=/var/tmp/oratab$$ 

    if [ -f ${TMPORATB} ]; then
        /usr/bin/rm -f ${TMPORATB} 2>/dev/null
    fi

    #
    # Make sure an oratab file exists on this system
    #

    if [ -s ${ORATAB} ];then
        /usr/bin/chown $ORACLE_OWNER ${ORATAB}
        /usr/bin/chmod 664 ${ORATAB}

        #
        # If an entry exists in $ORATAB for this $ORACLE_HOME, delete it 
        #

        FOUND_OLD=`/usr/bin/grep "^[^#]*:${ORACLE_HOME}:" ${ORATAB}`

        if [ -n "${FOUND_OLD}" ];then

            # if removal of SunMC entry from the oratab file will make it empty,
            # then remove the oratab file itself

			oratab_cnt=`/usr/bin/cat ${ORATAB} | /usr/bin/grep -v "^[^#]*:${ORACLE_HOME}:" | /usr/bin/grep -v "^[#]"`
            if [ -z "$oratab_cnt" ]; then
                /usr/bin/rm -f ${ORATAB} 2>/dev/null
                if [ -d "$ORATABLOC" ]
                then
                    oracle_cnt=`/usr/bin/ls -1 "$ORATABLOC"|/usr/bin/wc -l`
                    if [ $oracle_cnt -eq 0 ] ; then
                        /usr/bin/rm -rf $ORATABLOC 2>/dev/null
                    fi
                fi
            else
                /usr/bin/cat ${ORATAB} | /usr/bin/grep -v "^[^#]*:${ORACLE_HOME}:" | /usr/bin/grep -v "^[#]" > $TMPORATB
                /usr/bin/cat $TMPORATB > $ORATAB
                /usr/bin/rm -f $TMPORATB 2>/dev/null
            fi
        fi 
    fi


	# if SUNWestbl package is installed in a different location
	# then clean that up as well

    if [ -n "$tblbasedir" -a -d $tblbasedir/SUNWsymon ]; then
        /usr/bin/rm -rf $tblbasedir/SUNWsymon/SunMCDB02 >/dev/null 2>&1
	fi

    #
    #
    #  Delete Oracle Admin User and Group
    #
    #

     verifyDeleteOracleUser $SMCORAU

     retcode=$?

     if [ $retcode != 0 ]
     then
        echolog "execution of verifyDeleteOracleUser failed, exiting............."
        exit 1
     fi

     groupid=""

     verifyDeleteOracleGroup $SMCORAG

     retcode=$?

     if [ $retcode != 0 ]
     then
        echolog "execution of verifyDeleteOracleGroup failed, exiting............."
        exit 1
     fi

fi

if [ "$keepVarOpt" != "true" -a "$CANNOT_REMOVE" = "" ]
then
    if [ -h $VAROPTDIR/SunMCDB02 ]; then
        /usr/bin/rm -rf $VAROPTDIR/SunMCDB02 >/dev/null 2>&1
    fi

    if [ -d $VAROPTDIR ]; then
        /usr/bin/rm -rf $VAROPTDIR >/dev/null 2>&1
    fi
fi

#
#  Cleanup some dynamically created stuff
#

if [ -n "$orabasedir" -a -d $orabasedir/SUNWsymon/SunMCDB01 ]; then
  /usr/bin/rm -rf $orabasedir/SUNWsymon/SunMCDB01 >/dev/null 2>&1
fi

if [ -n "$orabasedir" -a -d $orabasedir/SUNWsymon/db ]; then
  /usr/bin/rm -rf $orabasedir/SUNWsymon/db >/dev/null 2>&1
fi

if [ -f $ADMIN ]
then
  /usr/bin/rm -f $ADMIN
fi


#Remove all the console banner related file which were copied
#at install time. This is only for development system
if [ $PRODUCTION_SYSTEM -eq 0 ] ; then
    if [ -f "$VARDIR/base-consoles_3_0_00_00-j.x" ] ; then
       /usr/bin/rm -f $VARDIR/base-consoles_3_0_00_00-j.x >/dev/null 2>&1
    fi
fi

if [ "$SUNWesora_preserved" = "1" ]; then
   echolog ''
   echolog 'Following packages are dependent on SUNWesora:$2' "$dependent_pkgs"
   echolog 'SUNWesora package preserved because these package level dependencies.'
   echolog 'Please remove this package manually if required.'
fi 


#
# This is for supporting Solaris 8 bits on Solaris 9. All the symolic links
# created at the time of setup, should be deleted here.
#
if [ "$CANNOT_REMOVE" = "" ] ; then
    remove_os_links "$BASEDIR" "$OSVERS"
fi

echo ""
echolog 'Sun Management Center uninstall complete.'
echo ""
exit 0
