#!/bin/sh
# CRS deconfiguration script. Must be run after running rootdelete.sh 
# on all nodes of the cluster.
# This script will wipe out OCR device used for Oracle Cluster Ready Services.
# USAGE: rootdeinstall [downgrade [ -version <version>] ]
# The option downgrade will downgrade the ocr from current 
# version to specified version
# For downgrading to 9.2.x versions, use 9.2
# For downgrading to 10.1.x versions, use 10.1
# For downgrading to 10.2.x versions, use 10.2

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

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 "$DD" ]; then DD=/bin/dd; fi
if [ -z "$ID" ]; then ID=/usr/bin/id; 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 "$MKDIRP" ]; then MKDIRP="/bin/mkdir -p"; fi

usage()
{
   printf "Usage: "
   printf "rootdeinstall [-help] [-paramfile <complete path of parameter value file>]"
   printf "              [-downgrade [-version <version>]] [-force]\n"
   printf "\-help: print this message\n"
   printf "\-paramfile <Complete path of parameter value file>\n"
   printf "\-downgrade: Downgrade OCR from 11gR1\n"
   printf "\-version <version>: Downgrade OCR to a specified version, default: 10.2\n"
   printf "\-force :  Force the cleanup of root configuration\n"
}

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

   if [ $# -gt 5 ]; 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 = "-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;
}

setOCRFile()
{
   $ECHO "Verifying existence of ocr.loc file"
   if [ ! -d $OCRCONFIGDIR ]; then
     $ECHO "$OCRCONFIGDIR directory does not exist"

     if [ -d /tmp/install ]; 
     then
        if [ -f /tmp/install/ocr.loc ];
	then
	    $ECHO "ocr.loc file exists in deinstall backup directory"
	    $MKDIRP $OCRCONFIGDIR
	    $CP /tmp/install/ocr.loc $OCRCONFIG
	    $RMF /tmp/install/ocr.loc
        fi
     fi
   fi
}
   
# This script is intended to be run by root.

RUID=`$ID|$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

USER_ARGS=$*
DOWNGRADE=false
VERSION=""
USE_FORCE=false;
USE_PARAM_FILE=false

####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

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

OCRCONFIGDIR=/etc/oracle
SRVCONFIG=$OCRCONFIGDIR/srvConfig.loc
OCRCONFIG=$OCRCONFIGDIR/ocr.loc

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

case $PLATFORM in
Linux) OCRCONFIGDIR=/etc/oracle
       OCRCONFIG=/etc/oracle/ocr.loc
       SRVCONFIG=/var/opt/oracle/srvConfig.loc
       ;;
HP-UX) OCRCONFIGDIR=/var/opt/oracle
       SRVCONFIG=/var/opt/oracle/srvConfig.loc
       OCRCONFIG=/var/opt/oracle/ocr.loc
       ;;
SunOS) OCRCONFIGDIR=/var/opt/oracle
       SRVCONFIG=/var/opt/oracle/srvConfig.loc
       OCRCONFIG=/var/opt/oracle/ocr.loc
       ;;
AIX)   OCRCONFIGDIR=/etc/oracle
       SRVCONFIG=/var/opt/oracle/srvConfig.loc
       OCRCONFIG=/etc/oracle/ocr.loc
       ;;
OSF1)  OCRCONFIGDIR=/var/opt/oracle
       SRVCONFIG=/var/opt/oracle/srvConfig.loc
       OCRCONFIG=/var/opt/oracle/ocr.loc
       ;;
*)     $ECHO "ERROR: Unknown Operating System"
       exit -1
       ;;
esac

setOCRFile

if [ "$DOWNGRADE" != "true" ];
then
   if [ -f "$SRVCONFIG" ];
   then
     $ECHO "There may be 9i RAC databases in OCR."
     $ECHO "Downgrading OCR will downgrade database configurations to 9i RAC format."
     $ECHO "Do you want to downgrade OCR configuration?[y]:[y/n]"
     while :
     do
        read RDVAR
        case $RDVAR in
          "")     RDVAR="n" ; break ;;
          !*)     ${SHELL-/bin/sh} ; echo ;;
          *)      break ;;
        esac
     done 

     if [ "$RDVAR" = "y" ] || [ "$RDVAR" = "Y" ]; then
        DOWNGRADE=true
     fi

     if $DOWNGRADE;
     then
       if [ -z "$VERSION" ];
       then
	  $ECHO "Which database version should OCR downgrade to?[10.2]:[10.2|10.1|9.2]"
	  while :
          do
	    read RDVAR
	    case $RDVAR in
	      "")     RDVAR="n" ; break ;;
	      !*)     ${SHELL-/bin/sh} ; echo ;;
	       *)     break ;;  
	    esac
          done 

          if [ "$RDVAR" = "10.2" ] || [ "$RDVAR" = "10.1" ] || [ "$RDVAR" = "9.2" ]; then
            VERSION=$RDVAR
	  else
	    $ECHO "The version '$RDVAR' entered for downgrade is invalid. Retry again with valid version for downgrade"
            exit 1
	  fi
       fi
     fi
   fi
fi

if $DOWNGRADE;
then

   #Downgrading databases
   $ECHO "Downgrading database configuration to version $VERION"
   #srvconfig -downgrade $VERSION

   #Downgrading OCR 
   #If OCR has any database configurations, then 
   #You must downgrade each databases manually, 
   #and downgrade its OCR configuration using 'srvconfig -downgrade' 
   #before downgrading OCR

   $ECHO "You must have downgraded Oracle database configurations in OCR using 'Oracle home/bin/srvconfig' prior to downgrading OCR. Continue?[n]:[y/n]"
   while :
   do
     read RDVAR
     case $RDVAR in
        "")     RDVAR="n" ; break ;;
        !*)     ${SHELL-/bin/sh} ; echo ;;
        *)      break ;;
     esac
   done 

   if [ "$RDVAR" = "n" -o "$RDVAR" = "N" ]; then
     exit 1
   fi

   #Remove 10.2 specific OCR keys and additional voting devices
   if [ "$VERSION" = "10.2" ] || [ "$VERSION" = "10.1" ];
   then
     CRS_VER=$VERSION.0.0.0
     $ECHO  $CH/bin/clscfg -downgrade -version $CRS_VER
     $CH/bin/clscfg -downgrade -version $CRS_VER
     status=$?
     if [ $status != 0 ];
     then
        $ECHO "CLSCFG failed to downgrade OCR keys"
        exit $status
     else
	VOTE_DISK=`$CH/bin/crsctl query css votedisk -force | $AWK '{ if (NR==1) print }' | $AWK '{ print $3}'`
        if [ -f $VOTE_DISK ];
	then
	   if $validOwner;
           then
	      $CHOWN $ORACLE_OWNER $VOTE_DISK
	   fi

	   if $validGrp;
           then
	      $CHGRP $DBA_GROUP $VOTE_DISK
	   fi

	   $CHMOD 640 $VOTE_DISK
	fi
     fi
   fi

   if [ "$VERSION" = "9.2" ]; then
    $ECHO "Downgrading ocr configuration to 9.2"
    #Check existence of srvConfig.loc
    if [ ! -f "$SRVCONFIG" ];
    then
      #CASE 1: srvConfig.loc file does not exist. So creating one
      OCRLOC=`$AWK -F= '/ocrconfig_loc/ {print $2}' < $OCRCONFIG`
      $ECHO srvconfig_loc=$OCRLOC > $SRVCONFIG 

      if $validGrp;
      then
         $CHGRP $DBA_GROUP $SRVCONFIG
      fi

      $CHMOD 644 $SRVCONFIG

      $ECHO "downgrading ocr configuration now"
      $CH/bin/ocrconfig -downgrade -version $VERSION

    else 
      #CASE 2: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 2.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 

        $ECHO "downgrading ocr configuration now"
        $CH/bin/ocrconfig -downgrade -version $VERSION

      elif [ "$SRV_OCRLOC" != "$OCRLOC" ];
      then
        #CASE 2.2 srvconfig_loc!=ocrconfig_loc

        $ECHO "downgrading ocr configuration now"
        $CH/bin/ocrconfig -downgrade -version $VERSION

	#OCR device contents will be wiped out
        $DD if=/dev/zero skip=25 bs=4k count=2560 of=$OCRLOC

      else 

        #CASE 2.3: srvconfig_loc = ocrconfig_loc
        $ECHO "downgrading ocr configuration now"
        $CH/bin/ocrconfig -downgrade -version $VERSION

      fi

      #Remove ocr.loc file
      $RM $OCRCONFIG
    fi
   elif [ "$VERSION" = "10.1" ]; then
      $ECHO "Downgrading ocr configuration to 10.1"
      $CH/bin/ocrconfig -downgrade -version $VERSION
   fi
fi

OCRMIRRORLOC=
if [ ! -f "$OCRCONFIG" ];
then
  # ocr.loc file does not exist. Take ocr location of srvconfig.loc for setting
  # file permissions
  OCRLOC=`$AWK -F= '/srvconfig_loc/ {print $2}' < $SRVCONFIG`
else 
  OCRLOC=`$AWK -F= '/ocrconfig_loc/ {print $2}' < $OCRCONFIG`
  OCRMIRRORLOC=`$AWK -F= '/ocrmirrorconfig_loc/ {print $2}' < $OCRCONFIG`

  if [ -z "$OCRMIRRORLOC" ];
  then
     #OCR mirror device is not specified.
     $ECHO ""
  elif [ "$OCRMIRRORLOC" = "/dev/null" ]; then
     #OCR mirror location is disabled
     $ECHO ""
  else
     $ECHO "Removing contents from OCR mirror device"
     $DD if=/dev/zero skip=25 bs=4k count=2560 of=$OCRMIRRORLOC
  fi

  if [ "$DOWNGRADE" != "true" ];
  then
     $ECHO "Removing contents from OCR device"
     $DD if=/dev/zero skip=25 bs=4k count=2560 of=$OCRLOC

     $RM $OCRCONFIG
  fi
fi

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

   if $validGrp;
   then
      $CHGRP $DBA_GROUP $OCRLOC
   fi

   $CHMOD 644 $OCRLOC
fi

if [ ! -z "$OCRMIRRORLOC" ];
then
  if [ -f $OCRMIRRORLOC ];
  then
     if $validOwner;
     then
        $CHOWN $ORACLE_OWNER $OCRMIRRORLOC
     fi

     if $validGrp;
     then
        $CHGRP $DBA_GROUP $OCRMIRRORLOC
     fi

     $CHMOD 644 $OCRMIRRORLOC
  fi
fi

#Reset the permissions on OCRCONFIGDIR
if [ -d $OCRCONFIGDIR ];
then
   $CHOWN $ORACLE_OWNER $OCRCONFIGDIR 
   $CHGRP $DBA_GROUP $OCRCONFIGDIR 
   $CHMOD 755 $OCRCONFIGDIR 
fi

$CHOWN -R $ORACLE_OWNER $CH
$CHMOD -R u+w $CH

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