#!/bin/ksh 
# Copyright 07/24/01 Sun Microsystems, Inc. All Rights Reserved.
# @(#)postpatch	1.11 07/24/01 Sun Microsystems

trap 2

#######################################################################################
#
# ENV vars which need to be modified
#

PATCHID="119530-02"
VERSION="AMMA6.3.1p2"

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

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

#######################################################################################
#
# Static ENV vars 
#
ECHO=/usr/bin/echo
UMASK=/usr/bin/umask
CP=/usr/bin/cp
SED=/usr/bin/sed
UNIQ=/usr/bin/uniq
GREP=/usr/bin/grep
LS=/usr/bin/ls
BASENAME=/usr/bin/basename
CAT=/usr/bin/cat
CHMOD=/usr/bin/chmod
CP=/usr/bin/cp
CUT=/usr/bin/cut
DATE=/usr/bin/date
DIRNAME=/usr/bin/dirname
AWK=/usr/bin/awk
ENV=/usr/bin/env
GREP=/usr/bin/grep
ID=/usr/bin/id
JAR=/usr/java/bin/jar
LN=/usr/bin/ln
LS=/usr/bin/ls
MKDIR=/usr/bin/mkdir
MV=/usr/bin/mv
NAWK=/usr/bin/nawk
PKGINFO=/usr/bin/pkginfo
RM=/usr/bin/rm
STTY=/usr/bin/stty
TOUCH=/usr/bin/touch

/usr/bin/echo $PATH | /usr/bin/grep "/usr/java/bin[^/]" > /dev/null 2>&1
if [ $? -ne 0 ] ; then
  PATH="$PATH:/usr/java/bin"
  export PATH
fi
PATCHREV=`/usr/bin/echo ${PATCHID} | /usr/bin/awk ' BEGIN { FS="-" } {print $2 }`
PATCHBASE=`/usr/bin/echo ${PATCHID} | /usr/bin/awk ' BEGIN { FS="-" } {print $1 }`


###############################################
# Get configuration from file
###############################################
GrabConfig() {
  local FILE=$1
  local KEY=$2
  local SEPARATOR=$3

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

BELL_CHAR='\a'
STATE_FILE="/etc/opt/SUNWam/config/AMConfig.properties"
if [ ! -f $STATE_FILE ]; then
  $ECHO "Error: $STATE_FILE does not exist. $BELL_CHAR"
  exit 1
fi

GrabConfig $STATE_FILE "com.iplanet.am.installdir" "="
if [ "$ANSWER" != "" ]; then
   IS_INSTALL_DIR=$ANSWER
else
   $ECHO "Error: Cannot determine IS_INSTALL_DIR. $BELL_CHAR"
   exit 1
fi

LDAPSEARCH=$IS_INSTALL_DIR/bin/ldapsearch
LDAPMODIFY=$IS_INSTALL_DIR/bin/ldapmodify
LD_LIBRARY_PATH=$IS_INSTALL_DIR/ldaplib/ldapsdk:$LD_LIBRARY_PATH
LD_LIBRARY_PATH=/usr/lib/mps:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH

GrabConfig $STATE_FILE "com.iplanet.am.directory.host" "="
if [ "$ANSWER" != "" ]; then
   LDAP_HOST=$ANSWER
else
   $ECHO "Error: Cannot determine LDAP_HOST. $BELL_CHAR"
   exit 1
fi

GrabConfig $STATE_FILE "com.iplanet.am.directory.port" "="
if [ "$ANSWER" != "" ]; then
   LDAP_PORT=$ANSWER
else
   $ECHO "Error: Cannot determine LDAP_PORT. $BELL_CHAR"
   exit 1
fi

GrabConfig $STATE_FILE "com.iplanet.am.rootsuffix" "="
if [ "$ANSWER" != "" ]; then
   ROOT_SUFFIX=$ANSWER
else
   $ECHO "Error: Cannot determine ROOT_SUFFIX. $BELL_CHAR"
   exit 1
fi

DIR_MGR_DN="cn=Directory Manager"
DIR_MGR_PASSWORD=""

getPassword() {
      DONE="n"
      while [ "$DONE" = "n" ]; do
        $ECHO
        $ECHO "Please enter $1 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 "Password verification failed! $BELL_CHAR"
          elif [ "$PASSWORD" = "" ]
          then
            print "You must specify a password. $BELL_CHAR"
          else
            DONE="y"
          fi
        fi
     done
}


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

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

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

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

} 

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

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

addValsToAttr() {
  set -A vals $*
  integer curCount=2
  attrName=$1
  fileName=$2
  while (( $curCount < ${#*} ))
  do
    vals[$curCount]="         <Val>${vals[$curCount]}<\/Val>"
sed -e "/$attrName/{n; n; n; n; n;
a\\
${vals[$curCount]}
;}" $fileName > /tmp/tmp$$
/bin/mv /tmp/tmp$$ $fileName
    ((curCount=$curCount + 1))
  done
}


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

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





######################################################################################
#
# Routines to handle client data update...
#

backup_client_data() {
  BACKUP_LDIF_FILENAME=sunAMClient_data_backup_$PATCHBASE-$1.ldif
  ETC_BACKUP_LDIF=${ROOTDIR}/etc/opt/SUNWam/config/ldif/$BACKUP_LDIF_FILENAME
  TMP_BACKUP_LDIF=/tmp/$BACKUP_LDIF_FILENAME

  LDAP_STAT=0
  if [ \! -f $ETC_BACKUP_LDIF ]
  then
    $LDAPSEARCH -T -h $LDAP_HOST -p $LDAP_PORT \
      -D "$DIR_MGR_DN" -w "$DIR_MGR_PASSWORD" \
      -b "$ROOT_SUFFIX" \
      entrydn='ou=*,ou=internalData,ou=1.0,ou=SunAMClientData,*' \
      > $TMP_BACKUP_LDIF
    LDAP_STAT=$?
    $SED -e 's/^ou=.*ou=SunAMClientData/dn: &/' \
      $TMP_BACKUP_LDIF \
      > $ETC_BACKUP_LDIF
    $RM -f $TMP_BACKUP_LDIF
  fi
}

update_client_data() {
  ETC_UPDATE_LDIF=$1
  TMP_UPDATE_LDIF=/tmp/sunAMClient_data_update_tmp.ldif

  $SED -e 's/ROOT_SUFFIX/'$ROOT_SUFFIX'/' $ETC_UPDATE_LDIF >$TMP_UPDATE_LDIF
  $LDAPMODIFY -c -h $LDAP_HOST -p $LDAP_PORT \
    -D "$DIR_MGR_DN" -w "$DIR_MGR_PASSWORD" \
    -f $TMP_UPDATE_LDIF \
    >/dev/null 2>&1
  if [ $? != 0 ]
  then
    echo "Possible errors in client data update."
  fi
  $RM -f $TMP_UPDATE_LDIF
}

backup_auth_jsps() {
  BACKUPDIR=$IS_INSTALL_DIR/web-src-services-BACKUP-$PATCHBASE-$1
  $MKDIR -p $BACKUPDIR
  ( 
    cd $IS_INSTALL_DIR/web-src/services 
    find . -type d | while read D
    do
      $MKDIR -p $BACKUPDIR/$D
    done
    $JAR -tf $IS_INSTALL_DIR/mobile_auth_jsps.jar 2>&1 | $GREP '.jsp' | while read F
    do
      $CP -p $F $BACKUPDIR/$F >/dev/null 2>&1
    done
  )
}





######################################################################################
#
# 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 install
#   script.
#

rev_mods() {
  typeset -i rev=$1

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

    ### REV01MOD01 update auth JSPs...

    pkginfo -q SUNWamma
    if [ $? -eq 0 ]; then

      if [ -d $IS_INSTALL_DIR/web-src/services ]
      then

        #
        # Backup existing auth JSPs...
        #
        backup_auth_jsps "01"

        #
        # Unpack auth JSP jar...
        #
        (
          cd $IS_INSTALL_DIR/web-src/services
          $JAR -xf ../../mobile_auth_jsps.jar
        )

      fi

    fi
    ### End of REV01MOD01 
    ###


    #########End of changes for Rev01##############
  elif [[ $rev == 2 ]]
  then
    #########Make changes for Rev02here###########
    echo "Making changes for $PATCHBASE-02"
    ###############################################


    ### REV02MOD01  update client data...

    pkginfo -q SUNWammae
    if [ $? -eq 0 ]; then

      if [ -z "$DIR_MGR_PASSWORD" ]
      then
        getPassword "Directory Manager"
        DIR_MGR_PASSWORD=$PASSWORD
      fi
    
      #
      # First, backup current client data...
      #
      backup_client_data 02

      #
      # Now, apply client data update...
      #
      if [ $LDAP_STAT = 0 ]
      then
        $LS -1 ${ROOTDIR}/etc/opt/SUNWam/config/ldif/sunAMClient_data_update_02_*.ldif | \
        while read LDIF
        do
          update_client_data $LDIF
        done
      else
        echo "Unable to backup existing client data."
        echo "Client data update not applied."
        $RM -f $ETC_BACKUP_LDIF
      fi

    fi
    ### End of REV02MOD01 
    ###

  fi

}

#######################################################################################
#
# 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 another
#    '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() {

  /usr/bin/echo "Checking for previous patch revisions..."

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

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

  # Check case where there may be no patch revisions installed

  if [[ $NUM_REVS > 1 ]]
  then 

    # Now sort it and get the highest rev currently installed
    sort_arr ${CURRENT_REVS[*]}

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

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

} 

#######################################################################################
#
# Main processing
#
check_patch_revs


#######################################################################################
#
# Done
#

/usr/bin/echo ""
/usr/bin/echo "Postpatch processing complete."

trap ''
