#!/bin/sh
#
# postpatch.sh for parsing CRS script files
#
#    This is run to parse the Installer specific variables in CRS scripts
#    that are to be patched with the values supplied by the user during
#    CRS installation.
#
#    This should be used for parsing any script that has regular expressions of
#    form %<installer-variable>%

CP=/bin/cp
MV=/bin/mv
CHOWN=/bin/chown
CHGRP=/bin/chgrp
CHMOD=/bin/chmod
ECHO=/bin/echo
RM=/bin/rm
RMF="/bin/rm -f"
CAT=/bin/cat
GREP=/bin/grep
CAT=/bin/cat
SED=/bin/sed
MKDIRP="/bin/mkdir -p"
UNAME="/bin/uname"
NULL='/dev/null'
EXPRN='/usr/bin/expr'
SH='/bin/sh'
FILE='/usr/bin/file'

PLATFORM=`$UNAME`
case $PLATFORM in
Linux)
  HEAD="/usr/bin/head"
  AWK=/bin/awk
  ;;
HP-UX)
  HEAD="/bin/head"
  AWK=/bin/awk
  ;;
SunOS)
  HEAD="/bin/head"
  AWK=/usr/bin/nawk
  ;;
AIX)
  HEAD="/bin/head"
  AWK=/bin/awk
  ;;
OSF1)
  HEAD="/bin/head"
  AWK=/bin/awk
  ;;
Darwin)
  HEAD="/usr/bin/head"
  AWK=/bin/awk
  ;;
*)
  /bin/echo "ERROR: Unknown Operating System"
  exit -1
  ;;
esac

##This lists all the CRS scripts that we use today in production environment
#If there is any new CRS script added for CRS then update this
ALL_SCRIPTS="bin/racgons bin/racgwrap bin/usrvip bin/evmd bin/crs_register bin/crs_relocate bin/crs_start bin/crs_stat bin/crs_stop bin/crs_unregister bin/crs_setperm bin/crs_getperm bin/crsd bin/evmmkbin bin/evmmklib bin/evmpost bin/evmshow bin/evmwatch bin/evmlogger bin/evminfo bin/evmreload bin/evmsort bin/crs_profile evm/admin/conf/evmlogger.conf evm/admin/conf/evmdaemon.conf evm/admin/conf/evm.auth root.sh install/rootconfig install/rootinstall bin/localconfig install/rootdeletenode.sh install/rootdelete.sh install/rootdeinstall.sh crs/admin/init.crsd css/admin/init.cssd evm/admin/init.evmd crs/admin/init.crs bin/ocssd bin/diskmon bin/crsctl bin/oprocd bin/oclsmon bin/oclsomon bin/oclsvmon bin/clscfg bin/clsfmt bin/clsid bin/cluvfy cv/remenv/exectask.sh cv/remenv/exectask bin/ocrconfig bin/ocrpatch bin/ocrdump bin/ocrcheck bin/lsnodes bin/cemutlo bin/cemutls bin/olsnodes bin/oifcfg bin/srvctl bin/cluutil bin/vipca bin/gsd.sh bin/gsdctl"
ALL_SCRIPTS="$ALL_SCRIPTS install/paramfile.crs install/rootlocaladd install/rootupgrade srvm/utl/rootconfigadd racg/admin/racgwrap install/cmdllroot.sh install/preupdate.sh install/onsconfig bin/clssproxy bin/oclskd"

###Function for displaying usage of this script
usage()
{
   printf "Usage:"
   printf "$0 -crshome <Oracle CRS home path>"
   printf "   [-paramfile <Path of file specifying CRS parameter values>]"
   printf "   [-scriptfile <Path of CRS script file to be parsed>]"
}

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

   while [ $# -gt 0 ];
   do
     if [ $1 = "-paramfile" ]; then
       if [ $# -ge 2 ]; then
         CRS_ENV_FILE=$2;
         shift;
       else
         usage;
         exit 2
       fi
     elif [ $1 = "-scriptfile" ]; then
       if [ $# -ge 2 ]; then
         CRS_SCRIPT_FILE=$2;
         shift;
       else
         usage;
         exit 2
       fi
     elif [ $1 = "-crshome" ]; then
       if [ $# -ge 2 ]; then
	 ORA_CRS_HOME=$2;
         shift;
       else
	 usage;
	 exit 2
       fi
     else
       usage;
       exit 2
     fi
     shift;
   done
}

##Function for verifying CRS parameter settings in the given param file
verifyparamfile()
{
  ret=0;
  $ECHO "Reading $CRS_ENV_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-zA-Z0-9_]*\=\`*\`/ { printf("\"%s\"\n", $0); next } \
                     /[a-zA-Z0-9_]*\=/ { next } \
                     /^$/   { next } \
                            { printf("\"%s\"\n", $0); next }' $CRS_ENV_FILE`

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

  return $ret;
}

##Function for verifying CRS parameter settings in the given param file
getparamfile()
{
  ret=0;
  $ECHO "Reading $CRS_ENV_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
  $AWK 'BEGIN { Ni=0 } \
       /[a-zA-Z0-9_]*\=/ { print; next } \
       /^$/   { next } \
       /^#.*/   { next } \
              { next }' $CRS_ENV_FILE > $CRS_ENV_FILE.$$

  fileContents=`$CAT $CRS_ENV_FILE.$$`
  if [ "x$fileContents" = "x" ]; then
     $ECHO "Failed to generate a temp paramfile for use"
     ret=1;
  fi

  return $ret;
}

validateScriptFile()
{
  for i in $CRS_SCRIPT_FILE;
  do
     i=$ORA_CRS_HOME/$i
     $ECHO "Verifying file $i"

     if [ -f "$i" ]; then
       ## Make sure that the file is really script file.
       $SH -n $i  > $NULL 2>&1 
       STATUS1=$?
       LC_ALL=C $FILE $i | $GREP -wi "text" > $NULL 2>&1
       STATUS2=$?
       if [ "$STATUS1" != "0" ] && [ "$STATUS2" != "0" ]; then
         $ECHO "Skipping non-text file $i" 
       else
         ## Make sure that CRS script file has been parsed to replace all the
         ##Installer variables. If there are some Installer variables that aren't
         ##replaced then it means the parameter files does not have values
         ##set for all of them
         awkOutput=`$AWK '
                         /^$/   { next } \
                         /^#/   { next } \
                         /^UNIQUEDATE/ { next } \
	   	         /%[a-zA-Z0-9_-]*%/ {
			    len=length();
			    str=$0;
			    grpind=index(str, "%");
			    substr1=substr(str, grpind+1, len);
			    grpind2=index(substr1, "%");
			    installstr=substr(str, grpind+1, grpind2-1);
			    printf("%s\n", installstr);
			    next } \
		          { next }' $i`
  
         if [ "x$awkOutput" != "x" ]; then
	   $ECHO "The following CRS variable values are not found to parse the file: $awkOutput"
	   $ECHO "Set the values for these variables in '$CRS_ENV_FILE' and rerun this script"
         fi
       fi
     else
       $ECHO "Skipping the missing file $i"
     fi
  done
}  

resetPerms()
{
  for i in $CRS_SCRIPT_FILE;
  do
     if [ -f "$ORA_CRS_HOME/$i" ]; then
       $ECHO "Reapplying file permissions on $ORA_CRS_HOME/$i"
       $CHMOD +x $ORA_CRS_HOME/$i
     fi
  done
}

validateNodeNameFormat()
{
   $AWK '{ if ((/^CRS_NODE_NAME_LIST/) && !(/(,[0-9])/))
           {
             print "CRS_NODE_NAME_LIST=%s_nodenumberlist%";
           } 
           else 
           {
             print $0;
           }
         }' $SCRIPT_FILE.$$ > /tmp/$$
   $RMF $SCRIPT_FILE.$$
   $CP /tmp/$$ $SCRIPT_FILE.$$
   $RMF /tmp/$$
}

#Function to copy the non-instantiated files to templates directory.
copyToTemplates()
{
  #Check if the files are instantiated then copy
  # some files which are added like rootconfig.sh and rootinstall.sh
  # were copied after instantiation
  notInstan=`$AWK '/%[a-zA-Z0-9_-]*%/ {
                     print("1");
                     exit }' $ORA_CRS_HOME/$i`
  if [ "$notInstan" = "1" ];
  then 
    if [ -s $ORA_CRS_HOME/inventory/Templates/$i ] \
       && [ ! -w $ORA_CRS_HOME/inventory/Templates/$i ];
    then
      $CHMOD ug+w $ORA_CRS_HOME/inventory/Templates/$i
    fi
    $ECHO "Copying file $ORA_CRS_HOME/$i to $ORA_CRS_HOME/inventory/Templates/$i"
    $CP $ORA_CRS_HOME/$i $ORA_CRS_HOME/inventory/Templates/$i
  else
    $ECHO "Skipping instantiated file $ORA_CRS_HOME/$i" 
  fi
}

parseArgs $*

if [ -z "$ORA_CRS_HOME" ];
then
    $ECHO "ORA_CRS_HOME is not specified"
    usage;
    exit 1;
fi

USRCO=$ORA_CRS_HOME/racg/usrco
if [ ! -d $USRCO ]; then
   $MKDIRP $USRCO
fi

if [ -z "$CRS_ENV_FILE" ];
then
    $ECHO "Oracle CRS_ENV_FILE is not specified but using $ORA_CRS_HOME/install/params.crs for parameter definitions"
    CRS_ENV_FILE=$ORA_CRS_HOME/install/params.crs
fi

USE_PATH=false
if [ -z "$CRS_SCRIPT_FILE" ];
then
    $ECHO "Oracle CRS_ENV_FILE is not specified"
    $ECHO "Oracle CRS_SCRIPT_FILE is not specified but using all the Oracle CRS scripts."
    CRS_SCRIPT_FILE=$ALL_SCRIPTS
    USE_PATH=true
fi

verifyparamfile || { $ECHO $?; exit 1; }
getparamfile || { $ECHO $?; exit 1; }

for i in $CRS_SCRIPT_FILE;
do
    if [ "$USE_PATH" = "true" ];
    then
        SCRIPT_FILE=$ORA_CRS_HOME/$i
    else
        SCRIPT_FILE=$i
    fi

    if [ -f $SCRIPT_FILE ];
    then
       
        ## Make sure that the file is really script file.
        $SH -n $SCRIPT_FILE > $NULL 2>&1
        STATUS1=$?
        LC_ALL=C $FILE $SCRIPT_FILE | $GREP -wi "text" > $NULL 2>&1
        STATUS2=$?
        if [ "$STATUS1" != "0" ] && [ "$STATUS2" != "0" ]; then
          $ECHO "Skipping non-text file $SCRIPT_FILE"
          continue
        fi

        ## Copy to Templates directory
        copyToTemplates
 
        $ECHO "Parsing file $SCRIPT_FILE"
	$CP $SCRIPT_FILE $SCRIPT_FILE.$$
        validateNodeNameFormat 
	for line in `$CAT $CRS_ENV_FILE.$$`;
	do
	    varName=`$ECHO $line | $AWK -F"=" '{ print $1 }'`
	    varValue=`$ECHO $line | $AWK -F"=" '{ print $2 }'`
	    varValue=`$ECHO "$varValue" | $SED -e 's|\/|\\\/|g'`

	    $CAT $SCRIPT_FILE.$$ | $SED -e s/%$varName%/$varValue/g > /tmp/$$
            $RMF $SCRIPT_FILE.$$
	    $CP /tmp/$$ $SCRIPT_FILE.$$
	done

	$RMF /tmp/$$

	if [ -s $SCRIPT_FILE.$$ ];
	then
            $RMF $SCRIPT_FILE
	    $CP $SCRIPT_FILE.$$ $SCRIPT_FILE
	else
	    $ECHO "Failed to parse the file $SCRIPT_FILE"
	    $RMF $SCRIPT_FILE.$$
	    exit 1
	fi
	$RMF $SCRIPT_FILE.$$;
    fi
done

$RMF $CRS_ENV_FILE.$$
	
validateScriptFile

resetPerms
