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

trap 2

###############################################
# ENV vars which need to be modified
###############################################
PATCHID="116411-13"

###############################################
# 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
STTY=/usr/bin/stty

HAS_IDENTITY_SUPER_ADMIN_PASSWORD="n"

pkginfo -q SUNWps
if [ $? -eq 0 ]; then
  INSTALL_DIR=`$GREP "^BASEDIR=" /var/sadm/pkg/SUNWps/pkginfo | cut -d= -f2`
  DEPLOY_URI=`$GREP "^DEPLOY_URI=" /var/sadm/pkg/SUNWps/pkginfo | cut -d= -f2`
  DEPLOY_DOMAIN=`$GREP "^DEPLOY_DOMAIN=" /var/sadm/pkg/SUNWps/pkginfo | cut -d= -f2`
  DEPLOY_INSTANCE=`$GREP "^DEPLOY_INSTANCE=" /var/sadm/pkg/SUNWps/pkginfo | cut -d= -f2`
  DEPLOY_TYPE=`$GREP "^DEPLOY_TYPE=" /var/sadm/pkg/SUNWps/pkginfo | cut -d= -f2`
fi
pkginfo -q SUNWpsgw
if [ $? -eq 0 ]; then
  INSTALL_DIR=`$GREP "^SRAP_BASEDIR=" /var/sadm/pkg/SUNWpsgw/pkginfo | cut -d= -f2`
fi
pkginfo -q SUNWamsvc
if [ $? -eq 0 ]; then
  IS_INSTALL_DIR=`$GREP "^BASEDIR=" /var/sadm/pkg/SUNWamsvc/pkginfo | cut -d= -f2`
  BIND_DN=`$GREP "com.sun.identity.authentication.super.user" "$IS_INSTALL_DIR/SUNWam/lib/AMConfig.properties" | cut -d= -f2-`
fi
pkginfo -q SUNWamdsc
if [ $? -eq 0 ]; then
  LOCAL_DIR=1
fi
PATCHREV=`$ECHO ${PATCHID} | cut -d- -f2`
PATCHBASE=`$ECHO ${PATCHID} | cut -d- -f1`

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

restoreVersionString() {
  VERSION_FILE=$INSTALL_DIR/SUNWps/lib/PSversion.properties
  if [ -f $VERSION_FILE ]; then
    $ECHO "`$GREP -v $PATCHID $VERSION_FILE`" > $VERSION_FILE 
  fi
  VERSION_FILE2=$INSTALL_DIR/SUNWps/lib/SRAversion.properties
  if [ -f $VERSION_FILE2 ]; then
    $ECHO "`$GREP -v $PATCHID $VERSION_FILE2`" > $VERSION_FILE2
  fi
}

test_bind() {
  local PASSWD=$1
  `$INSTALL_DIR/SUNWps/bin/rwadmin list --runasdn "$BIND_DN" --password "$PASSWD" | $GREP -i "Authorization Failed" > /dev/null 2>&1`
  if [ $? -eq 0 ]; then
    $ECHO "Authentication failed for user $BIND_DN..."
    BIND_SUCCESS=n
  else
    BIND_SUCCESS=y
  fi
} # end of test_bind

GetIdentitySuperAdminPassword() {
BIND_SUCCESS="n"
typeset -i fail_count=0
while (( $fail_count < 3 )) && [ $BIND_SUCCESS = "n" ]
do
  DONE="n"
  while [ "$DONE" = "n" ]; do
    $ECHO
    $ECHO "Please Enter Identity Server Super Administrator Password: "
    $STTY -echo
    read PASSWORD
    $STTY echo
    if [ "$PASSWORD" != "" ]; then
	print "Again? $OMIT_CHAR"
	$STTY -echo
	read PASSWORD_REPEAT
	$STTY echo
	print ""
	if [ "$PASSWORD" != "$PASSWORD_REPEAT" ]; then
	print "Passwords do not match! $BELL_CHAR"
	else
	DONE="y"
	fi
    fi
  done
  test_bind $PASSWORD
  ((fail_count=$fail_count + 1))
  if (( $fail_count == 3 )); then
    $ECHO "Failed to authenticate 3 times..."
  fi
done
IS_ADMIN_PASSWORD=$PASSWORD
HAS_IDENTITY_SUPER_ADMIN_PASSWORD="y"
}


redeploy() {
$ECHO "Restoring Portal web service with original files..."
if [ $DEPLOY_TYPE = "IWS" ]; then
  for INSTANCE in `$LS $INSTALL_DIR/SUNWps/web-apps | $GREP -v pre$PATCHID`
  do
    if [ -d $INSTALL_DIR/SUNWps/web-apps/$INSTANCE.pre$PATCHID ]; then
      $RM -rf $INSTALL_DIR/SUNWps/web-apps/$INSTANCE
      $MV $INSTALL_DIR/SUNWps/web-apps/$INSTANCE.pre$PATCHID $INSTALL_DIR/SUNWps/web-apps/$INSTANCE
    fi
  done
elif [ $DEPLOY_TYPE = "SUNONE" ]; then
  $RM -rf $DEPLOY_DOMAIN
  $MV $DEPLOY_DOMAIN.pre$PATCHID $DEPLOY_DOMAIN
else
  $ECHO "Unsupported or unknown DEPLOY TYPE: $DEPLOY_TYPE..."
fi

}


###############################################
# 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 "Backing out changes for $PATCHBASE-01..."
    #==============================================
    #
    # REV01
    # Backout changes to version handling
    #
    #==============================================
    $ECHO "Restoring gateway start file..."
    GWSTARTFILE=/etc/init.d/gateway
    RPSTARTFILE=/etc/init.d/rwproxyd
    NPSTARTFILE=/etc/init.d/netletd

    if [ -f $GWSTARTFILE.pre116411-01 ]; then
      $MV $GWSTARTFILE.pre116411-01 $GWSTARTFILE
      if [ -f $INSTALL_DIR/SUNWps/bin/gateway.pre116411-01 ]; then
        $MV $INSTALL_DIR/SUNWps/bin/gateway.pre116411-01 $INSTALL_DIR/SUNWps/bin/gateway
      fi
      $CP $GWSTARTFILE /etc/rc0.d/K41gateway
      $CP $GWSTARTFILE /etc/rc1.d/K41gateway
      $CP $GWSTARTFILE /etc/rc2.d/K41gateway
      $CP $GWSTARTFILE /etc/rc3.d/S43gateway
      $CP $GWSTARTFILE /etc/rcS.d/K41gateway
    fi

    if [ -f $RPSTARTFILE.pre116411-01 ]; then
      $MV $RPSTARTFILE.pre116411-01 $RPSTARTFILE
      if [ -f $INSTALL_DIR/SUNWps/bin/rwproxyd.pre116411-01 ]; then
        $MV $INSTALL_DIR/SUNWps/bin/rwproxyd.pre116411-01 $INSTALL_DIR/SUNWps/bin/rwproxyd
      fi
    fi

    if [ -f $NPSTARTFILE.pre116411-01 ]; then
      $MV $NPSTARTFILE.pre116411-01 $NPSTARTFILE
      if [ -f $INSTALL_DIR/SUNWps/bin/netletd.pre116411-01 ]; then
        $MV $INSTALL_DIR/SUNWps/bin/netletd.pre116411-01 $INSTALL_DIR/SUNWps/bin/netletd
      fi
    fi

    VERSIONSCRIPT=$INSTALL_DIR/SUNWps/bin/version
    if [ -f $VERSIONSCRIPT.pre116411-01 ]; then
	$ECHO "Restoring version script..."
      $MV $VERSIONSCRIPT.pre116411-01 $VERSIONSCRIPT
    fi

    #==============================================
    #
    # REV01
    # Backout platform.conf entries added for BugIDs 
    # #4841043, and #4880860
    #
    #==============================================
    PLATFORMFILE=/etc/opt/SUNWps/platform.conf.default
    if [ -f $PLATFORMFILE ]; then
      $ECHO "Backing out changes made to platform.conf files..."
      for files in `ls /etc/opt/SUNWps/platform.conf* | grep -v platform.conf-orig`
      do
        if [ -f $files.pre116411-01 ]; then
          /usr/bin/mv $files.pre116411-01 $files
          /usr/bin/chmod 644 $files
        fi
      done
    fi
    #==============================================
    #
    # REV01
    # Backout srapGateway.properties entry for 
    # BugID #4880860
    #
    #==============================================
    PROPFILE=$INSTALL_DIR/SUNWps/locale/srapGateway.properties
    if [ -f $PROPFILE.pre116411-01 ]; then
      /usr/bin/mv $PROPFILE.pre116411-01 $PROPFILE
      /usr/bin/chmod 644 $PROPFILE
    fi

  elif [[ $rev == 2 ]]
  then
    $ECHO "Backing out changes for $PATCHBASE-02..."
  elif [[ $rev == 3 ]]
  then
    $ECHO "Backing out changes for $PATCHBASE-03..."
  elif [[ $rev == 4 ]]
  then
    $ECHO "Backing out changes for $PATCHBASE-04..."
  elif [[ $rev == 5 ]]
  then
    $ECHO "Backing out changes for $PATCHBASE-05..."
  elif [[ $rev == 6 ]]
  then
    $ECHO "Backing out changes for $PATCHBASE-06..."
  elif [[ $rev == 7 ]]
  then
    $ECHO "Backing out changes for $PATCHBASE-07..."
  elif [[ $rev == 8 ]]
  then
    $ECHO "Backing out changes for $PATCHBASE-08..."
  elif [[ $rev == 9 ]]
  then
    $ECHO "Backing out changes for $PATCHBASE-09..."
  elif [[ $rev == 10 ]]
  then
    $ECHO "Backing out changes for $PATCHBASE-10..."

    #==============================================
    #
    # REV10
    # Backout default_gateway_ruleset mods 
    # BugID #5053792
    #
    #==============================================

    pkginfo -q SUNWps
    if [ $? -eq 0 ]; then
      if [ $HAS_IDENTITY_SUPER_ADMIN_PASSWORD = "n" ]; then
        GetIdentitySuperAdminPassword
      fi
      DEFAULTGWRULESET=$INSTALL_DIR/SUNWps/export/DefaultGatewayRuleSet.xml
      if [ -f $DEFAULTGWRULESET.pre116411-10 ]; then
        $ECHO "Backing out changes made to the default_gateway_ruleset..."
        $MV $DEFAULTGWRULESET.pre116411-10 $DEFAULTGWRULESET
        $CHMOD 644 $DEFAULTGWRULESET
        if [ $BIND_SUCCESS = "y" ]; then
          $INSTALL_DIR/SUNWps/bin/rwadmin list --runasdn "$BIND_DN" --password "$IS_ADMIN_PASSWORD" | $GREP "default_gateway_ruleset" > /dev/null 2>&1
          if [ $? -eq 0 ]; then
            $ECHO "Removing new default_gateway_ruleset..."
            $INSTALL_DIR/SUNWps/bin/rwadmin remove --runasdn "$BIND_DN" --password "$IS_ADMIN_PASSWORD" -r "default_gateway_ruleset"
            $ECHO "Restoring old default_gateway_ruleset..."
            $INSTALL_DIR/SUNWps/bin/rwadmin store --runasdn "$BIND_DN" --password "$IS_ADMIN_PASSWORD" $DEFAULTGWRULESET
          fi
        fi
      fi
    fi
  elif [[ $rev == 11 ]]
  then
    $ECHO "Backing out changes for $PATCHBASE-11..."

    # BugId 5042938: changing classpaths back from jss3.jar to jss32.jar
    rollback_classpath "$INSTALL_DIR/SUNWps/bin/gateway"  "0755"
    rollback_classpath "$INSTALL_DIR/SUNWps/bin/rwproxyd" "0755"
    rollback_classpath "$INSTALL_DIR/SUNWps/bin/netletd"   "0755"
    rollback_classpath "/etc/init.d/gateway"  "0744"
    rollback_classpath "/etc/init.d/rwproxyd" "0744"
    rollback_classpath "/etc/init.d/netletd"  "0744"
    $CP /etc/init.d/gateway /etc/rc0.d/K41gateway
    $CP /etc/init.d/gateway /etc/rc1.d/K41gateway
    $CP /etc/init.d/gateway /etc/rc2.d/K41gateway
    $CP /etc/init.d/gateway /etc/rc3.d/S43gateway
    $CP /etc/init.d/gateway /etc/rcS.d/K41gateway

    # Fix for BugId 5002088
    for file in `find /etc/opt/SUNWps -name launchPopup.jsp`
    do
      /usr/bin/mv $file.pre116411-11 $file
    done

  elif [[ $rev == 12 ]]
  then
    $ECHO "Backing out changes for $PATCHBASE-12..."
  elif [[ $rev == 13 ]]
  then
    $ECHO "Backing out changes for $PATCHBASE-13..."
  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
# for backout, the order is reversed

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

  while (($orig_rev < $patch_rev))
  do
    rev_mods $patch_rev;
    ((patch_rev=$patch_rev - 1))
  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[*]}

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

# Rev 11 - roll back classpath updates
rollback_classpath() {
  file=$1
  mode=$2

  if [ -f $file ]; then
    /usr/bin/mv $file.pre116411-11 $file
    /usr/bin/chown root:root $file
    /usr/bin/chmod $mode $file
  fi
}

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

check_patch_revs
restoreVersionString
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 "Postbackout processing complete."

trap ''
