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

trap 2

###############################################
# ENV vars which need to be modified
###############################################
PATCHID="117284-06"
VERSION="PS6.0PC6"
FILES_TO_DEPLOY="desktop.jar desktopp.jar netfilejava1.jar netfilejava2.jar netmail.jar rewriter.jar"

###############################################
# 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
OMIT_CHAR='\c'
BELL_CHAR='\a'
STTY=/usr/bin/stty
GETFACL=/usr/bin/getfacl
HAS_IDENTITY_SUPER_ADMIN_PASSWORD="n"

pkginfo -q SUNWps
if [ $? -eq 0 ]; then
  PS_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
  SRA_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`
  LOCAL_DIR=1
fi
PATCHREV=`$ECHO ${PATCHID} | cut -d- -f2`
PATCHBASE=`$ECHO ${PATCHID} | cut -d- -f1`


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

updateVersionString() {
  PS_VERSION_FILE=/etc/opt/SUNWps/.version
  VERSION="$VERSION,`/usr/bin/date`"
  if [ -f $PS_VERSION_FILE ]; then
    $ECHO "patch=$PATCHID,$VERSION" >> $PS_VERSION_FILE
  fi
  SRA_VERSION_FILE=/etc/opt/SUNWps/.version-sra
  if [ -f $SRA_VERSION_FILE ]; then
    $ECHO "patch=$PATCHID,$VERSION" >> $SRA_VERSION_FILE
  fi
}

redeploy() {
/usr/bin/pkginfo -q SUNWps
if [ $? -eq 0 ]; then
  # Cannot use deploy command for 6.0, so must perform file cp instead
  $ECHO "Backing up and redeploying Portal web service with updated files..."
  if [ $DEPLOY_TYPE = "iWS" ]; then
    for INSTANCE in `$LS $PS_INSTALL_DIR/SUNWps/web-apps | $GREP https- | $GREP -v pre`
    do
      $CP -R $PS_INSTALL_DIR/SUNWps/web-apps/$INSTANCE $PS_INSTALL_DIR/SUNWps/web-apps/$INSTANCE.pre$PATCHID
      for FILENAME in $FILES_TO_DEPLOY
      do
        cd $PS_INSTALL_DIR/SUNWps/web-src/
        FN=`$FIND . -name $FILENAME | cut -b3-`
        SRC=$PS_INSTALL_DIR/SUNWps/web-src/$FN
        if [ x$FN != x ] && [ -f $FN ]; then
          TGT=$PS_INSTALL_DIR/SUNWps/web-apps/$INSTANCE/$DEPLOY_URI/$FN
          $RM -f $TGT
          $CP -fp $SRC $TGT
          $ECHO "\nCopy $SRC\n  to $TGT"
        fi
      done
    done
  elif [ $DEPLOY_TYPE = "SUNONE" ]; then
  $ECHO "Portal web service must be redeployed using the SUNONE application server command line interface"
  else
  $ECHO "Unsupported or unknown DEPLOY TYPE: $DEPLOY_TYPE..."
  fi
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-$$
}

# 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 "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
      replace_line $GWSTARTFILE "\/usr\/bin\/cat -s \$VERSIONFILE" "    \/usr\/bin\/cat -s \$VERSIONFILE | sed -e 's\/patch=\/\/g'"
      #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

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

    VERSIONFILE=$PS_INSTALL_DIR/SUNWps/bin/version
    if [ -f $VERSIONFILE ]; then
      $ECHO "Updating version command to handle display patch info..."
      $CP $VERSIONFILE $VERSIONFILE.pre$PATCHID
      replace_line $VERSIONFILE "\$TAIL -1l \$VERSION_FILE" "    \/usr\/bin\/cat \$VERSION_FILE | sed -e 's\/patch=\/\/g'" 
      $CHMOD 755 $VERSIONFILE
    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.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 IOError Message to 
    #   srapGateway.properties 
    #
    #==============================================
    PROP_FILE=$PS_INSTALL_DIR/SUNWps/locale/srapGateway.properties
    if [ -f $PROP_FILE ] ; then
      /usr/bin/cp $PROP_FILE $PROP_FILE.pre$PATCHID
      /usr/bin/grep "IOErrorMessage" $PROP_FILE > /dev/null 2>&1
      if [ $? -ne 0 ] ; then
        /usr/bin/echo "IOErrorMessage=<html><head><title>Rewriter:IOException</title></head><body>Rewriter could not retrieve content from remote server. <br/> Please contact your administrator.</body></html> " >> $PROP_FILE
      fi
    fi 

  elif [[ $rev == 2 ]]
  then
    $ECHO "Making changes for $PATCHBASE-02..."
    #==============================================
    #
    # REV02
    # Change file perms for new ruleset to match
    # portal user permissions.
    #
    #==============================================

    DEFAULTRULESET=$PS_INSTALL_DIR/SUNWps/export/DefaultRuleSet.xml
    DARULESET=$PS_INSTALL_DIR/SUNWps/export/iDARuleSet.xml
    if [ -f $DEFAULTRULESET ]; then
      PSUSER=`$GETFACL $DEFAULTRULESET | $GREP owner | $SED -n -e 's/ //gp' | $CUT -d ':' -f2`
      PSGROUP=`$GETFACL $DEFAULTRULESET | $GREP group | $SED -n -e 's/ //gp' | $CUT -d ':' -f2`
      if [ -f $DARULESET ]; then
        $CHOWN $PSUSER:$PSGROUP $DARULESET
      fi
    fi

    #==============================================
    #
    # REV02
    # Add the new DA rewriter ruleset to Identity
    # using rwadmin CLI
    #
    #==============================================

    pkginfo -q SUNWps
    if [ $? -eq 0 ]; then
      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 [ -f $DARULESET ] && [ $BIND_SUCCESS = "y" ]; then
        $ECHO "Adding new RuleSet for Delegated Administrator..."
        $PS_INSTALL_DIR/SUNWps/bin/rwadmin store --runasdn "$BIND_DN" --password "$IS_ADMIN_PASSWORD" $DARULESET > /dev/null 2>&1
        if [ $? -ne 0 ]; then
          $ECHO "Failed to upload new ruleset to the Identity Server: $DARULESET"
        fi
      fi

    fi

  elif [[ $rev == 3 ]]
  then
    $ECHO "Making changes for $PATCHBASE-03..."
  elif [[ $rev == 4 ]]
  then
    $ECHO "Making changes for $PATCHBASE-04..."
  elif [[ $rev == 5 ]]
  then
    $ECHO "Making changes for $PATCHBASE-05..."
  elif [[ $rev == 6 ]]
  then
    $ECHO "Making changes for $PATCHBASE-06..."
  elif [[ $rev == 7 ]]
  then
    $ECHO "Making 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

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 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 "Postpatch processing complete."

trap ''
