#!/bin/ksh 
# Copyright 10/15/2002 Sun Microsystems, Inc. All Rights Reserved.

trap 2

###############################################
# ENV vars which need to be modified
###############################################
PATCHID="116411-02"
VERSION="PS6.1PC2"
#set -x


###############################################
# Static ENV vars 
###############################################
ECHO=/usr/bin/echo
GREP=/usr/bin/grep
PKGINFO=/usr/bin/pkginfo
SED=/usr/bin/sed
CP=/usr/bin/cp
RM=/usr/bin/rm
MV=/usr/bin/mv
LS=/usr/bin/ls
CAT=/usr/bin/cat
CHOWN=/usr/bin/chown
CHMOD=/usr/bin/chmod
AWK=/usr/bin/awk
NAWK=/usr/bin/nawk
FIND=/usr/bin/find
OMIT_CHAR='\c'
BELL_CHAR='\a'
STTY=/usr/bin/stty
pkginfo -q SUNWps
if [ $? -eq 0 ]; then
  INSTALL_DIR=`$GREP "BASEDIR=" /var/sadm/pkg/SUNWps/pkginfo | $GREP -v DEPLOY | $GREP -v IDSAME | $AWK ' BEGIN { FS="=" } { print $2 }`
  DEPLOY_URI=`$GREP "DEPLOY_URI=" /var/sadm/pkg/SUNWps/pkginfo | $AWK ' BEGIN { FS="=" } { print $2 }`
  DEPLOY_DOMAIN=`$GREP "DEPLOY_DOMAIN=" /var/sadm/pkg/SUNWps/pkginfo | $AWK ' BEGIN { FS="=" } { print $2 }`
  DEPLOY_INSTANCE=`$GREP "DEPLOY_INSTANCE=" /var/sadm/pkg/SUNWps/pkginfo | $AWK ' BEGIN { FS="=" } { print $2 }`
  DEPLOY_TYPE=`$GREP "DEPLOY_TYPE=" /var/sadm/pkg/SUNWps/pkginfo | $AWK ' BEGIN { FS="=" } { print $2 }`
fi
pkginfo -q SUNWpsgw
if [ $? -eq 0 ]; then
  INSTALL_DIR=`$GREP "SRAP_BASEDIR=" /var/sadm/pkg/SUNWpsgw/pkginfo | $AWK ' BEGIN { FS="=" } { print $2 }`
fi
pkginfo -q SUNWamdsc
if [ $? -eq 0 ]; then
  LOCAL_DIR=1
fi
PATCHREV=`$ECHO ${PATCHID} | $AWK ' BEGIN { FS="-" } {print $2}`
PATCHBASE=`$ECHO ${PATCHID} | $AWK ' BEGIN { FS="-" } {print $1}`


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

updateVersionString() {
  VERSION_FILE=$INSTALL_DIR/SUNWps/lib/PSversion.properties
  VERSION="$VERSION,`/usr/bin/date`"
  if [ -f $VERSION_FILE ]; then
    $ECHO "patch=$PATCHID,$VERSION" >> $VERSION_FILE
  fi
  VERSION_FILE2=$INSTALL_DIR/SUNWps/lib/SRAversion.properties
  if [ -f $VERSION_FILE2 ]; then
    $ECHO "patch=$PATCHID,$VERSION" >> $VERSION_FILE2
  fi
}

redeploy() {
$ECHO "Backing up and redeploying Portal web service with updated files..."
if [ $DEPLOY_TYPE = "IWS" ]; then
  for INSTANCE in `$LS $INSTALL_DIR/SUNWps/web-apps | $GREP https- | $GREP -v pre`
  do
    $CP -R $INSTALL_DIR/SUNWps/web-apps/$INSTANCE $INSTALL_DIR/SUNWps/web-apps/$INSTANCE.pre$PATCHID
  done
  DONE="n"
  if (($LOCAL_DIR)); then
    GUESS_FILE=$INSTALL_DIR/SUNWam/bin/ammultiserverinstall
    if [ -f $GUESS_FILE ]; then
      DIRBASE=`$GREP "DIRBASE" $INSTALL_DIR/SUNWam/bin/ammultiserverinstall | cut -d "=" -f2 | sed -e "s/\"//g"`
      GUESS=`$GREP "siepid:" $DIRBASE/admin-serv/config/adm.conf | cut -d ":" -f2 | sed -e "s/ //g"`
      $INSTALL_DIR/SUNWps/bin/deploy redeploy -is_admin_password "$GUESS"
    else
      while [ "$DONE" = "n" ]; do
      $ECHO
      $ECHO "Please enter Identity Server Administration Password: "
      $STTY -echo
      read ANSWER
      $STTY echo
      if [ "$ANSWER" != "" ]; then
        print "Again? $OMIT_CHAR"
        $STTY -echo
        read ANSWER_REPEAT
        $STTY echo
        print ""
        if [ "$ANSWER" != "$ANSWER_REPEAT" ]; then
          print "Password verification failed! $BELL_CHAR"
        else
          DONE="y"
        fi
      fi
    done
    $INSTALL_DIR/SUNWps/bin/deploy redeploy -is_admin_password "$ANSWER" 
    if [ $? != 0 ]; then
      $ECHO "Redeploy failed."  
      $ECHO "You will need to run again manually using $INSTALL_DIR/SUNWps/bin/deploy redeploy -is_admin_password <password>"
    fi
    fi
  fi
elif [ $DEPLOY_TYPE = "SUNONE" ]; then
  $CP -R $DEPLOY_DOMAIN $DEPLOY_DOMAIN.pre$PATCHID
  DONE="n"
  while [ "$DONE" = "n" ]; do
    $ECHO
    $ECHO "Please enter Deploy Administration Password: "
    $STTY -echo
    read ANSWER
    $STTY echo
    if [ "$ANSWER" != "" ]; then
      print "Again? $OMIT_CHAR"
      $STTY -echo
      read ANSWER_REPEAT
      $STTY echo
      print ""
      if [ "$ANSWER" != "$ANSWER_REPEAT" ]; then
        print "Password verification failed! $BELL_CHAR"
      else
        DONE="y"
      fi
    fi
  done
  $INSTALL_DIR/SUNWps/bin/deploy redeploy -deploy_admin_password "$ANSWER" -is_admin_password "foobar"
else
  $ECHO "Unsupported or unknown DEPLOY TYPE: $DEPLOY_TYPE..."
fi

}

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

  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
rm $file-orig-$$
}



###############################################
# Helper functions specific to handling previous patch revisions
###############################################

# function sort_arr sorts an array lexicographically and writes a global val 
# NEW_ARR with the results

sort_arr() {
  set -s
  set -A NEW_ARR $*
}

# rev_mods handles all profile updates file manipulation and anything else 
# which may be required by the patch itself. rev_mods is the workhorse of the 
# patch ins tall script.

rev_mods() {
  typeset -i rev=$1

  if [[ $rev == 1 ]]
  then
    $ECHO "Making changes for $PATCHBASE-01..."
    #==============================================
    #
    # REV01
    # Change version logic to maintain historical
    # patch applications 
    #
    #==============================================
    GWSTARTFILE=/etc/init.d/gateway
    if [ -f $GWSTARTFILE ]; then
      $ECHO "Updating gateway start file to handle new version subcommand logic..."
      $CP $GWSTARTFILE $GWSTARTFILE.pre$PATCHID
      /usr/bin/sed -n -e '1,/echo \"\$BUILD $ANSWER\"/p' $GWSTARTFILE > /var/tmp/version.top
      /usr/bin/sed '$d' /var/tmp/version.top > /var/tmp/version.tmp
      /usr/bin/mv /var/tmp/version.tmp /var/tmp/version.top
      /usr/bin/cat <<EOF > /var/tmp/version.new
	PRODUCTVERSION=\$ANSWER
	GrabConfig \$VERSIONFILE "patch" "="
	echo "\$BUILD \$PRODUCTVERSION"
	echo "\$ANSWER"
EOF
      /usr/bin/sed -n -e '/"\$BUILD $ANSWER\"/,$p' $GWSTARTFILE > /var/tmp/version.bottom
      /usr/bin/sed '1d' /var/tmp/version.bottom > /var/tmp/version.tmp
      /usr/bin/mv /var/tmp/version.tmp /var/tmp/version.bottom
      cat /var/tmp/version.top /var/tmp/version.new /var/tmp/version.bottom > $GWSTARTFILE
      #Fix for BugID #4970128
      insert_line $GWSTARTFILE "PLATFORM_CONF=" "PLATFORM_DIR=/etc/opt/SUNWps"
      insert_line $GWSTARTFILE "for x in \$PLATFORM_CONF" "    for x in \`ls \$PLATFORM_DIR | grep \"platform\\\.conf\\\.\" | grep -v pre\`; do"
      replace_line $GWSTARTFILE "for x in \$PLATFORM_CONF" "    x=\$PLATFORM_DIR/\$x"
      # end of fix for BugID #4907018 
      if [ -f $INSTALL_DIR/SUNWps/bin/gateway ]; then
        $CP $INSTALL_DIR/SUNWps/bin/gateway $INSTALL_DIR/SUNWps/bin/gateway.pre$PATCHID
        $CP $GWSTARTFILE $INSTALL_DIR/SUNWps/bin/gateway 
        $CHMOD 755 $INSTALL_DIR/SUNWps/bin/gateway
      fi
      /usr/bin/rm /var/tmp/version.top /var/tmp/version.new /var/tmp/version.bottom
      $CHMOD 755 $GWSTARTFILE
    fi
    VERSIONSCRIPT=$INSTALL_DIR/SUNWps/bin/version
    if [ -f $VERSIONSCRIPT ]; then
      $ECHO "Updating version script to handle new version subcommand logic..."
      $CP $VERSIONSCRIPT $VERSIONSCRIPT.pre$PATCHID
      /usr/bin/sed -n -e '1,/\$ECHO \$BUILD \$ANSWER/p' $VERSIONSCRIPT > /var/tmp/version.top
      /usr/bin/sed '$d' /var/tmp/version.top > /var/tmp/version.tmp
      /usr/bin/mv /var/tmp/version.tmp /var/tmp/version.top
      /usr/bin/cat <<EOF > /var/tmp/version.new
  	PRODUCTVERSION=\$ANSWER
  	GrabConfig \$VERSION_FILE "patch" "="
  	echo "\$BUILD \$PRODUCTVERSION"
  	echo "\$ANSWER"
EOF
  	/usr/bin/sed -n -e '/\$ECHO \$BUILD \$ANSWER/,$p' $VERSIONSCRIPT > /var/tmp/version.bottom
  	/usr/bin/sed '1d' /var/tmp/version.bottom > /var/tmp/version.tmp
  	/usr/bin/mv /var/tmp/version.tmp /var/tmp/version.bottom
  	cat /var/tmp/version.top /var/tmp/version.new /var/tmp/version.bottom > $VERSIONSCRIPT
  	/usr/bin/rm /var/tmp/version.top /var/tmp/version.new /var/tmp/version.bottom
    fi
    #==============================================
    #
    # REV01
    # Add platform.conf entries for BugID #4841043,
    # #4880860
    #
    # Remove unsightly blank lines
    #
    #==============================================
    PLATFORMFILE=/etc/opt/SUNWps/platform.conf.default
    if [ -f $PLATFORMFILE ]; then
      $ECHO "Adding new entries to platform.conf..."
      for files in `ls /etc/opt/SUNWps/platform.conf* | grep -v platform.conf-orig | grep -v platform.conf.pre` 
      do
        /usr/bin/cp $files $files.pre$PATCHID
        /usr/bin/grep "gateway.min_auth_level" $files > /dev/null 2>&1
        if [ $? -ne 0 ]; then
          $ECHO "gateway.min_auth_level=0" >> $files
        fi
        /usr/bin/grep "gateway.rewriter.ignorecl" $files > /dev/null 2>&1
        if [ $? -ne 0 ]; then
          $ECHO "gateway.rewriter.ignorecl=false" >> $files
        fi
        /usr/bin/sed '/^$/d' $files > $files.no_blank_lines
        /usr/bin/mv $files.no_blank_lines $files
        /usr/bin/chmod 644 $files $files.pre$PATCHID
      done
    fi
    #==============================================
    #
    # REV01
    # Add additional entry to srapGateway.properties
    # for BugID #4880860 
    #
    #==============================================
    PROPFILE=$INSTALL_DIR/SUNWps/locale/srapGateway.properties
    if [ -f $PROPFILE ]; then
      /usr/bin/grep "IOErrorMessage" $PROPFILE
      if [ $? -ne 0 ]; then
        /usr/bin/cp $PROPFILE $PROPFILE.pre$PATCHID
        /usr/bin/chmod 644 $PROPFILE.pre$PATCHID
        insert_line $PROPFILE "UnSupportedEncodingWarningMessage" "IOErrorMessage=<html><head><title>Rewriter:IOException</title></head><body>Rewriter could not retrieve content from remote server. <br/> Please contact your administrator.</body></html>"
      fi
    fi


  elif [[ $rev == 2 ]]
  then
    $ECHO "Making changes for $PATCHBASE-02..."
  elif [[ $rev == 3 ]]
  then
    $ECHO "Making changes for $PATCHBASE-03..."
  else
    $ECHO "$rev: Unrecognized version number for patch base - $PATCHBASE"
  fi
}

# function call_rev_mods() calls rev_mods for every revision between the 
# current revision on the system, and the revision of the patch 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
}

# Check for previous patch revisions. If there are not any, then continue with
# profile updates and flatfile manipulation. For more than one patch revision,
# use a nother 'if' block so that the statements are not executed multiple 
# times. Check for the highest rev first, and then only make changes from it
# to the current rev.
#    EX:  PATCHREV=04
#         if 03, then only apply changes for 04
#         if 02, then apply changes for 03, and 04
#         if 01, then apply changes for 02, 03, and 04
#         else, just apply changes for 04
#   
# Note: These steps are necessary for the cummulative patch process to work
# correctly
# Function check_patch_revs checks for the existence of previous patch 
# revisions for the current patch being installed.

check_patch_revs() {

  $ECHO "Checking for previous patch revisions..."

  # First get highest rev for the patch
  set -A CURRENT_REVS `showrev -p | $NAWK ' { print substr($0, match($0,"Patch:")+7)} ' | \
  $SED 's/ Obsoletes:.*//g' | $GREP ${PATCHBASE} | $AWK ' BEGIN { FS="-" } {print $2} '`

  typeset -i NUM_REVS=${#CURRENT_REVS[*]}-1

  # Check case where there may be no patch revisions installed
  if [[ $NUM_REVS > 0 ]]
  then
    # Now sort it and get the highest rev currently installed
    sort_arr ${CURRENT_REVS[*]}

    HIGHEST_REV=${NEW_ARR[${NUM_REVS}-1]}

    call_rev_mods ${PATCHREV} ${HIGHEST_REV}
  else
    call_rev_mods ${PATCHREV} '00'
  fi
}


###############################################
# Main processing
###############################################

check_patch_revs
updateVersionString
pkginfo -q SUNWps
if [ $? -eq 0 ]; then
  redeploy
fi

###############################################
# Restart the Server
###############################################

pkginfo -q SUNWps
if [ $? -eq 0 ]; then
  $ECHO ""

  if [ $DEPLOY_TYPE = "IWS" ]; then
    $ECHO "Restarting SunONE Portal Server w/ original settings."
    /etc/init.d/amserver stop
    /etc/init.d/amserver start
  elif [ $DEPLOY_TYPE = "SUNONE" ]; then
    $ECHO "Restarting SunONE Portal Server on SunONE App Server instance $DEPLOY_INSTANCE w/ original settings."
    for INSTANCE in $INSTANCES
    do
      $ECHO
      $ECHO "Instance --- $INSTANCE"
      $DEPLOY_DOMAIN/$INSTANCE/bin/stopserv
      $DEPLOY_DOMAIN/$INSTANCE/bin/startserv
    done
  elif [ $DEPLOY_TYPE = "SUNONE" ]; then
    $ECHO "Do not know how to start yet!"
  else
    $ECHO "Do not know how to start yet!"
  fi

  $ECHO "Server restarted.  Please wait a moment before connecting to it."
fi


###############################################
# Restart the Gateway
###############################################

pkginfo -q SUNWpsgw
if [ $? -eq 0 ]; then
  $ECHO ""
  $ECHO "Restarting SunONE Portal Server Gateway w/ original settings."
  /etc/init.d/gateway stop
  /etc/init.d/gateway start
  $ECHO "Gateway restarted.  Please wait a moment before connecting to it."
fi


###############################################
# Done
###############################################
$ECHO ""
$ECHO "Postpatch processing complete."

trap ''
