#!/bin/ksh

trap 2

#######################################################################################
#
# Patch unique env vars...
#

PATCHID="118952-21"
VERSION="PS6.3.1p21"
rel_ver="25.21"

#######################################################################################

last_rel=""
LOG=/dev/stdout # /dev/null or /dev/stdout

#######################################################################################
#
# Static ENV vars
#
SED=/bin/sed
GREP=/bin/grep
EGREP=/bin/egrep
UNIQ=/usr/bin/uniq
ECHO=/bin/echo
MV=/bin/mv
CP=/bin/cp
DATE=/bin/date
CHOWN=/bin/chown
CHMOD=/bin/chmod
RM=/bin/rm
MKDIR=/bin/mkdir

PWD=$(pwd)
PATCHREV=`$ECHO ${PATCHID} | /usr/bin/awk ' BEGIN { FS="-" } {print $2 } '`
PATCHBASE=`$ECHO ${PATCHID} | /usr/bin/awk ' BEGIN { FS="-" } {print $1 }'`
ISSERVER="N"
ISGATEWAY="N"
ISRPROXY="N"
ISNPROXY="N"
PREFIX="/opt/sun"
PROD_DIR="portal"

# Get value of a key in a flatfile and assign it to ANSWER
$ECHO " PrePatch Processing ..."
GrabConfig() {
  local FILE=$1
  local KEY=$2
  local SEPARATOR=$3

  ANSWER=`$GREP "^$KEY$SEPARATOR" $FILE | $UNIQ | $SED -e "s/$KEY$SEPARATOR//"`
}


#########################################################################################
#
# preinstall processing
#
#

rpm -qa | $GREP sun-portal-core-6.3 > /dev/null 2>&1
if [ $? -eq 0 ]; then

  ISSERVER="Y" 

  PS_STATE_FILE="/etc/opt/sun/portal/PSConfig.properties"
  if [ ! -f $PS_STATE_FILE ]; then
    $ECHO "Error: $PS_STATE_FILE does not exist. "
    exit 1
  fi

  GrabConfig $PS_STATE_FILE "BASEDIR" "="
  if [ "$ANSWER" != "" ]; then
     PS_INSTALL_DIR=$ANSWER
  else
     $ECHO "Error: Cannot determine BASEDIR. "
     exit 1
  fi

  GrabConfig $PS_STATE_FILE "IDSAME_BASEDIR" "="
  if [ "$ANSWER" != "" ]; then
     IS_INSTALL_DIR=$ANSWER
  else
     $ECHO "Error: Cannot determine IDSAME_BASEDIR. "
     exit 1
  fi

  GrabConfig $PS_STATE_FILE "DEPLOY_TYPE" "="
  if [ "$ANSWER" != "" ]; then
    DEPLOY_TYPE=$ANSWER
  else
    $ECHO "Warning: Cannot determine DEPLOY_TYPE. "
  fi

  DEPLOY=$PS_INSTALL_DIR/portal/bin/deploy

  GrabConfig $PS_INSTALL_DIR/portal/lib/PSversion.properties "productversion" "="
  if [ "$ANSWER" != "6.3.1" ]
  then
    $ECHO "This patch is compatible with:"
    $ECHO '"'Sun Java System Portal Server 6 2005Q1'"'
    $ECHO "or later versions."
    $ECHO "This patch is not compatible with the current installation."
    exit 1
  fi

  $ECHO ""
  $ECHO "To complete the patch install, you must deploy"
  $ECHO "the updated web application using:"
  $ECHO "# $DEPLOY redeploy"
  $ECHO "and then restart your web container instances."
  $ECHO ""

  if [ $DEPLOY_TYPE="IWS" ]; then

      GrabConfig $PS_STATE_FILE "DEPLOY_INSTANCE" "="
      if [ "$ANSWER" != "" ]; then
        DEPLOY_INSTANCE=$ANSWER
      else
        $ECHO "Warning: Cannot determine DEPLOY_INSTANCE. $BELL_CHAR"
        DEPLOY_INSTANCE="<deploy-instance>"
      fi

      GrabConfig $PS_STATE_FILE "DEPLOY_URI" "="
      if [ "$ANSWER" != "" ]; then
        DEPLOY_URI=$ANSWER
      else
        $ECHO "Warning: Cannot determine DEPLOY_URI. $BELL_CHAR"
        DEPLOY_URI="<deploy-uri>"
      fi

      $ECHO "WARNING: The deploy command redeploys content from $PS_INSTALL_DIR/portal/web-src"
      $ECHO "to /var/opt/sun/portal/https-$DEPLOY_INSTANCE$DEPLOY_URI/web-apps"
      $ECHO "Any customisations to the Portal web application should always be made"
      $ECHO "to web-src and then deployed to web-apps. Ensure that any changes you"
      $ECHO "have made under web-apps have been replicated in web-src before"
      $ECHO "running deploy, or they will be lost."
      $ECHO ""
  fi
fi # end of checking for core package

rpm -qa | $GREP sun-portal-gateway-6.3 > /dev/null 2>&1
if [ $? -eq 0 ]; then
  ISGATEWAY="Y"
  GW_STATE_FILE="/etc/opt/sun/portal/GWConfig.properties"
  if [ ! -f $GW_STATE_FILE ]; then
    $ECHO "Error: $GW_STATE_FILE does not exist. "
    exit 1
  fi

  GrabConfig $GW_STATE_FILE "GW_BASEDIR" "="
  if [ "$ANSWER" != "" ]; then
     GW_INSTALL_DIR=$ANSWER
  else
     $ECHO "Error: Cannot determine BASEDIR. "
     exit 1
  fi

  GrabConfig $GW_STATE_FILE "IDSAME_BASEDIR" "="
  if [ "$ANSWER" != "" ]; then
     IS_INSTALL_DIR=$ANSWER
  else
     $ECHO "Error: Cannot determine IDSAME_BASEDIR. "
     exit 1
  fi

  GrabConfig $GW_INSTALL_DIR/portal/lib/SRAversion.properties "productversion" "="
  if [ "$ANSWER" == "" ]
  then
    GrabConfig $GW_INSTALL_DIR/portal/lib/SRAversion.properties "version" "="
  fi
  if [ "$ANSWER" != "6.3.1" ]
  then
    $ECHO "This patch is compatible with:"
    $ECHO '"'Sun Java System Portal Server Secure Remote Access 6 2005Q1'"'
    $ECHO "or later versions."
    $ECHO "This patch is not compatible with the current installation."
    exit 1
  fi
fi # end of checking for gateway package

rpm -qa | $GREP sun-portal-rewriterproxy-6.3 > /dev/null 2>&1
if [ $? -eq 0 ]; then
    ISRPROXY="Y"
    RWP_STATE_FILE="/etc/opt/sun/portal/RWPConfig.properties"
    if [ ! -f $RWP_STATE_FILE ]; then
	$ECHO "Error: $RWP_STATE_FILE does not exist. "
    exit 1
  fi

   GrabConfig $RWP_STATE_FILE "RWP_BASEDIR" "="
   if [ "$ANSWER" != "" ]; then
	RWP_INSTALL_DIR=$ANSWER
   else
     $ECHO "Error: Cannot determine BASEDIR. "
     exit 1
  fi

  GrabConfig $RWP_STATE_FILE "IDSAME_BASEDIR" "="
  if [ "$ANSWER" != "" ]; then
     IS_INSTALL_DIR=$ANSWER
  else
     $ECHO "Error: Cannot determine IDSAME_BASEDIR. "
     exit 1
  fi

  GrabConfig $RWP_INSTALL_DIR/portal/lib/SRAversion.properties "productversion" "="
  if [ "$ANSWER" == "" ]
  then
    GrabConfig $RWP_INSTALL_DIR/portal/lib/SRAversion.properties "version" "="
  fi
  if [ "$ANSWER" != "6.3.1" ]
  then
    $ECHO "This patch is compatible with:"
    $ECHO '"'Sun Java System Portal Server Secure Remote Access 6 2005Q1'"'
    $ECHO "or later versions."
    $ECHO "This patch is not compatible with the current installation."
    exit 1
  fi
fi

rpm -qa | $GREP sun-portal-netletproxy-6.3 > /dev/null 2>&1
if [ $? -eq 0 ]; then
    ISNPROXY="Y"
    NLP_STATE_FILE="/etc/opt/sun/portal/NLPConfig.properties"
    if [ ! -f $NLP_STATE_FILE ]; then
        $ECHO "Error: $NLP_STATE_FILE does not exist. "
    exit 1
  fi

   GrabConfig $NLP_STATE_FILE "NLP_BASEDIR" "="
   if [ "$ANSWER" != "" ]; then
        NLP_INSTALL_DIR=$ANSWER
   else
     $ECHO "Error: Cannot determine BASEDIR. "
     exit 1
  fi

  GrabConfig $NLP_STATE_FILE "IDSAME_BASEDIR" "="
  if [ "$ANSWER" != "" ]; then
     IS_INSTALL_DIR=$ANSWER
  else
     $ECHO "Error: Cannot determine IDSAME_BASEDIR. "
     exit 1
  fi

  GrabConfig $NLP_INSTALL_DIR/portal/lib/SRAversion.properties "productversion" "="
  if [ "$ANSWER" == "" ]
  then
    GrabConfig $NLP_INSTALL_DIR/portal/lib/SRAversion.properties "version" "="
  fi
  if [ "$ANSWER" != "6.3.1" ]
  then
    $ECHO "This patch is compatible with:"
    $ECHO '"'Sun Java System Portal Server Secure Remote Access 6 2005Q1'"'
    $ECHO "or later versions."
    $ECHO "This patch is not compatible with the current installation."
    exit 1
  fi
fi


#######################################################################################
#
# Util functions
#

updateVersionString() {
    VERSION="$VERSION,`$DATE`"
    rpm -qa | $GREP sun-portal-core-6.3 > /dev/null 2>&1
    if [ $? = 0 ]; then
      VERSION_FILE=$PS_INSTALL_DIR/portal/lib/PSversion.properties
      $ECHO "patch=$PATCHID,$VERSION" >> $VERSION_FILE
    fi
    rpm -qa | $GREP sun-portal-gateway-6.3 > /dev/null 2>&1
    if [ $? = 0 ]; then
      VERSION_FILE=$GW_INSTALL_DIR/portal/lib/SRAversion.properties
      $ECHO "patch=$PATCHID,$VERSION" >> $VERSION_FILE
    fi
}

replace_line() {
  file=$1
  match=$2
  new=$3

  #$CP $file $file-orig-$$
  sed -e "
/$match/ {
c\\
$new
}" $file > $file-tmp
mv $file-tmp $file
}

insert_line() {
  file=$1
  match=$2
  new=$3
                                                                                                                                                   
  #$CP $file $file-orig-$$
  sed -e "
/$match/ {
i\\
$new
}" $file > $file-tmp
mv $file-tmp $file
}

replace_script_install_vars() {
  BASE_DIR=$1
  SCRIPTNAME=$2
  STARTFILE=$BASE_DIR/$PROD_DIR/bin/$SCRIPTNAME

  $SED -e "s#\${BASE_DIR}#$BASE_DIR#g" \
       -e "s#\${PRODUCT_DIR}#$PROD_DIR#g" \
       -e "s#\${IDSAME_BASE_DIR}#$IS_INSTALL_DIR#g" $STARTFILE > $STARTFILE.$PATCHID.tmp

  $MV $STARTFILE.$PATCHID.tmp $STARTFILE
  $CHMOD 755 $STARTFILE
  $CP $STARTFILE /etc/init.d/$SCRIPTNAME

  $ECHO 
  $ECHO "WARNING: A new $SCRIPTNAME start script has been"
  $ECHO "installed in $BASE_DIR/$PROD_DIR/bin"
  $ECHO "You will need to reapply any changes or"
  $ECHO "tuning you previously made to this script."
  $ECHO "A copy of your old start script has been retained"
  $ECHO "for your reference as $STARTFILE.rpmsave"
  $ECHO 
}

replace_sra_install_vars() {
  if [ "$ISGATEWAY" == "Y" ]; then
    replace_script_install_vars $GW_INSTALL_DIR gateway
  fi

  # Not yet needed
  #if [ "$ISRPROXY" == "Y" ]; then
  #  replace_script_install_vars $RWP_INSTALL_DIR rwproxyd
  #fi
  #
  #if [ "$ISNPROXY" == "Y" ]; then
  #  replace_script_install_vars $NLP_INSTALL_DIR netletd
  #fi
}

#######################################################################################
#
# Installing RPM
#

updateRPMs() {

  ## first see if the patch was ever applied before by checking if backup directory is present
  ## if the backup directory is present dont backup new files else back them up

  BACKDIR=/var/spool/backup/$PATCHID
  if [ -d $BACKDIR ]; then
        ## get the prefix to use for updating the rpms because it can be installed in
        ## non default location

        if [ "$ISSERVER" == "Y" ]; then
                PREFIX=$PS_INSTALL_DIR
        elif [ "$ISGATEWAY" == "Y" ]; then
                PREFIX=$GW_INSTALL_DIR
        elif [ "$ISRPROXY" == "Y" ]; then
                PREFIX=$RWP_INSTALL_DIR
        elif [ "$ISNPROXY" == "Y" ]; then
                PREFIX=$NLP_INSTALL_DIR
        fi
        echo "Using Prefix $PREFIX"

        ## upgrade rpms without backing up
        ## update rpm only if it is already present on the system

        for eaRPM in `ls $PWD | grep ".rpm"`
        do
                rpmname=`$ECHO $eaRPM | cut -d - -f-3`;
                rpm -q $rpmname >/dev/null 2>&1 ;
                if [ $? = 0 ]; then
                        $ECHO "Updating  $eaRPM ...."
			## do not relocate rpm that ship config files under /etc/opt
                        echo $eaRPM|$EGREP -q 'sun-.*-config-'
                        if [ "$?" \!= 0 ]; then
                                #rpm -Uvh --repackage --replacefiles --relocate /opt/sun=$PREFIX $eaRPM
                                rpm -Uvh --force --relocate /opt/sun=$PREFIX $eaRPM
                        else
                                #rpm -Uvh --repackage --replacefiles $eaRPM
                                rpm -Uvh --force $eaRPM
                        fi

                fi
        done

  else

	## first check if macros file  is present and has repackage directory specified
        FILE="/usr/lib/rpm/macros"
        FILECHECK=n;
        if [ -f $FILE ]; then
                 FILECHECK=y;
                 $CP $FILE $FILE.pre$PATCHBASE-$PATCHREV
                 $GREP -i "repackage_dir" $FILE >> /dev/null
                 if [ $? = 0 ]; then
                        replace_line $FILE "%_repackage_dir" "%_repackage_dir         /var/spool/backup/$PATCHID"
                 else
                        $ECHO  "%_repackage_dir         /var/spool/backup/$PATCHID" >> $FILE
                 fi
		 $CHMOD 755 $FILE
		 $RM -fr /var/spool/backup/$PATCHID
		 $MKDIR -p /var/spool/backup/$PATCHID
        else
                $ECHO ""
                $ECHO ""
                $ECHO "   /usr/lib/rpm/macros cannot be found"
                $ECHO "   It is needed for valid backup "
                $ECHO "   Do you want to continue without backup"
                $ECHO "   If you Continue, patch cannot be backed out"
                $ECHO ""
                $ECHO "     [C]ontinue       [Q]uit"
                read ans
                if [ $ans = 'q' ] || [ $ans = 'Q' ]; then
                        $ECHO "Exitting patch install"
                        exit 1;
                fi
                if [ $ans = 'c'  ] || [ $ans = 'C' ]; then
                        $ECHO
                else
                        while [ $ans ]
                        do
                                $ECHO "Answer not understood"
                                $ECHO "  \n\t[C]ontinue\t\t[Q]uit"
                                read ans
                                if [ $ans = 'q' ] || [ $ans = 'Q' ]; then
                                        $ECHO "Exitting patch install..."
                                        exit 1;
                                fi
                                if [ $ans = 'c'  ] || [ $ans = 'C' ]; then
                                 break
                                fi
                        done
                fi
        fi
	## get the prefix to use for updating the rpms because it can be installed in 
        ## non default location
	
        if [ "$ISSERVER" == "Y" ]; then
                PREFIX=$PS_INSTALL_DIR
        elif [ "$ISGATEWAY" == "Y" ]; then
                PREFIX=$GW_INSTALL_DIR
        elif [ "$ISRPROXY" == "Y" ]; then
                PREFIX=$RWP_INSTALL_DIR
        elif [ "$ISNPROXY" == "Y" ]; then
                PREFIX=$NLP_INSTALL_DIR
        fi
	echo "Using Prefix $PREFIX"
        ### update rpms by keeping valid backup
        ## update rpm only if it is already present on the system
       
        for eaRPM in `ls $PWD | grep ".rpm"`
        do
                rpmname=`$ECHO $eaRPM | cut -d - -f-3`;
                rpm -q $rpmname >/dev/null 2>&1 ;
                if [ $? = 0 ]; then
                        $ECHO "Updating  $eaRPM ...."
			## do not relocate rpm that ship config files under /etc/opt
                        echo $eaRPM|$EGREP -q 'sun-.*-config-'
                        if [ "$?" \!= 0 ]; then
                        	#rpm -Uvh --repackage --replacefiles --relocate /opt/sun=$PREFIX $eaRPM
                                rpm -Uvh --repackage --force --relocate /opt/sun=$PREFIX $eaRPM
			else
				#rpm -Uvh --repackage --replacefiles $eaRPM
                                rpm -Uvh --repackage --force $eaRPM
			fi
                fi
        done

        ### restore the original macrosfile
        if [ "$FILECHECK" = "y" ]; then
               $CP $FILE.pre$PATCHID $FILE
	       $CHMOD 755 $FILE
        fi
 fi

}

###############################################################################################
#
# postinstall utiltity
#


# function call_rev_mods() calls rev_mods for every revision between the current
#   revision on the system, and the revision of the rpm to be installed

call_rev_mods() {
  typeset -i patch_rev=$1
  typeset -i cur_rev=$2


  while (($cur_rev < $patch_rev))
  do
    ((cur_rev=$cur_rev + 1))
    rev_mods $cur_rev;
  done
}

######################################################################################
#
# rev_mods handles all profile updates file manipulation and anything else which may
#   be required by the patch itself. 
#

rev_mods() {
typeset -i rev=$1

if [[ $rev == 1 ]]
then
#########Make changes for Rev01 here###########
echo "Making changes for $PATCHBASE-01..."

elif [[ $rev == 2 ]]
then
#########Make changes for Rev02 here###########
echo "Making changes for $PATCHBASE-02..."

elif [[ $rev == 3 ]]
then
#########Make changes for Rev03 here###########
echo "Making changes for $PATCHBASE-03..."

elif [[ $rev == 4 ]]
then
#########Make changes for Rev04 here###########
echo "Making changes for $PATCHBASE-04..."

elif [[ $rev == 5 ]]
then
#########Make changes for Rev05 here###########
echo "Making changes for $PATCHBASE-05..."

fi ## end of big if block

}

## get the last rev on the system before upgrading the rpms
setlastrev() {

        if [ "$ISSERVER" == "Y" ]; then
                last_rel=`rpm -qa sun-portal-core | cut -d - -f5 `
                last_rev=` echo "$last_rel." | cut -d . -f2`
        elif [ "$ISGATEWAY" == "Y" ]; then
                last_rel=`rpm -qa sun-portal-gateway | cut -d - -f5 `
                last_rev=` echo "$last_rel." | cut -d . -f2`
        elif [ "$ISRPROXY" == "Y" ]; then
                last_rel=`rpm -qa sun-portal-rewriterproxy | cut -d - -f5`
                last_rev=`echo "$last_rel." | cut -d . -f2`
        elif [ "$ISNPROXY" == "Y" ]; then
                last_rel=`rpm -qa sun-portal-netletproxy | cut -d - -f5`
                last_rev=`echo "$last_rel." | cut -d . -f2`
        fi
        if [ "$last_rev" == "" ]; then
                last_rev=0;
	fi
}


postinstall() {
	##  get the last version install
	patch_rev=`echo $rel_ver | cut -d . -f2`;
        typeset -i last_rev=$last_rev;

	call_rev_mods $patch_rev $last_rev
}

# Restarting stand-alone processes
restart_processes() {
	if [ "$ISGATEWAY" == "Y" ]; then
		$GW_INSTALL_DIR/$PROD_DIR/bin/gateway start
	fi

	if [ "$ISNPROXY" == "Y" ]; then
		$NLP_INSTALL_DIR/$PROD_DIR/bin/netletd start
	fi

	if [ "$ISRPROXY" == "Y" ]; then
		$RWP_INSTALL_DIR/$PROD_DIR/bin/rwproxyd start
	fi
}

#######################################################################################
#
# Main processing
#
setlastrev
updateRPMs
postinstall
replace_sra_install_vars
updateVersionString
restart_processes

trap ''
