#!/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 [local|remote] [sharedvar|nosharedvar] [shardhome|nosharedhome]
# 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] [local|remote] [nosharedvar|sharedvar] [sharedhome|nosharedhome] [-downgrade [-version <version>]]\n"
   printf "\-help: print this message\n"
   printf "local: if this node is the node where OUI is to be run to deinstall, otherwise use 'remote'\n"
   printf "sharedvar: OCR is on a shared path, otherwise use 'nosharedvar'\n"
   printf "sharedhome: CRS home is on a shared path, otherwuse use 'nosharedhome'\n"
   printf "\-downgrade: Oracle clusterware and OCR will be reset for downgrade\n"
   printf "\-version <version>: OCR location file will reset for downgrade to specified version, default: 10.1\n"
}

USER_ARGS=$*

LOCALNODE="local"
SHAREDVAR="nosharedvar"
SHAREDHOME="sharedhome"
DOWNGRADE=FALSE
VERSION="10.1"

CH=$ORA_CRS_HOME
ORACLE_HOME=$ORA_CRS_HOME
export ORA_CRS_HOME
export ORACLE_HOME

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

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

   if [ "$DOWNGRADE" = "TRUE" ];
   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 ""
         else
           #CASE 1.3: srvconfig_loc = ocrconfig_loc
	   #do nothing
	   $ECHO ""
         fi
      fi

      if [ "$LOCALNODE" = "remote" ];
       then
       $RM $OCRCONFIG
      fi

     else
      #ocr.loc will preserved for downgrading to 10.1
      $ECHO ""
     fi
   else
     if [ "$LOCALNODE" = "remote" ];
     then
       $RM $OCRCONFIG
     fi
   fi

   #Reset the permissions of OCRCONFIGDIR
   $CHOWN $ORACLE_OWNER $OCRCONFIGDIR 
   $CHGRP $DBA_GROUP $OCRCONFIGDIR 
   $CHMOD 755 $OCRCONFIGDIR 

   return 0
}

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
   NODE_NAME=`$ORA_CRS_HOME/bin/olsnodes -l`

   ### 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 | grep $NODE_NAME | $AWK '{ 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. Delete the database instance using DBCA before preparing to deconfigure CRS stack on this node."
             return 1
	   fi
	 done
       fi
     done

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

   $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=$?

   if [ "$STATUS" != "0" ];then
      return 1
   fi

  fi

  return 0
}

# 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

if [ $# -gt 6 ]; then
  usage;
  exit 1
fi

if [ $# -gt 0 ];
then
 if [ $1 = "-help" ];
 then
   usage;
   exit 2;
 fi
fi

while [ $# -gt 0 ];
do
  if [ $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.1" -a "$VERSION" != "9.2" ]; then
           $ECHO "Wrong version ($VERSION) number specified as an input. You can  downgrade cluster repository to either 10.1 or 9.2 versions"
	   exit 1;
         fi
       else
         $ECHO "Specify a target version number for downgrade"
         exit 2
       fi
       shift;
      fi
    fi
  else
    usage;
    exit 2;
  fi
  shift;
done

#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 | $AWK '{ print tolower($0); }'`;
else
 HOST=`$ECHO $HOST | $AWK '{ print tolower($0); }'`
fi

# 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=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
       ;;
HP-UX) 
       ID=/sbin/init.d
       RCALLDIR="/sbin/rc2.d /sbin/rc3.d"
       RC_START=S960
       RC_KILL=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
       ;;
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=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
       ;;
AIX)   
       ID=/etc
       RCALLDIR="/etc/rc.d/rc2.d"
       RC_START=S96
       RC_KILL=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
       ;;
OSF1)  
       ID=/sbin/init.d
       RCALLDIR="/sbin/rc3.d"
       RC_START=S96
       RC_KILL=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
       ;;
*)     /bin/echo "ERROR: Unknown Operating System"
       exit -1
       ;;
esac

if [ "$DOWNGRADE" != "TRUE" ];
then
  #########################################
  #STEP0: remove CRS nodeapps for this node
  ##########################################
  verifyCRSResources || { $ECHO $?; exit 1; }
fi

###############################
#STEP1: stop CRS stack
###############################
$ID/init.crs stop
works=false
for i in 5 10 15 20 25 30 35 40 45 50 55 60
do
    $ECHO "Checking to see if Oracle CRS stack is down..."
    if $CH/bin/crs_stat > /dev/null 2>&1
    then
	$ECHO ""
    else
        $ECHO "Oracle CRS stack is not running."
        works=true
        break;
    fi
    $SLEEP 5
done

if $works
then
   $ECHO "Oracle CRS stack is down now."
else 
   ###Fix the problem and rerun this script again
   $ECHO "Oracle CRS stack could not be brought down."
   $ECHO "Fix the problem and rerun this script."
   exit 1
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"
$RM $ID/init.crs $ID/init.crsd $ID/init.cssd $ID/init.evmd

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

for rc in $RCALLDIR
do
  $RMF $rc/"$RC_START"init.crs
  $RMF $rc/"$RC_KILL"init.crs
done

if [ "$SHAREDHOME" = "nosharedhome" ]; then
  $CHOWN -R $ORACLE_OWNER $CH
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

   $CHOWN $ORACLE_OWNER $LOGDIR || { $ECHO $?; exit 1; }
   $CHOWN $ORACLE_OWNER $CRS_LOGDIR || { $ECHO $?; exit 1; }
   $CHOWN $ORACLE_OWNER $ALERTFILE || { $ECHO $?; exit 1; }

fi

############### Step 5 ###################
## delete SCR settings
##########################################
$ECHO "Cleaning up SCR settings in '$SCR_BASE'"
$RM -rf $SCR_BASE

