#!/bin/sh

# rootdelete.sbs for CRS
#
# This script is run once per CRS_HOME during the de-install or delete node 
# operation. It needs to remove inittab entries, stop the CRS stack, 
# and delete CRS files from $ID and $RCALLDIR.
#
# USAGE: rootdelete.sh [-paramfile <complete path of parameter file>] 
#           [local|remote] [sharedvar|nosharedvar] [shardhome|nosharedhome]
#           [-downgrade [-version <version to downgrade>]] [-force]
# local/remote: Use 'local', if it is run on local node. Otherwise use "remote"
#               Default: local
#               NOTE: A node is a local node if you will be running 
#                     OUI from that.
#
# nosharedvar/sharedvar: Use 'sharedvar', if directory path of ocr.loc is 
#                        shared across cluster nodes. 
#                        Otherwise use "nosharedvar".
#                        Default: nosharedvar
#
# sharedhome/nosharedhome: Use 'sharedhome', if CRS home is shared across 
#                          cluster nodes. 
#                          Otherwise, use 'nosharedhome'.
#                          Default: sharedhome

ORA_CRS_HOME=%ORA_CRS_HOME%
ORACLE_OWNER=%OwnerId%
DBA_GROUP=%s_usergroup%

usage()
{
   printf "Usage: "
   printf "rootdelete [-help] [-paramfile <complete path of parameter file>]"
   printf "           [local|remote] [nosharedvar|sharedvar] "
   printf "           [sharedhome|nosharedhome] "
   printf "           [-downgrade [-version <version>]] [-force]\n"
   printf "\-help: print this message\n"
   printf "\-paramfile <Complete path of parameter file\n"
   printf "local: Use this option if OUI will be run on this node to remove "
   printf "       software, otherwise use 'remote'\n"
   printf "sharedvar: Use this option if OCR is on a shared path"
   printf "           otherwise use 'nosharedvar'\n"
   printf "sharedhome: Use this option if CRS home is on a shared path"
   printf "            otherwise use 'nosharedhome'\n"
   printf "\-downgrade: Use this option if database is downgraded to previous"
   printf "            version of Oracle clusterware or RAC database"
   printf "\-version <version>: Use this option to specify version "
   printf "       (default: 10.2). Use this option with -downgrade option\n"
   printf "\-force : Force the cleanup of root configuration\n"
}

USER_ARGS=$*

LOCALNODE="local"
SHAREDVAR="nosharedvar"
SHAREDHOME="sharedhome"
DOWNGRADE=false
VERSION="10.2"
USE_FORCE=false
USE_PARAM_FILE=false
THIS_NODE=
OCW_NODES=

CH=$ORA_CRS_HOME
ORACLE_HOME=$ORA_CRS_HOME
export ORA_CRS_HOME
export ORACLE_HOME
CRSCTL=$CH/bin/crsctl

if [ -z "$CP" ]; then CP=/bin/cp; fi
if [ -z "$ECHO" ]; then ECHO=/bin/echo; fi
if [ -z "$SLEEP" ]; then SLEEP=/bin/sleep; fi
if [ -z "$CHOWN" ]; then CHOWN=/bin/chown; fi
if [ -z "$CHGRP" ]; then CHGRP=/bin/chgrp; fi
if [ -z "$CHMOD" ]; then CHMOD=/bin/chmod; fi
if [ -z "$PING" ]; then PING=/bin/ping; fi
if [ -z "$RM" ]; then RM=/bin/rm; fi
if [ -z "$RMF" ]; then RMF="/bin/rm -f"; fi
if [ -z "$CAT" ]; then CAT=/bin/cat; fi
if [ -z "$GREP" ]; then GREP=/bin/grep; fi
if [ -z "$AWK" ]; then AWK=/bin/awk; fi
if [ -z "$IDCMD" ]; then IDCMD=/usr/bin/id; fi
if [ -z "$WC" ]; then WC=/usr/bin/wc; fi
if [ -z "$HOSTN" ]; then HOSTN=/bin/hostname; fi
if [ -z "$CUT" ]; then CUT=/usr/bin/cut; fi
if [ -z "$EXPRN" ]; then EXPRN=/usr/bin/expr; fi
if [ -z "$LS1" ]; then LS1="/bin/ls -1"; fi
if [ -z "$WCL" ]; then WCL="/usr/bin/wc -l"; fi
if [ -z "$RMRF" ]; then RMRF="/bin/rm -rf"; fi
if [ -z "$IFCONFIG" ]; then IFCONFIG="/sbin/ifconfig"; fi

# Needs to print out (at least) the basename of all processes on the box
if [ -z "$PSE" ]; then PSE="/bin/ps -e"; fi

##Function for parsing the command line arguments
parseArgs()
{
   USER_ARGS=$*

   if [ $# -gt 9 ]; then
     usage;
     return 1;
   fi

   if [ $# -gt 0 ];
   then
     if [ $1 = "-help" ];
     then
       usage;
       return 1;
     fi
   fi
 
   while [ $# -gt 0 ];
   do
     if [ $1 = "-paramfile" ]; then
       USE_PARAM_FILE=true
       if [ $# -ge 2 ]; then
         PARAM_VALUE_FILE=$2;
         shift;
       else
         usage;
         return 2;
       fi
     elif [ $1 = "local" -o $1 = "remote" ]; then
       LOCALNODE=$1
     elif [ $1 = "nosharedvar" -o $1 = "sharedvar" ]; then
       SHAREDVAR=$1
     elif [ $1 = "sharedhome" -o $1 = "nosharedhome" ]; then
       SHAREDHOME=$1
     elif [ $1 = "-downgrade" ]; then
       DOWNGRADE=true
       if [ $# -ge 2 ]; then
         if [ $2 = "-version" ]; then
           if [ $# -ge 3 ]; then
             VERSION=$3
             shift;
             if [ "$VERSION" != "10.2" -a "$VERSION" != "10.1" -a "$VERSION" != "9.2" ]; then
                $ECHO "Wrong version ($VERSION) number specified as an input"
                $ECHO "You can  downgrade cluster repository to either 10.2, 10.1 or 9.2 versions"
	        return 1;
             fi
           else
             $ECHO "Specify a target version number for downgrade"
             usage;
             return 2;
           fi
           shift;
         fi
       fi
     elif [ $1 = "-force" ]; then
       USE_FORCE=true
     else
       usage;
       return 2;
     fi
     shift;
   done;

   return 0;
}

##Function for reading CRS parameters from the given param file
readparamfile()
{
  $ECHO "Reading $PARAM_VALUE_FILE.."
  ## Make sure that this input file has only "LHS=RHS" and empty lines
  ## Any other lines will be considered improper input for root script
  awkOutput=`$AWK 'BEGIN { Ni=0 } \
                     /^#/   { next } \
                     /[A-Z]\=\`*\`/ { printf("\"%s\"\n", $0); next } \
                     /[A-Z_]\=/ { next } \
                     /^$/   { next } \
                            { printf("\"%s\"\n", $0); next }' $PARAM_VALUE_FILE`

  if [ "x$awkOutput" != "x" ]; then
     $ECHO "The following unexpected input found in CRS parameter file: $awkOutput"
     exit 1
  fi

  . $PARAM_VALUE_FILE

  $ECHO "File ($PARAM_VALUE_FILE) is used for setting CRS variables."
  $ECHO "ORA_CRS_HOME=$ORA_CRS_HOME"
  $ECHO "ORACLE_OWNER=$ORACLE_OWNER"
  $ECHO "DBA_GROUP=$DBA_GROUP"
}

validate_var()
{
   PARAM_NAME=$1
   valid=`$ECHO $PARAM_NAME | $AWK '/^%/ { print "false"; }'`
   if [ "$valid" = "false" ];
   then
     return 1;
   fi

   return 0;
}

if [ -z "$TR" ]; then TR=/bin/tr;fi
#solaris on amd and SPARC has issue with /bin/tr
[ 'SunOS' = `/bin/uname` ] && TR=/usr/xpg4/bin/tr 
#on linux tr is at /usr/bin/tr
[ 'Linux' = `/bin/uname` ] && TR=/usr/bin/tr

resetOCR()
{
   $ECHO "Updating ocr file for downgrade"

   if $DOWNGRADE;
   then
     if [ "$VERSION" = "9.2" ]; then

      #Check existence of srvConfig.loc
      if [ -f "$SRVCONFIG" ];
      then
         #CASE 1:srvConfig.loc does exist. So lets see the OCR location
         SRV_OCRLOC=`$AWK -F= '/srvconfig_loc/ {print $2}' < $SRVCONFIG`
         OCRLOC=`$AWK -F= '/ocrconfig_loc/ {print $2}' < $OCRCONFIG`

         #CASE 1.1: srvconfig_loc = /dev/null
         if [ "$SRV_OCRLOC" = "/dev/null" ];
         then
            # srvConfig.loc has /dev/null that was invalidated during 10g install
	    # Copying the location from ocr.loc to srvConfig.loc for downgrade
            $ECHO srvconfig_loc=$OCRLOC > $SRVCONFIG 

         elif [ "$SRV_OCRLOC" != "$OCRLOC" ];
         then
            #CASE 1.2: srvconfig_loc!=ocrconfig_loc
            #OCR device in ocr.loc will be wiped out next
	    $ECHO ""
            # fix up permissions on SRV_OCRLOC below
            OCRLOC=$SRV_OCRLOC
         else
           #CASE 1.3: srvconfig_loc = ocrconfig_loc
	   #do nothing
	   $ECHO ""
         fi
      fi
      # ensure 9i GSD can read/write 9i OCR
      if $validOwner;
      then
         $CHOWN $ORACLE_OWNER $OCRLOC
      fi
      if $validGrp;
      then
         $CHOWN $DBA_GROUP $OCRLOC
      fi
      $CHMOD 644 $OCRLOC

      # if local, preserve ocr.loc file for later rootdeinstall -downgrade
      if [ "$LOCALNODE" = "remote" ];
      then
       if [ -f $OCRCONFIG ];
       then
          if [ -d /tmp/install ];
	  then
	     $CP $OCRCONFIG /tmp/install
	  fi

          $RM $OCRCONFIG
       fi
      fi
     else
      #ocr.loc will be preserved for downgrading to 10.1
      $ECHO ""
     fi
   else
     if [ "$LOCALNODE" = "remote" ];
     then
      if [ -f $OCRCONFIG ];
      then
         if [ -d /tmp/install ];
	 then
	    $CP $OCRCONFIG /tmp/install
	 fi

         $RM $OCRCONFIG
      fi
     fi
   fi

   if [ -d $OCRCONFIGDIR ];
   then
     #Reset the permissions of OCRCONFIGDIR
     if [ ! -z "$ORACLE_OWNER" ];
     then

         validVar=true
	 validate_var $ORACLE_OWNER || { validVar=false; }

	 if $validVar;
	 then
            $CHOWN $ORACLE_OWNER $OCRCONFIGDIR
	 fi
     fi

     if [ ! -z "$DBA_GROUP" ];
     then
	 if $validGrp;
	 then
             $CHGRP $DBA_GROUP $OCRCONFIGDIR
	 fi
     fi

     $CHMOD 755 $OCRCONFIGDIR 
   fi

   return 0
}

isOCRFileExists()
{
   $ECHO "Retrieving OCR file path"

   if [ ! -f $OCRCONFIG ];
   then
      return 1
   fi

   OCRLOC=`$AWK -F= '/ocrconfig_loc/ {print $2}' < $OCRCONFIG`
   OCRMIRRORLOC=`$AWK -F= '/ocrmirrorconfig_loc/ {print $2}' < $OCRCONFIG`

   if [ ! -z "$OCRLOC" ];
   then
      if [ -b "$OCRLOC" ] || [ -c "$OCRLOC" ] || [ -f "$OCRLOC" ];
      then
         status=0;
      else
         status=1;
      fi
   elif [ ! -z "$OCRMIRRORLOC" ];
   then
      if [ -b "$OCRMIRRORLOC" ] || [ -c "$OCRMIRRORLOC" ] || [ -f "$OCRMIRRORLOC" ];
      then
         status=0;
      else
         status=1;
      fi
   fi

   return $status
}

getLocalNode()
{
   $ECHO "Getting local node name"
   THIS_NODE=""
   if [ -f $ORA_CRS_HOME/bin/olsnodes ];
   then
      THIS_NODE=`$ORA_CRS_HOME/bin/olsnodes -l`
      status=$?
      if [ $status != 0 ];
      then
         THIS_NODE=`$HOSTN`
      fi
   else
      THIS_NODE=`$HOSTN`
   fi

   $ECHO "NODE = $THIS_NODE"
}

getClusterNodes()
{
   $ECHO "Getting cluster node names"
   if [ -f $ORA_CRS_HOME/bin/olsnodes ];
   then
      OCW_NODES=`$ORA_CRS_HOME/bin/olsnodes`
      status=$?
      if [ $status != 0 ];
      then
         OCW_NODES=""
      fi
   fi

   if [ -z "$OCW_NODES" ];
   then
      ## extract node names from node1,node1-number,node2,node2-number,...
      NODES_LIST=`$ECHO $CLUSTER_NODES | $AWK '{
	nElems = split($1, nodeList, ",");
	for (i = 1; i <= nElems;)
	{
	    print nodeList[i];
	    i ++;
	}
      }'`

      OCW_NODES=$NODES_LIST
   fi

   $ECHO "Cluster Nodes = $OCW_NODES"
}

verifyCRSResources()
{
  VIP_SUFFIX=".vip"
  GSD_SUFFIX=".gsd"
  ONS_SUFFIX=".ons"
  LSNR_SUFFIX=".lsnr"
  DB_SUFFIX=".db"
  
  ##if CRS stack is up and running
  if $ORA_CRS_HOME/bin/crs_stat > /dev/null 2>&1
  then
     getLocalNode
     NODE_NAME=$THIS_NODE

     ### dependent resources other than VIP, GSD, and ONS
     DEP_RES=`$ORA_CRS_HOME/bin/crs_stat -l | $AWK '/NAME=/ {print $0}' | $GREP -v $VIP_SUFFIX | $GREP -v $GSD_SUFFIX | $GREP -v $ONS_SUFFIX`

     ##Node specific Listener resources
     LSNR_RES=`$ORA_CRS_HOME/bin/crs_stat -l | $AWK '/NAME=/ {print $0}' | $GREP $NODE_NAME | $GREP $LSNR_SUFFIX`

     ##The database resources
     DB_RES=`$ORA_CRS_HOME/bin/crs_stat -l | $AWK '/NAME=/ {print $0}' | $GREP $DB_SUFFIX | $AWK -F'.' '{print $2}'`

     if [ ! -z "$DEP_RES" ];
     then
       for i in `$ECHO $DB_RES`
       do
         ##Find the database instances configured to run on this node
         INSTS=`$ORA_CRS_HOME/bin/srvctl config database -d $i | $AWK "/^$NODE_NAME / { print \\$2 }"`
         if [ ! -z "$INSTS" ];
         then
           for j in `$ECHO $INSTS`
	   do
	     INST_RES="ora.$i.$j.inst"
	     if $ORA_CRS_HOME/bin/crs_stat $INST_RES;
	     then
	       $ECHO "The database instance is still configured on this node."
	       if [ "$USE_FORCE" != "true" ];
	       then
                 $ECHO "Delete the database instance using DBCA before preparing to deconfigure CRS stack on this node."
		 return 1
	       fi
	     fi
	   done
         fi
       done

       if [ ! -z "$LSNR_RES" ]; then
         $ECHO "CRS resources for listeners are still configured."
	 if [ "$USE_FORCE" != "true" ];
	 then
           $ECHO "You must remove the CRS listener resources before deconfiging CRS stack. Use NETCA to remove them."
           return 1
	 fi
       fi
     fi
  fi

  return 0
}

removeNodeApps()
{
   getLocalNode
   NODE_NAME=$THIS_NODE

   if [ -f $ORA_CRS_HOME/bin/srvctl ];
   then
     NODE_VIP_STRING=`$ORA_CRS_HOME/bin/srvctl config nodeapps -n $NODE_NAME -a`
     $ORA_CRS_HOME/bin/srvctl stop nodeapps -n $NODE_NAME
     $ECHO y | $ORA_CRS_HOME/bin/srvctl remove nodeapps -n $NODE_NAME > /dev/null
     STATUS=$?
   else
     STATUS=-1
   fi

   if [ "$STATUS" != "0" ];then
      if $USE_FORCE;
      then
         if [ ! -z "$NODE_VIP_STRING" ];
         then

            NODE_VIP=`$ECHO $NODE_VIP_STRING | $AWK -F"/" '{ print $3 }'`
	    NODE_IF=`$ECHO $NODE_VIP_STRING | $AWK -F"/" '{ print $5 }'`
	    NODE_MASK=`$ECHO $NODE_VIP_STRING | $AWK -F"/" '{ print $4 }'`
	 fi

	 NODE_UPCASE=`$ECHO $NODE_NAME | $AWK '{ print toupper($1) }'`

	 if [ -z "$NODE_VIP" ];
	 then
	    PARAM_NAME=VIP_`$ECHO $NODE_UPCASE`_IP
	    NODE_VIP=`eval echo \\$$PARAM_NAME`
	 fi

	 if [ -z "$NODE_MASK" ];
	 then
	    PARAM_NAME=VIP_`$ECHO $NODE_UPCASE`_MASK
	    NODE_MASK=`eval echo \\$$PARAM_NAME`
	 fi

	 if [ -z "$NODE_IF" ];
	 then
	    PARAM_NAME=VIP_`$ECHO $NODE_UPCASE`_IF
	    NODE_IF=`eval echo \\$$PARAM_NAME`
	 fi

         if [ ! -z "$NODE_VIP" ]; then
	    $PING -c 5 $NODE_VIP > /dev/null
	    STATUS=$?
	    if [ "$STATUS" = "0" ]; then
		export _USR_ORA_VIP=$NODE_VIP
		export _USR_ORA_NETMASK=$NODE_MASK
		export _USR_ORA_IF=$NODE_IF
		if [ -f $ORA_CRS_HOME/bin/racgvip ];
		then
		    $ORA_CRS_HOME/bin/racgvip stop ora.$NODE_NAME.vip > /dev/null
		else
		    if [ ! -z $NODE_IF ];
		    then
			$ECHO "Stopping Virtual IP configured on this node"
		    fi
		fi
	    fi
	 fi
      else
         return 1
      fi
   fi

   return 0
}

isExistsOCWProcess()
{
   # Changes for bug 7551160
   if [ $PLATFORM = "SunOS" -a $MAJOROS -ge 5 -a $MINOROS -ge 10 -a -f $ZONENAME ]; then
      $PS -z `$ZONENAME` | $GREP -i 'oc[s]sd' > /tmp/ocssd.ps
      $PS -z `$ZONENAME` | $GREP -i 'cr[s]d.bin' > /tmp/crsd.ps
      $PS -z `$ZONENAME` | $GREP -i 'ev[m]d.bin' > /tmp/evmd.ps
   else
      $PSE | $GREP -i 'oc[s]sd' > /tmp/ocssd.ps
      $PSE | $GREP -i 'cr[s]d.bin' > /tmp/crsd.ps
      $PSE | $GREP -i 'ev[m]d.bin' > /tmp/evmd.ps
   fi
   PROCS=`$CAT /tmp/ocssd.ps /tmp/crsd.ps /tmp/evmd.ps`
   if [ ! -z "$PROCS" ]; then
    $RMF /tmp/ocssd.ps /tmp/crsd.ps /tmp/evmd.ps 
    return 1
   else
    $RMF /tmp/ocssd.ps /tmp/crsd.ps /tmp/evmd.ps
    return 0
   fi
}

NSReset()
{
  $ECHO "Cleaning up Network socket directories"

  for dir in /var/tmp/.oracle /tmp/.oracle
  do
    if [  -d $dir ];
    then
      $RMF $dir/*CSS*
      $RMF $dir/*CRS*
      $RMF $dir/*EVM*
      $RMF $dir/*PROC*
      $RMF $dir/*css*
      $RMF $dir/*crs*
      $RMF $dir/*evm*
      $RMF $dir/*proc*

      NoFiles=`$LS1 $dir | $WCL | $AWK '{print $1}'`
      if [ "$NoFiles" = "0" ];
      then
  	  $RMRF $dir
      fi
    fi
  done

  return 0;
}

stopVIP()
{
   getClusterNodes
   NODE_NAMES=$OCW_NODES

   for i in `$ECHO $NODE_NAMES`;
   do
      $ECHO "Stopping vip"

      NODE_UPCASE=`$ECHO $i | $AWK '{ print toupper($1) }'`

      PARAM_NAME=VIP_`$ECHO $NODE_UPCASE`_IP
      NODE_VIP=`eval echo \\$$PARAM_NAME`

      PARAM_NAME=VIP_`$ECHO $NODE_UPCASE`_MASK
      NODE_MASK=`eval echo \\$$PARAM_NAME`

      PARAM_NAME=VIP_`$ECHO $NODE_UPCASE`_IF
      NODE_IF=`eval echo \\$$PARAM_NAME`

      if [ ! -z "$NODE_VIP" ]; then
	 $PING -c 1 $NODE_VIP > /dev/null
	 STATUS=$?
	 if [ "$STATUS" = "0" ]; then

           VIPAddress=$NODE_VIP
           Interface=$NODE_IF

           if [ -f $IFCONFIG ];
           then
              IFs=`$IFCONFIG -a | grep $Interface | $AWK '{ print $1 }'`
              for i in `$ECHO $IFs`
              do
                 $IFCONFIG -a $i | $GREP $VIPAddress
                 status=$?
	         if [ "$status" = "0" ];
	         then
	            IPInterface=$i
	            break
	         fi
              done

              if [ ! -z "$IPInterface" ];
              then
                $ECHO "Removing $VIPAddress from interface $Interface"
	        $IFCONFIG $IPInterface del $VIPAddress
	        status=$?
	        if [ "$status" = "0" ];
	        then
	           $ECHO "The IP address $VIPAddress is now successfully removed from interface $interface"
	        fi
              fi
           fi
         fi
      fi
   done
}

# This script is intended to be run by root.

RUID=`$IDCMD|$AWK -F\( '{print $2}'|$AWK -F\) '{print $1}'`
if [ ${RUID} != "root" ];then
  $ECHO "You must be logged in as root to run $0."
  $ECHO "Log in as root and restart $0 execution."
  exit 1
fi

####Parsing command line arguments
parseArgs $* || { $ECHO $?; exit 1;}

if $USE_PARAM_FILE;
then
  if [ ! -f "$PARAM_VALUE_FILE" ]; then
     $ECHO "The input file($PARAM_VALUE_FILE) specifying the parameter values for CRS variables is not found"
     exit 1
  fi

  ###Read CRS parameter values from param file
  readparamfile
fi

validOwner=true
if $USE_FORCE;
then
  validate_var $ORACLE_OWNER || { validOwner=false; }
fi

validGrp=true
if $USE_FORCE;
then
  validate_var $DBA_GROUP || { validGrp=false; }
fi

#convert host name to lower case
#If the hostname is an IP address, let hostname
#remain as IP address
HOST=`$HOSTN`
len1=`$EXPRN "$HOST" : '.*'`
len2=`$EXPRN match $HOST '[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*'`
                                                                                
# Strip off domain name in case /bin/hostname returns
# FQDN hostname
if [ $len1 != $len2 ]; then
 HOST=`$ECHO $HOST | cut -d'.' -f1`
fi

HOST=`$ECHO $HOST | $TR '[:upper:]' '[:lower:]'`

# Definition to Remove inittab entries
RMITAB="$CAT \$IT | $GREP -v init.evmd | $GREP -v init.cssd | $GREP -v init.crsd > \$IT.no_crs || { $ECHO $?; exit 1; } ; \
        $CP \$IT.no_crs \$IT || { $ECHO $?; exit 1; }"

UNAME=/bin/uname
PLATFORM=`$UNAME`

case $PLATFORM in
Linux) 
       ID=/etc/init.d
       RCALLDIR="/etc/rc.d/rc0.d /etc/rc.d/rc1.d /etc/rc.d/rc2.d /etc/rc.d/rc3.d /etc/rc.d/rc4.d /etc/rc.d/rc5.d /etc/rc.d/rc6.d"
       RC_START=S96
       RC_KILL=K19
       RC_KILL_OLD=K96       
       IT=/etc/inittab
       INIT=/sbin/init
       OCRCONFIGDIR=/etc/oracle
       OCRCONFIG=/etc/oracle/ocr.loc
       SRVCONFIG=/var/opt/oracle/srvConfig.loc
       SCR_BASE=/etc/oracle/scls_scr
       NETWORK_DIR=/var/tmp/.oracle
       OPROCDDIR=/etc/oracle/oprocd
       ;;
HP-UX) 
       ID=/sbin/init.d
       RCALLDIR="/sbin/rc2.d /sbin/rc3.d"
       RC_START=S960
       RC_KILL=K190
       RC_KILL_OLD=K001       
       IT=/etc/inittab
       INIT=/sbin/init
       OCRCONFIGDIR=/var/opt/oracle
       SRVCONFIG=/var/opt/oracle/srvConfig.loc
       OCRCONFIG=/var/opt/oracle/ocr.loc
       SCR_BASE=/var/opt/oracle/scls_scr
       NETWORK_DIR=/tmp/.oracle
       OPROCDDIR=/var/opt/oracle/oprocd
       ;;
SunOS) 
       ID=/etc/init.d
       RCALLDIR="/etc/rc0.d /etc/rc1.d /etc/rc2.d /etc/rc3.d /etc/rcS.d"
       RC_START=S96
       RC_KILL=K19
       RC_KILL_OLD=K96       
       IT=/etc/inittab  
       INIT=/sbin/init
       OCRCONFIGDIR=/var/opt/oracle
       SRVCONFIG=/var/opt/oracle/srvConfig.loc
       OCRCONFIG=/var/opt/oracle/ocr.loc
       SCR_BASE=/var/opt/oracle/scls_scr
       NETWORK_DIR=/var/tmp/.oracle
       OPROCDDIR=/var/opt/oracle/oprocd
       # Changes for bug 7551160
       PS="/bin/ps"
       ZONENAME="/bin/zonename"
       MAJOROS=`$UNAME -r | $AWK -F. '{print $1}'`
       MINOROS=`$UNAME -r | $AWK -F. '{print $2}'`
       ;;
AIX)   
       ID=/etc
       RCALLDIR="/etc/rc.d/rc2.d"
       RC_START=S96
       RC_KILL=K19
       RC_KILL_OLD=K96       
       IT=/etc/inittab
       INIT=/usr/sbin/init
       RMITAB="while read line; \
                do \
                identifier=\`echo \$line | $CUT -d ':' -f 1\`; \
                rmitab \$identifier 2>/dev/null; \
                done < $CH/crs/admin/inittab"
       OCRCONFIGDIR=/etc/oracle
       SRVCONFIG=/var/opt/oracle/srvConfig.loc
       OCRCONFIG=/etc/oracle/ocr.loc
       SCR_BASE=/etc/oracle/scls_scr
       NETWORK_DIR=/tmp/.oracle
       OPROCDDIR=/etc/oracle/oprocd
       ;;
OSF1)  
       ID=/sbin/init.d
       RCALLDIR="/sbin/rc3.d"
       RC_START=S96
       RC_KILL=K19
       RC_KILL_OLD=K96       
       IT=/etc/inittab
       INIT=/sbin/init
       OCRCONFIGDIR=/var/opt/oracle
       SRVCONFIG=/var/opt/oracle/srvConfig.loc
       OCRCONFIG=/var/opt/oracle/ocr.loc
       SCR_BASE=/var/opt/oracle/scls_scr
       NETWORK_DIR=/tmp/.oracle
       OPROCDDIR=/var/opt/oracle/oprocd
       ;;
*)     /bin/echo "ERROR: Unknown Operating System"
       exit -1
       ;;
esac

if [ "$DOWNGRADE" != "true" ];
then
  #########################################
  #STEP0: remove CRS nodeapps for this node
  ##########################################
  verifyCRSResources || { $ECHO $?; exit 1; }
  removeNodeApps || { $ECHO $?; exit 1; }
  if $USE_FORCE;
  then
    $ECHO "Stopping VIPs that are still up" 
    stopVIP
  fi
fi

###############################
#STEP1: stop CRS stack
###############################
if [ -f $CRSCTL ];
then
  $CRSCTL stop crs -wait
  works=false
  if $ORA_CRS_HOME/bin/crs_stat > /dev/null 2>&1
  then
    $ECHO ""
  else
    $ECHO "Oracle CRS stack is not running."
    works=true
  fi
else
  $ECHO "Unable to locate $CRSCTL"
  works=false
fi

if $works
then
   $ECHO "Oracle CRS stack is down now."

   if $USE_FORCE;
   then
      isExistsOCWProcess
      statusp=$?

      if [ "$statusp" != "0" ];
      then
          FINAL_MSG="You must kill CRSD, EVMD, and CSSD processes or reboot the system to properly cleanup the processes started by Oracle clusterware"
      fi
   fi
else 
   ###Fix the problem and rerun this script again
   $ECHO "Oracle CRS stack could not be brought down."

   if $USE_FORCE;
   then
      isOCRFileExists
      statuso=$?
      isExistsOCWProcess
      statusp=$?

      if [ "$statusp" != "0" ];
      then
          FINAL_MSG="You must kill CRSD, EVMD, and CSSD processes or reboot the system to properly cleanup the processes started by Oracle clusterware"
      else
          FINAL_MSG=""
      fi
   else
      FINAL_MSG=""
      $ECHO "Fix the problem and rerun this script."
      exit 1
   fi
fi

##Allow CRS daemons to shutdown in 10sec
sleep 10

###############################
#STEP2: remove inittab entries
###############################
$CP $IT $IT.orig || { $ECHO $?; exit 1; }
eval $RMITAB
$INIT q

$ECHO "Removing script for Oracle Cluster Ready services"
if [ -f $ID/init.crs ];
then
   $RM $ID/init.crs
fi

if [ -f $ID/init.crsd ];
then
   $RM $ID/init.crsd
fi

if [ -f $ID/init.cssd ];
then
  $RM $ID/init.cssd
fi

if [ -f $ID/init.evmd ];
then
  $RM $ID/init.evmd
fi

if [ -f $IT.crs ];
then
   $RM $IT.crs
fi

for rc in $RCALLDIR
do
  if [ -f $rc/"$RC_START"init.crs ] || [ -h $rc/"$RC_START"init.crs ];
  then
     $RMF $rc/"$RC_START"init.crs
  fi

  if [ -f $rc/"$RC_KILL"init.crs ] || [ -h $rc/"$RC_KILL"init.crs ];
  then
     $RMF $rc/"$RC_KILL"init.crs
  fi

  if [ -f $rc/"$RC_KILL_OLD"init.crs ] || [ -h $rc/"$RC_KILL_OLD"init.crs ];
  then
    $RMF $rc/"$RC_KILL_OLD"init.crs
  fi
done

if [ "$SHAREDHOME" = "nosharedhome" ]; then
  if [ -d $ORA_CRS_HOME ];
  then
     if $validOwner;
     then
       $CHOWN -R $ORACLE_OWNER $ORA_CRS_HOME
       $CHMOD -R u+w $ORA_CRS_HOME
     fi
  fi
fi

################ Step 3 ###############
## Reset OCR settings
#######################################
resetOCR || { $ECHO $?; exit 1;}

#######################################
## Reset permissions on log files
#######################################
if [ "$LOCALNODE" = "remote" ];
then
   #Reset permissions on log dirs
   LOGDIR=$ORA_CRS_HOME/log/$HOST
   CRS_LOGDIR=$LOGDIR/crsd
   ALERTFILE=$LOGDIR/alert$HOST.log

   if [ -d $LOGDIR ];
   then
     if $validOwner;
     then
       $CHOWN $ORACLE_OWNER $LOGDIR
     fi
   fi

   if [ -d $CRS_LOGDIR ];
   then
     if $validOwner;
     then
        $CHOWN $ORACLE_OWNER $CRS_LOGDIR
     fi
   fi

   if [ -f $ALERTFILE ];
   then
     if $validOwner;
     then
       $CHOWN $ORACLE_OWNER $ALERTFILE
     fi
   fi

fi

############### Step 5 ###################
## delete SCR settings
##########################################
$ECHO "Cleaning up SCR settings in '$SCR_BASE'"
if [ -d $SCR_BASE ];
then
  $RM -rf $SCR_BASE
fi

############### Step 6 ###################
## cleaning up NS directories
##########################################
NSReset

# remove oprocd directory, including socket directories and log files
if [ -d  $OPROCDDIR ];
then
  $RMRF $OPROCDDIR
fi

if [ -d  $OCRCONFIGDIR ];
then
  NoFiles=`$LS1 $OCRCONFIGDIR | $WCL | $AWK '{print $1}'`
  if [ "$NoFiles" = "0" ];
  then
    $RMRF $OCRCONFIGDIR
  fi
fi

$ECHO $FINAL_MSG
