#!/bin/ksh 
# Copyright 03/29/2004 Sun Microsystems, Inc. All Rights Reserved.

trap 2

###############################################
# ENV vars which need to be modified
###############################################
PATCHID="117284-05"

###############################################
# 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
CUT=/usr/bin/cut
CHOWN=/usr/bin/chown
CHMOD=/usr/bin/chmod
AWK=/usr/bin/awk
NAWK=/usr/bin/nawk
FIND=/usr/bin/find
GETFACL=/usr/bin/getfacl
STTY=/usr/bin/stty
HAS_IDENTITY_SUPER_ADMIN_PASSWORD="n"
pkginfo -q SUNWps
if [ $? -eq 0 ]; then
  PS_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
  SRA_INSTALL_DIR=`$GREP "SRAP_BASEDIR=" /var/sadm/pkg/SUNWpsgw/pkginfo | $AWK ' BEGIN { FS="=" } { print $2 }`
fi
pkginfo -q SUNWamdsc
if [ $? -eq 0 ]; then
  IS_INSTALL_DIR=`$GREP "BASEDIR=" /var/sadm/pkg/SUNWamsvc/pkginfo | $AWK ' BEGIN { FS="=" } { print $2 }`
fi
PATCHREV=`$ECHO ${PATCHID} | $AWK ' BEGIN { FS="-" } {print $2}`
PATCHBASE=`$ECHO ${PATCHID} | $AWK ' BEGIN { FS="-" } {print $1}`


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

restoreVersionString() {
  PS_VERSION_FILE=/etc/opt/SUNWps/.version
  if [ -f $PS_VERSION_FILE ]; then
    $ECHO "`$GREP -v $PATCHID $PS_VERSION_FILE`" > $PS_VERSION_FILE 
  fi
  SRA_VERSION_FILE=/etc/opt/SUNWps/.version-sra
  if [ -f $SRA_VERSION_FILE ]; then
    $ECHO "`$GREP -v $PATCHID $SRA_VERSION_FILE`" > $SRA_VERSION_FILE
  fi
}

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

}

# function test_bind checks to make sure that the password matches for the super
# admin bind DN set in the Identity config file.  Sets BIND_SUCCESS to y if the
# password given is correct

test_bind() {
  local PASSWD=$1
  local BIND_DN=`$GREP "com.iplanet.authentication.super.user" "$IS_INSTALL_DIR/SUNWam/lib/AMConfig.properties" | cut -d "=" -f2-`
  `$PS_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
}

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



###############################################
# 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 of version logic changes
    #
    #==============================================

    $ECHO "Backing out version logic changes..."
    GWSTARTFILE=/etc/init.d/gateway
    if [ -f $GWSTARTFILE.pre$PATCHID ]; then
      $MV $GWSTARTFILE.pre$PATCHID $GWSTARTFILE
      $CHMOD 755 $GWSTARTFILE
    fi

    GWSTARTFILE=$SRA_INSTALL_DIR/SUNWps/bin/gateway
    if [ -f $GWSTARTFILE.pre$PATCHID ]; then
      $MV $GWSTARTFILE.pre$PATCHID $GWSTARTFILE
      $CHMOD 755 $GWSTARTFILE
    fi

    VERSIONFILE=$PS_INSTALL_DIR/SUNWps/bin/version
    if [ -f $VERSIONFILE.pre$PATCHID ]; then
      $MV $VERSIONFILE.pre$PATCHID $VERSIONFILE
      $CHMOD 755 $VERSIONFILE
    fi

    #==============================================
    #
    # REV01
    # Backout platform.conf entries 
    # 
    #
    #==============================================
    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.pre$PATCHID ]; then
          /usr/bin/mv $files.pre$PATCHID $files
          /usr/bin/chmod 644 $files
        fi
      done
    fi

    #==============================================
    #
    # REV01
    #   Backout new error message added to 
    #   srapGateway.properties
    #
    #==============================================
    PROP_FILE=$PS_INSTALL_DIR/SUNWps/locale/srapGateway.properties
    if [ -f $PROP_FILE.pre$PATCHID ]; then
        /usr/bin/mv $PROP_FILE.pre$PATCHID $PROP_FILE
        /usr/bin/chmod 644 $PROP_FILE
    fi

  elif [[ $rev == 2 ]]
  then
    $ECHO "Backing out changes for $PATCHBASE-02..."
    #==============================================
    #
    # REV02
    # Remove the new DA rewriter ruleset 
    # using rwadmin CLI
    #
    #==============================================

    pkginfo -q SUNWps
    if [ $? -eq 0 ]; then
      $ECHO "Removing iDA Ruleset..."
      if [ $HAS_IDENTITY_SUPER_ADMIN_PASSWORD = "n" ]; then
        GetIdentitySuperAdminPassword
      fi
      BIND_DN=`$GREP "com.iplanet.authentication.super.user" "$IS_INSTALL_DIR/SUNWam/lib/AMConfig.properties" | cut -d "=" -f2-`
      if [ $BIND_SUCCESS = "y" ]; then
        $PS_INSTALL_DIR/SUNWps/bin/rwadmin list --runasdn "$BIND_DN" --password "$IS_ADMIN_PASSWORD" | $GREP "ida_ruleset" > /dev/null 2>&1
        if [ $? -eq 0 ]; then
          $PS_INSTALL_DIR/SUNWps/bin/rwadmin remove --runasdn "$BIND_DN" --password "$IS_ADMIN_PASSWORD" --rulesetid "ida_ruleset" > /dev/null 2>&1
        fi
      fi
    fi


  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..."
  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
}


###############################################
# 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 startall
  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/$DEPLOY_INSTANCE/bin/stopserv
      $DEPLOY_DOMAIN/$DEPLOY_INSTANCE/bin/startserv
    #done
  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 ''
