#!/bin/sh
#
# $Header: tfa/src/v2/install_wrapper.sh /st_tfa_12.1/8 2014/05/29 06:20:07 bburton Exp $
#
# install_wrapper.sh
#
# Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
#
#    NAME
#      install_wrapper.sh - <one-line expansion of the name>
#
#    DESCRIPTION
#      <short description of component this file declares/defines>
#
#    NOTES
#      <other useful comments, qualifications, etc.>
#
#    MODIFIED   (MM/DD/YY)
#    bburton     05/29/14 - XbranchMerge bburton_bug-18862153 from main
#    cnagur      05/29/14 - XbranchMerge cnagur_tfa_patch_exit_status_txn from
#                           main
#    cnagur      05/22/14 - XbranchMerge cnagur_tfa_buildid_sunos_txn from main
#    cnagur      05/20/14 - XbranchMerge cnagur_tfa_buildid_hpux_txn from main
#    gadiga      05/20/14 - XbranchMerge gadiga_add_oratop from main
#    cnagur      05/19/14 - XbranchMerge cnagur_tfa_buildid_issues_txn from
#                           main
#    bburton     04/30/14 - XbranchMerge cnagur_tfa_hpux_rm_tfahome_txn from
#                           main
#    bburton     04/24/14 - XbranchMerge cnagur_tfa_awk_issues_txn from main
#    bburton     05/29/14 - bug 18862153 used invalied test args in oratop
#                           addition
#    cnagur      05/29/14 - Fix for Bug 18841413
#    cnagur      05/22/14 - BUILDID issues with SunOS
#    cnagur      05/20/14 - BUILDID issues with HP-UX
#    cnagur      05/19/14 - Fix for Bug 18765905
#    cnagur      04/25/14 - CD to home dir - Bug 18634296
#    cnagur      04/14/14 - AWK Issues - Bug 18533720
#    cnagur      03/17/14 - Export PERL
#    cnagur      03/04/14 - Fix for Bug 18343490
#    amchaura    02/28/14 - Fix scanner after patch/restart TFA
#    cnagur      02/25/14 - Updated TFA messages and exit status
#    cnagur      02/07/14 - Added check for BASEDIR if it ends with /tfa/
#    cnagur      01/20/14 - Removed duplicate AWK
#    cnagur      12/30/13 - Added REL_DIR check for Non-GI Install
#    cnagur      12/18/13 - Not remove any files for debug
#    cnagur      12/18/13 - Bug 17964643
#    cnagur      12/17/13 - Bug 17964798
#    gadiga      11/22/13 - SI support
#    cnagur      11/18/13 - 12.1 Release directory changes
#    cnagur      11/11/13 - Added check to validate CRSHOME Bug:17730581
#    cnagur      11/05/13 - Added changes to remove trailing / from GIHOME
#    cnagur      10/29/13 - Remove Old TFA for GI Install
#    cnagur      10/23/13 - Changes to remove output dir in ORACLE_BASE if
#                           Install is interrupted
#    cnagur      10/11/13 - Updated REPO_DIR for ODA GI Install
#    cnagur      10/07/13 - Changes for ODA GI Install
#    cnagur      09/24/13 - Pass -local and -silent when patching
#    cnagur      09/11/13 - TFA Patching Changes for 12.1 Shiphome
#    cnagur      08/26/13 - Remove TFA_BASE if Install was not sucessful.
#    cnagur      07/12/13 - Added function getCommandLocation()
#    cnagur      09/03/13 - TFA Installer Changes for 12.1 Shiphome
#    cnagur      08/12/13 - Fix for Bugs 17279427 and 17290209
#    cnagur      08/01/13 - Fix for Bug: 17168390
#    bburton     06/26/13 - remove shell incompatibilities
#    bburton     06/25/13 - /c.
#    cnagur      06/19/13 - Fix for Bug 16973989
#    bburton     06/19/13 - remove -e from echo commands
#    cnagur      06/19/13 - Updated script to remove BDB and Logs if it in
#                           ORACLE_BASE
#    bburton     06/18/13 - add the debug option so as not to remove tfa on
#                           install failure
#    bburton     06/18/13 - remove -crshome option from help and make is silent
#                           by default.
#    cnagur      06/16/13 - Moving Tfa logs to /tmp incase the installation was
#                           successful
#    cnagur      06/11/13 - Should not prompt the Install Location if -silent
#                           is passed
#    bburton     06/10/13 - add some command help and warn for illegal
#                           combinations.
#    bburton     06/07/13 - allow for -local flag
#    bburton     06/06/13 - add option to defer discovery and pass javahome
#    gadiga      05/29/13 - add build id
#    bburton     05/23/13 - Add the -crshome flag for rootcrs.pl install
#    cnagur      05/10/13 - Added /tfa to <BASEDIR> if not present
#    cnagur      05/08/13 - Added /tfa to BASEDIR if it not ends with /tfa.
#    cnagur      05/02/13 - New Directory Structure for TFA
#    gadiga      02/14/13 - permission
#    bburton     01/22/13 - fix init path for other platforms
#    gadiga      01/13/13 - sunos
#    gadiga      01/11/13 - remove duplicates
#    gadiga      01/10/13 - fix tail command
#    bburton     07/30/12 - Creation
#

#Function to get the location of commands
getCommandLocation() {

        COMMAND=$1;

        if [ -f "/bin/$COMMAND" ]
        then
                CMDLOC="/bin/$COMMAND";
        elif [ -f "/usr/bin/$COMMAND" ]
        then
                CMDLOC="/usr/bin/$COMMAND";
        elif [ -f "/usr/local/bin/$COMMAND" ]
        then
                CMDLOC="/usr/local/bin/$COMMAND";
        else
                CMDLOC="$COMMAND";
        fi

        echo "$CMDLOC";
}


UNAME=`getCommandLocation "uname"`;
PLATFORM=`$UNAME`
AWK=`getCommandLocation "awk"`;
PWD=`getCommandLocation "pwd"`;
CAT=`getCommandLocation "cat"`;
CHGRP=`getCommandLocation "chgrp"`;
CHOWN=`getCommandLocation "chown"`;
CHMOD=`getCommandLocation "chmod"`;
CP=`getCommandLocation "cp"`;
CD=`getCommandLocation "cd"`;
CUT=`getCommandLocation "cut"`;
DATE=`getCommandLocation "date"`;
DIFF=`getCommandLocation "diff"`;
ECHO=`getCommandLocation "echo"`;
GREP=`getCommandLocation "grep"`;
LBIN=/usr/local/bin;
LS=`getCommandLocation "ls"`;
MKDIR=`getCommandLocation "mkdir"`;
MV=`getCommandLocation "mv"`;
PERL=`getCommandLocation "perl"`;
PS=`getCommandLocation "ps"`;
RM=`getCommandLocation "rm"`;
SED=`getCommandLocation "sed"`;
SH=`getCommandLocation "sh"`;
TAIL=`getCommandLocation "tail"`;
TAR=`getCommandLocation "tar"`;
TEE=`getCommandLocation "tee"`;
UNZIP=`getCommandLocation "unzip"`;
WC=`getCommandLocation "wc"`;

case $PLATFORM in
Linux)
        ID=/etc/init.d
        ;;
AIX)
        ID=/etc
        ;;
SunOS)
        ID=/etc/init.d
        GREP=/usr/xpg4/bin/grep
	AWK=`getCommandLocation "gawk"`;

	# if not able to find gawk then use nawk
	if [ `$ECHO $AWK | $GREP -c "^gawk$"` -eq 1 ]
	then
		AWK=`getCommandLocation "nawk"`;

		# if not found, then exit with proper message
		if [ `$ECHO $AWK | $GREP -c "^nawk$"` -eq 1 ]
		then
			$ECHO "TFA-00016: Oracle Trace File Analyzer (TFA) requires GAWK or NAWK. Please install gawk or nawk and try again."
		fi
	fi
        ;;
HP-UX)
        ID=/sbin/init.d
        ;;
*)     $ECHO "TFA-00000: Oracle Trace File Analyzer (TFA) is not supported on this platform."
       exit -1
       ;;
esac

ME=${0}
#MESHORT=${0##*/}
SILENT=""
CRSHOME=""
CRSHOMEFLAG=""
ORAHOME=""
ORABASE=""
ORAHOMEFLAG=""
DEFERDISCOVERY=""
LOCALONLY=""

BUILDID=12120020140619094932

HOSTNAME=`hostname | $CUT -d. -f1 | $AWK '{print tolower($0)}'`

# print help function
printhelp() {

$ECHO ""
$ECHO "   Usage for $ME"
$ECHO ""
$ECHO "   $ME [-local][-deferdiscovery][-tfabase <install dir>][-javahome <path to JRE>][-silent]"
$ECHO ""
$ECHO "        -local            -    Only install on the local node"
$ECHO "        -deferdiscovery   -    Discover Oracle trace directories after installation completes"
$ECHO "        -tfabase          -    Install into the directory supplied "
$ECHO "        -javahome         -    Use this directory for the JRE"
$ECHO "        -silent           -    Do not ask any install questions"
$ECHO "        -debug            -    Print debug tracing and do not remove TFA_HOME on install failure"
$ECHO ""
$ECHO ""
$ECHO "   Note: Without parameters TFA will take you through an interview process for installation"
$ECHO "         /tfa will be appended to -tfabase if it is not already there. "
$ECHO ""
$ECHO ""

}


# Extract ext jar
install_ext() {
  if [ ! -n "$CRSHOME" ] ; then return; fi
  if [ -d "$tfa_home" ] ; then
    c_loc=`pwd`
    java_home_loc=`grep "JAVA_HOME=" $tfa_home/tfa_setup.txt | sed 's/JAVA_HOME=//'`
    jar_exe="$java_home_loc/bin/jar";
    if [ ! -f "$jar_exe" ] ; then
      jar_exe="$java_home_loc/../bin/jar";
    fi
    if [ ! -f "$jar_exe" ] ; then
      echo "ORATOP-WARNING: Could not find jar program\n";
      return;
    fi
    cd $tfa_home/jlib
    $jar_exe xf RATFA.jar ext.jar
    $MV ext.jar $tfa_home/ext/
    if [ -d "$java_home_loc" ] ; then
      cd $tfa_home/ext
      if [ -f "ext.jar" ] ; then
        $ECHO ""
        $ECHO "Installing oratop extension.."
        $ECHO ""
        case $PLATFORM in
          Linux)
            $RM -f oratop/oratop.RDBMS_12.1_LINUX.X64 oratop/oratop.RDBMS_12.1_LINUX.X32 oratop/oratop.RDBMS_11.2_LINUX.X64 oratop/oratop.RDBMS_11.2_LINUX.X32
            $jar_exe xf ext.jar oratop/oratop.RDBMS_12.1_LINUX.X64 oratop/oratop.RDBMS_12.1_LINUX.X32 oratop/oratop.RDBMS_11.2_LINUX.X64 oratop/oratop.RDBMS_11.2_LINUX.X32
          ;;
          AIX)
            $RM -f oratop/oratop.RDBMS_12.1_AIX.PPC64 oratop/oratop.RDBMS_11.2_AIX.PPC64
            $jar_exe xf ext.jar oratop/oratop.RDBMS_12.1_AIX.PPC64 oratop/oratop.RDBMS_11.2_AIX.PPC64
          ;;
          SunOS)
            $RM -f oratop/oratop.RDBMS_11.2_SOLARIS.X64 oratop/oratop.RDBMS_11.2_SOLARIS.SPARC64 oratop/oratop.RDBMS_12.1_SOLARIS.X64 oratop/oratop.RDBMS_12.1_SOLARIS.SPARC64
            $jar_exe xf ext.jar oratop/oratop.RDBMS_11.2_SOLARIS.X64 oratop/oratop.RDBMS_11.2_SOLARIS.SPARC64 oratop/oratop.RDBMS_12.1_SOLARIS.X64 oratop/oratop.RDBMS_12.1_SOLARIS.SPARC64
          ;;
          HP-UX)
            $RM -f oratop/oratop.RDBMS_11.2_HPUX.PARISC64 oratop/oratop.RDBMS_11.2_HPUX.IA64 oratop/oratop.RDBMS_12.1_HPUX.IA64
            $jar_exe xf ext.jar oratop/oratop.RDBMS_11.2_HPUX.PARISC64 oratop/oratop.RDBMS_11.2_HPUX.IA64 oratop/oratop.RDBMS_12.1_HPUX.IA64
          ;;
          *)     
          ;;
        esac
        $RM -f ext.jar
        cd $c_loc
      fi
    else
      $ECHO "ORATOP-WARNING: Unable to find JAVA_HOME"
    fi
  else
    $ECHO "ORATOP-WARNING: Unable to find tfa_home.";
  fi
}

#
# Parse argument
#
  while [ $# -gt 0 ]
  do
    case $1 in
      -silent)  SILENT=$1;;         # silent is set to true
      -tfabase) shift; TFABASE=$1; export TFABASE;;  # TFABASE is set
      -crshome) shift; CRSHOME=$1; export CRSHOME;;  # CRSHOME is set
      -ohome) shift; ORAHOME=$1; export ORAHOME; ORAHOMEFLAG="-ohome";;  # DBHOME is set
      -javahome) shift; JAVA_HOME=$1; TFA_JAVA=$1; export JAVA_HOME;; # JAVA_HOME is set
      -deferdiscovery) DEFERDISCOVERY=$1;;   # DEFERDISCOVERY  is set
      -local) LOCALONLY=$1;;   # LOCALONLY  is set
      -debug) INSTDEBUG=$1; TFA_DEBUG=7;export TFA_DEBUG;;   # DEBUG  is set
      -help) HELP=$1;;   # print the help and exit
      -h) HELP=$1;;   # print the help and exit
       *) $ECHO "   TFA-00003: Invalid Option $1 for TFA"; printhelp ; exit 1

    esac;
    shift
  done

if [ $HELP ]; then 
   printhelp
   exit 1
fi

if [ -n "$TFABASE" ] && [ ! -d "$TFABASE" ]; then
   $ECHO "TFA-00004: Provided TFA Base Directory $TFABASE does not exist"
   exit 1
fi

if [ -n "$CRSHOME" ]  && [ ! -d "$CRSHOME" ]; then
   $ECHO "TFA-00005: Provided CRS_HOME directory $CRSHOME does not exist"
   exit 1
fi

if [ -n "$ORAHOMEFLAG" ] && [ -z "$ORAHOME" ] ; then
  ORAHOME=`$ECHO $0 | $SED 's/\/crs\/install.*//'`;
fi

if [ -n "$ORAHOMEFLAG" ]  && [ ! -d "$ORAHOME" ]; then
   $ECHO "TFA-00006: Provided ORACLE_HOME directory $ORAHOME does not exist"
   exit 1
fi

if [ -n "$ORAHOME" ] && [ -f "$ORAHOME/bin/orabase" ] ; then
  ORABASE=`ORACLE_HOME=$ORAHOME; export ORACLE_HOME;$ORAHOME/bin/orabase`
fi

if [ -n "$ORAHOMEFLAG" ]  && [ ! -d "$ORABASE" ]; then
   $ECHO "TFA-00007: ORACLE_BASE directory '$ORABASE' does not exist"
   exit 1
fi

if [ -n "$TFA_JAVA" ] && [ ! -x "$TFA_JAVA/bin/java" ]; then 
   $ECHO "TFA-00008: JAVAHOME supplied does not have $TFA_JAVA/bin/java executable"
   exit 1
fi

if [ -n "$CRSHOME" ] || [ -n "$ORAHOME" ] ; then 
   if [ -n "$TFABASE" ] || [ -n "$TFA_JAVA" ] || [ -n "$DEFERDISCOVERY" ] || [ -n "$LOCALONLY" ]; then 
      $ECHO "TFA-00009: Invalid Parameters. Do not use any other parameters with -crshome or -ohome"
       printhelp
       exit 1
   fi
fi

if [ -n "$CRSHOME" ]  && [ ! -n "$SILENT" ]; then # -crshome is always a silent install
   SILENT="-silent"
fi

if [ -n "$CRSHOME" ]  && [ ! -n "$LOCALONLY" ]; then # -crshome is always a local install
   LOCALONLY="-local"
fi

if [ -n "$ORAHOME" ] ; then
  SILENT="-silent"
  LOCALONLY="-local"
fi

if [ -n "$CRSHOME" ]
then
	if [ `$ECHO $CRSHOME | $GREP -c "/$"` -eq 1 ]
	then
		CRSHOME=`$ECHO $CRSHOME | $SED 's/\/$//'`;
	fi

	if [ ! -f "$CRSHOME/crs/install/crsconfig_params" ]
	then
		$ECHO "TFA-00010: Provided CRS_HOME directory $CRSHOME is not valid. Please verify once again.";
		exit 1;
	fi

	REL_DIR="$CRSHOME/suptools/tfa/release";
	PERL="$CRSHOME/perl/bin/perl";

	# If location of unzip is not found then use unzip from CRSHOME
	if [ `$ECHO $UNZIP | $GREP -c "^unzip$"` -eq 1 ]
	then
		if [ -f "$CRSHOME/bin/unzip" ]
		then
			UNZIP="$CRSHOME/bin/unzip";
		else
			$ECHO "TFA-00015: Unable to find unzip. Please ensure it is in your PATH and try again.";
			exit 1;
		fi
	fi
fi

if [ -n "$ORAHOME" ]
then
        if [ `$ECHO $ORAHOME | $GREP -c "/$"` -eq 1 ]
        then
                ORAHOME=`$ECHO $ORAHOME | $SED 's/\/$//'`;
        fi

        REL_DIR="$ORAHOME/suptools/tfa/release";
	PERL="$ORAHOME/perl/bin/perl";
fi

$ECHO ""
$ECHO "Starting TFA installation"
$ECHO ""

# Firstly check if we are root .. If not then stop here.

RUID=`/usr/bin/id|$AWK -F\( '{print $1}'|$AWK -F= '{print $2}'`
if [ $RUID -ne 0 ]
then
   $ECHO "TFA-00011: Oracle Trace File Analyzer (TFA) must be run as the root user"
   exit 1
fi

# Check if bash exists
BASH_EXIST=`which bash >/dev/null 2>&1; $ECHO $?`
if [ $BASH_EXIST -ne 0 ]
then
   $ECHO "TFA-00012: Oracle Trace File Analyzer (TFA) requires BASH shell. Please install bash and try again."
   exit 1
fi

# If we are patching then we do not to do a number of the following checks.
# If tfa is already installed just patch
TFA_INSTALLED=0;
INSTALLED_BUILD=0;
INSTALLED_BLDDT=0;
INSTALLED_BLDVR=0;

# Below varables are used to remove Old TFA after Install.
OLD_TFA_HOME="";
REMOVE_OLD_TFA=0;

if [ -r "$ID/init.tfa" ]
then
	tfa_home=`$GREP '^export TFA_HOME=' $ID/init.tfa | $AWK -F"=" '{print $2}'`

  	if [ ! -n "$tfa_home" ]; then
    		tfa_home=`$GREP '^TFA_HOME=' $ID/init.tfa | $AWK -F"=" '{print $2}'`
  	fi

  	BASEDIR=`$ECHO $tfa_home | $SED -e "s/\/[^\/]*$//"`

  	if [ -r "$tfa_home/bin/tfactl" ]
  	then
		TFA_INSTALLED=1;

		# Extract Current TFA Build Version and Date
		BUILD_DATE=`$ECHO $BUILDID | $TAIL -15c`;
		BUILD_VERSION=`$ECHO $BUILDID | $SED "s/$BUILD_DATE//"`;

		$ECHO "TFA Build Version: $BUILD_VERSION Build Date: $BUILD_DATE";

		if [ -f "$tfa_home/internal/.buildid" ]
		then
			INSTALLED_BUILD=`cat $tfa_home/internal/.buildid`;

			# Extract Installed Build Version and Date
			INSTALLED_BLDDT=`$ECHO $INSTALLED_BUILD | $TAIL -15c`;
			INSTALLED_BLDVR=`$ECHO $INSTALLED_BUILD | $SED "s/$INSTALLED_BLDDT//"`;

			# If Installed version is null then set it to 0
			if [ ! -n "$INSTALLED_BLDVR" ]
			then
				INSTALLED_BLDVR=0;
			fi

			$ECHO "Installed Build Version: $INSTALLED_BLDVR Build Date: $INSTALLED_BLDDT";
			$ECHO "";
		fi

		# Check Build Version
		if [ "$BUILD_VERSION" -ge "$INSTALLED_BLDVR" ]
		then
			if [ -n "$CRSHOME" ]
			then
				#if [ "$BUILDID" -gt "$INSTALLED_BUILD" ]
				# Check Build Date
				if [ "$BUILD_DATE" -gt "$INSTALLED_BLDDT" ]
				then
					#Check if its a new GI Home:
					if [ `$ECHO $tfa_home | $GREP -c $CRSHOME` -eq 0 ]
					then
						#Shutdown TFA if it is running
						if [ `$PS -ef | $GREP $ID/init.tfa | $GREP -v grep | $WC -l` -ge 1 ]
						then
							$ECHO  "Shutting Down TFA for Patching...";
      							$ECHO "";
							$ID/init.tfa shutdown
							$ECHO "";
						fi
					
						if [ -f "$ID/init.tfa" ]
						then
							$ECHO "Removing $ID/init.tfa...";
							$RM -f $ID/init.tfa;
							$ECHO "";
						fi

						# Remove Old TFA from /opt/oracle/tfa for ODA 11204 GI Install
						ODA_TFA="/opt/oracle/tfa";

						if [ `$ECHO $tfa_home | $GREP -c "$ODA_TFA"` -eq 1 ]
						then
							if [ -d "$ODA_TFA" ]
							then
								OLD_TFA_HOME="$ODA_TFA";
								REMOVE_OLD_TFA=1;
							fi
						fi

						$ECHO "Installing TFA new version at $CRSHOME/tfa/$HOSTNAME/tfa_home...";
						$ECHO "";

						#Do a Fresh Install
						TFA_INSTALLED=0;
					fi

				#elif [ "$BUILDID" -le "$INSTALLED_BUILD" ]
				#then
				else
					#Just Start TFA if its not running and Exit
					$ECHO "TFA is already running latest version. No need to patch.";
					$ECHO "";

					# Start TFA if its not running
					STARTTFA=1;

					if [ -f "$tfa_home/internal/.pidfile" ]
					then
						TFAPID=`cat $tfa_home/internal/.pidfile`;
					
						if [ -n $TFAPID ]
						then
							TFAPID=`$PS -f -p $TFAPID | $GREP -v PID | $AWK '{print $2}'`

							if [ ! -z "$TFAPID" ]
							then
								STARTTFA=0;
							fi
						fi
					fi

					if [ $STARTTFA -eq 1 ]
					then
						$ID/init.tfa start
						$ECHO "";
					fi
					exit 0;
				fi  # END OF BUILD_DATE - CRSHOME

			# Check for NON-GI Install
			#elif [ "$BUILDID" -le "$INSTALLED_BUILD" ]
			elif [ "$BUILD_DATE" -le "$INSTALLED_BLDDT" ] 
			then
				$ECHO "TFA is already running latest version. No need to patch.";
				exit 0;

			fi  #END of CRSHOME
		else
			$ECHO "TFA is already running latest version. No need to patch.";
			# CHECK:
			# NEED TO START TFA FOR GI INSTALL ?

			exit 0;

		fi   # END of CHECK BUILD_VERSION
	else
		#No TFA Binaries. Remove init.tfa and do fresh install.
		$ECHO "Not able to find TFA binaries.";
		$RM -f $ID/init.tfa

  	fi  #END of tfactl

fi   #END of init.tfa

# archive required for patching and not patching
ARCHIVE=`$AWK '/^__ARCHIVE_BELOW__/ {print NR + 1; exit 0; }' $0`

#Only do the basedir and crs_up checks if we are doing a new install.
if [ $TFA_INSTALLED -eq "0" ]
then
   # And more over don;t do them if we are passed the -crshome as CRS is unlikely to be up and we know where the BASE is .
   if [ -n "$CRSHOME" ] # CRSHOME was supplied 
   then
   	BASEDIR=$CRSHOME/tfa
        CRSHOMEFLAG="-crshome $CRSHOME"
        if [ ! -d $BASEDIR ]
        then
          $MKDIR -p $BASEDIR;
        fi
   elif [ -n "$ORAHOME" ] ; then
        BASEDIR=$ORABASE/tfa
        CRSHOMEFLAG="-ohome $ORAHOME -obase $ORABASE"
        if [ ! -d $BASEDIR ]
        then
          $MKDIR -p $BASEDIR;
        fi 
   else
      # Check if CRS is up
      check_crs=`$PS -ef | $GREP -ic "d.bin"`
      if [ ${check_crs} -ge 4 ]
      then
        crs_up=1
      else
        crs_up=0
        if [ -n "$SILENT" ]
        then
          $ECHO "TFA-00013: CRS must be running for Silent Mode install. Exiting Installation";
          exit 1
        fi
      fi

      if [ -n "$TFABASE" ]; then # We supplied the install dir
         BASEDIR=$TFABASE
      else
         BASEDIR=`$PWD`
      fi

      # Check if default BASEDIR ends with /tfa. If not add /tfa to BASEDIR.
      tfa_dir="/tfa";
      root_dir="/";

      if [ `$ECHO $BASEDIR | $GREP -c $tfa_dir$` -eq 0 ] && [ `$ECHO $BASEDIR | $GREP -c $tfa_dir$root_dir$` -eq 0 ]
      then
              # Check if the BASEDIR ends with /
              if [ `$ECHO $BASEDIR | $GREP -c $root_dir$` -eq 1 ]
              then
                      BASEDIR=$BASEDIR"tfa";
              else
                      BASEDIR=$BASEDIR$tfa_dir;
              fi
      fi


      # Check for ODA or ask user for install location and cd to that location

      if [ -f "/opt/oracle/oak/bin/oakcli" ]; then
       BASEDIR="/opt/oracle/tfa"
      else
        if [ ! -n "$TFABASE" ]  && [ ! -n "$SILENT" ];then
          $ECHO "Enter a location for installing TFA (/tfa will be appended if not supplied) [$BASEDIR]: "
          read basedir
          if [ -n "$basedir" ]; then
            BASEDIR=$basedir;
          fi
        fi
      fi

      # Check if BASEDIR still ends with /tfa. If not add /tfa to BASEDIR.
      if [ `$ECHO $BASEDIR | $GREP -c $tfa_dir$` -eq 0 ] && [ `$ECHO $BASEDIR | $GREP -c $tfa_dir$root_dir$` -eq 0 ]
      then
    		# Check if the BASEDIR ends with /
		if [ `$ECHO $BASEDIR | $GREP -c $root_dir$` -eq 1 ] 
		then
			BASEDIR=$BASEDIR"tfa";
		else
			BASEDIR=$BASEDIR$tfa_dir;
   		fi
      fi
  
      # Create BASEDIR if it does not exist

      if [ ! -d $BASEDIR ]
      then
          	$MKDIR -p $BASEDIR;
      fi
   fi # End of if -n $CRSHOME 
fi # End of setup required just for a new install ie !TFA_INSTALLED

ZFILE=$BASEDIR/tfa_install.$$.zip

if [ `uname -s` = "SunOS" ] ; then
	tail +$ARCHIVE $0 > $ZFILE
else
	tail -n +$ARCHIVE $0 > $ZFILE
fi

export PERL;

cd $BASEDIR

if [ $TFA_INSTALLED -eq "1" ] ; then

  $ECHO "TFA is already installed. Patching $tfa_home...";

  PATCH_STATUS="1";
  TFAMAIN_STATUS="0";

  if [ -n "$CRSHOME" ] || [ -n "$ORAHOME" ] 
  then
	#If the ZIP FILE Size > 0 use that else use release DIR.
	if [ -s "$ZFILE" ]
	then
		TMPLOC="/tmp/.$$.tfa"
		$MKDIR $TMPLOC
		cd $TMPLOC
		$UNZIP -q $ZFILE
		$TAR xfo tfahome_full.tar
		$MV tfahome_full.tar tfa_home

		tfa_home/bin/patchtfa.sh -local -silent | tee $BASEDIR/tfapatch.log
	
	elif [ -d "$REL_DIR" ]
	then
		$REL_DIR/tfa_home/bin/patchtfa.sh -local -silent | tee $BASEDIR/tfapatch.log
	else
		$ECHO "TFA-00014: Invalid TFA Installer. Please Contact Oracle Support for Help.";
		$RM -f $ZFILE;
		exit 1;
	fi
  else
	if [ -s "$ZFILE" ]
	then
  		TMPLOC="/tmp/.$$.tfa"
		$MKDIR $TMPLOC
  		cd $TMPLOC
  		$UNZIP -q $ZFILE
  		$TAR xfo tfahome_full.tar
  		$MV tfahome_full.tar tfa_home

  		tfa_home/bin/patchtfa.sh $LOCALONLY $SILENT | tee $BASEDIR/tfapatch.log
	else
		$ECHO "Unable to patch TFA...";
		$ECHO "";
		$ECHO "TFA-00014: Invalid TFA Installer. Please Contact Oracle Support for Help.";
		$RM -f $ZFILE;
		exit 1;
	fi
  fi

  #PATCH_STATUS=${PIPESTATUS[0]};

  if [ -f "/tmp/.tfa.patch" ]
  then
	PATCH_STATUS=`cat /tmp/.tfa.patch`;
	$RM -f "/tmp/.tfa.patch";
  fi

  # If its patched properly then generate cookie and copy buildid
  if [ $PATCH_STATUS -eq 0 ]
  then
        install_ext;

	cd $BASEDIR;

  	# We no longer support file for cookie.
  	# Remove it if its already present.
  	if [ -r tfa_home/internal/.tfacookie ]; then
    		$RM -f tfa_home/internal/.tfacookie
  	fi

  	# Check status of TFAMain
	$SH tfa_home/bin/tfactl -check > /dev/null 2>&1
	TFAMAIN_STATUS=$?;
  	
	if [ $TFAMAIN_STATUS -eq 1 ]
	then 
		#$ECHO "Setting TFA cookie clusterwide"
  		$SH tfa_home/bin/tfactl generatecookie

		$ECHO "$BUILDID" > tfa_home/internal/.buildid
	
		#Start inventory after patch
		$SH tfa_home/bin/tfactl run inventory > /dev/null 2>&1
	fi
  fi

  $RM -rf $TMPLOC
  $RM -f $ZFILE
  $RM -f $BASEDIR/tfa_home/tfahome_full.tar

  if [ $TFAMAIN_STATUS -eq 1 ]
  then
  	exit 0;
  else
	exit 1;
  fi

else

  if [ -n "$CRSHOME" ] || [ -n "$ORAHOME" ] 
  then
	tfa_base=$BASEDIR/$HOSTNAME
	tfa_home=$tfa_base/tfa_home;

	if [ ! -d bin ]
	then
		$MKDIR bin;
		$CHMOD a+x bin;
	fi

	if [ ! -d $tfa_base ]
	then
		$MKDIR $tfa_base;
		$CHMOD a+x $tfa_base;
	fi

	cd $tfa_base

	#If the ZIP FILE Size > 0 use that else use release DIR.

	if [ -s "$ZFILE" ]
	then
		$UNZIP -q $ZFILE
		$TAR xfo tfahome_full.tar
		$MV tfahome_full.tar $tfa_home

	elif [ -d "$REL_DIR/tfa_home" ]
	then
		$CP -r -L $REL_DIR/tfa_home $tfa_base/
	else
		$ECHO "TFA-00014: Invalid TFA Installer. Please Contact Oracle Support for Help.";
		$RM -f $ZFILE;
		exit 1;
	fi

	$PERL $tfa_home/bin/tfasetup.pl $SILENT $CRSHOMEFLAG $DEFERDISCOVERY $LOCALONLY

  elif [ ! -f "/opt/oracle/oak/bin/oakcli" ]
  then 
  	tfa_base=$BASEDIR/$HOSTNAME
  	tfa_home=$tfa_base/tfa_home

  	if [ ! -d bin ]
	then
		$MKDIR bin;
	  	$CHMOD a+x bin;
	fi

	if [ ! -d $tfa_base ]
	then
		$MKDIR $tfa_base;
		$CHMOD a+x $tfa_base;
	fi

	cd $tfa_base

	if [ -s "$ZFILE" ]
	then
		$UNZIP -q $ZFILE
		$TAR xfo tfahome_full.tar
		$MV tfahome_full.tar $tfa_home
		#$MV $tfa_home/bin/tfactl $BASEDIR/bin
		$PERL $tfa_home/bin/tfasetup.pl $SILENT $CRSHOMEFLAG $DEFERDISCOVERY $LOCALONLY
	else
		$ECHO "TFA-00014: Invalid TFA Installer. Please Contact Oracle Support for Help.";
		$RM -f $ZFILE;
		exit 1;
	fi
  else # This is an ODA so we never provide CRSHOME
  	tfa_home=$BASEDIR/tfa_home
	$UNZIP -q $ZFILE
	$TAR xfo tfahome_full.tar
	$MV tfahome_full.tar $tfa_home
	$PERL tfa_home/bin/tfasetup.pl $SILENT
  fi

fi

EXIT_STATUS=$?;

if [ $EXIT_STATUS -eq 0 ] ; then

  install_ext;

  $ECHO "";
  $ECHO "TFA is successfully installed...";
  $ECHO "";
  $PERL tfa_home/bin/tfactl -help

  #Remove Old TFA Home if present
  if [ $REMOVE_OLD_TFA -eq 1 ]
  then
        if [ -d "$OLD_TFA_HOME" ]
        then
		$ECHO "Removing Old TFA $OLD_TFA_HOME...";
                $RM -rf $OLD_TFA_HOME;
        fi
  fi
else
  $ECHO "Removing TFA Setup files..."

  #Move the TFA logs to /tmp

  LOG_DIR="$tfa_home/log";

  if [ -f "$tfa_home/tfa_setup.txt" ]
  then
	CRS_HOME=`$GREP '^CRS_HOME=' $tfa_home/tfa_setup.txt | $AWK -F"=" '{print $2}'`;
	ORACLE_BASE=`$GREP '^ORACLE_BASE=' $tfa_home/tfa_setup.txt | $AWK -F"=" '{print $2}'`;

	if [ -n "$CRS_HOME" ]
	then
		#Check if TFA_HOME is under CRS_HOME [ GI Install ]
		if [ `$ECHO $tfa_home | $GREP -ic "$CRS_HOME"` -eq 1 ]
		then
			if [ -n "$ORACLE_BASE" ]
			then
				LOG_DIR="$ORACLE_BASE/tfa/$HOSTNAME/log";
				BDB_DIR="$ORACLE_BASE/tfa/$HOSTNAME/database";
				OUT_DIR="$ORACLE_BASE/tfa/$HOSTNAME/output";
				SHARED_FILE="$ORACLE_BASE/tfa/.$HOSTNAME.shared";
				REPO_DIR="$ORACLE_BASE/tfa/repository";
			fi
		fi
	fi
  fi

  $ECHO "";

  LOG_COUNT=`$LS -1 $LOG_DIR | $WC -l`;

  if [ -d "$LOG_DIR" ] && [ -n "$LOG_COUNT" ] && [ "$LOG_COUNT" -ge "1" ]
  then
	TEMP_LOG_DIR="/tmp/tfa/`date '+%Y%m%d_%H%M%S'`";

	if [ ! -d "$TEMP_LOG_DIR" ]
	then
		$MKDIR -p "$TEMP_LOG_DIR";
	fi

	$ECHO "Copying TFA logs to $TEMP_LOG_DIR";
	$CP -f $LOG_DIR/* $TEMP_LOG_DIR
	$ECHO "";

	#$ECHO "Removing $LOG_DIR...";
	#$RM -rf $LOG_DIR;
  else
	$ECHO "No TFA Logs in $LOG_DIR to copy to /tmp.";
	$ECHO "";
  fi

  # Shutdown TFA if it is running
  if [ `$PS -ef | $GREP $ID/init.tfa | $GREP -v grep | $WC -l` -ge 1 ]
  then
	$ECHO  "Shutting down TFA now...";
        $ECHO "";
        $ID/init.tfa shutdown
	$ECHO "";
  fi
   
  # CD to home directory before removing TFA files
  cd;

  # Do not remove TFA if we supply the -debug option
  if [ $INSTDEBUG ]
  then 
    	$ECHO "Leaving TFA_HOME in tact due to -debug flag: $tfa_home...";
  else
    	# Remove init.tfa
    	if [ -f "$ID/init.tfa" ]
    	then
  		$ECHO "Removing $ID/init.tfa...";
    		$RM -f $ID/init.tfa
    	fi

	# Remove TFA Log Directory
    	if [ -d "$LOG_DIR" ]
    	then
		$ECHO "Removing $LOG_DIR...";
		$RM -rf $LOG_DIR;
    	fi

	# Remove Shared File 
	if [ -n "$SHARED_FILE" ] && [ -f "$SHARED_FILE" ]
	then
		$ECHO "Removing $SHARED_FILE...";
		$RM -rf $SHARED_FILE;
	fi

	# Remove BDB in ORACLE_BASE
	if [ -n "$BDB_DIR" ] && [ -d "$BDB_DIR" ]
	then
		$ECHO "Removing $BDB_DIR...";
		$RM -rf $BDB_DIR;
	fi

	# Remove Output Directory in ORACLE_BASE
	if [ -n "$OUT_DIR" ] && [ -d "$OUT_DIR" ]
	then
		$ECHO "Removing $OUT_DIR...";
		$RM -rf $OUT_DIR;
	fi

	# Remove <ORACLE_BASE>/tfa/<NODE>
	if [ -n "$CRS_HOME" ]
	then
		OB_TFA="$ORACLE_BASE/tfa/$HOSTNAME";

		if [ -d "$OB_TFA" ]
		then
			$ECHO "Removing $OB_TFA...";
			$RM -rf $OB_TFA;
		fi
	fi

	# Remove TFA_HOME
    	if [ -d "$tfa_home" ]
    	then
  		$ECHO "Removing TFA_HOME $tfa_home...";
  		$RM -rf tfa_home/
    	fi

	# Remove TFA_BASE/HOSTNAME
    	if [ -d "$BASEDIR/$HOSTNAME" ]
    	then
		$ECHO "Removing $BASEDIR/$HOSTNAME...";
		$RM -rf $BASEDIR/$HOSTNAME
    	fi
  fi

  # Remove repository if its empty.
  if [ -n "$CRSHOME" ]
  then
	if [ -n "$ORACLE_BASE" ]
	then
		REPO_DIR="$ORACLE_BASE/tfa/repository";
	else
		if [ -f "$tfa_base/ora_stack_status.out" ]
		then
			ORACLE_BASE=`cat $tfa_base/ora_stack_status.out | grep "^ORACLE_BASE" | awk -F"=" '{ print $2 }'`
			REPO_DIR="$ORACLE_BASE/tfa/repository";
		fi
	fi
  elif [ -f "/opt/oracle/oak/bin/oakcli" ]
  then
	REPO_DIR="$tfa_home/repository";
  else
	REPO_DIR="$BASEDIR/repository";
  fi

  if [ -d "$REPO_DIR" ]
  then
	if [ "$($LS -A $REPO_DIR)" ]; then
		$ECHO "Repository[$REPO_DIR] is not Empty to delete.";
	else
		$ECHO "Removing Repository $REPO_DIR";
		$RM -rf $REPO_DIR;
	fi
  fi 
fi

$RM -f $ZFILE
$RM -f $tfa_home/tfa_install*
$RM -f $tfa_home/tfahome_full.tar

$ECHO "";

exit $EXIT_STATUS

__ARCHIVE_BELOW__
