#!/bin/ksh
# @(#)postbackout       1.16 01/07/25 Sun Microsystems

trap 2

#######################################################################################
#
# Patch unique env vars...
#

PATCHID="119531-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
EGREP=/usr/bin/egrep
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
}

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

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


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

######################################################################################
#
# 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 "Backing out changes for $PATCHBASE-01..."
  
    ### REV01MOD01: backout changes to client data...

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

      #
      # Restore web-src...
      #
      BACKUPDIR=$IS_INSTALL_DIR/web-src-services-BACKUP-$PATCHBASE-01
      if [ -d $BACKUPDIR ]
      then
        (
          cd $BACKUPDIR
          find . -name '*jsp' | while read F
          do
            $CP -p $F $IS_INSTALL_DIR/web-src/services/$F
          done
        )

        $RM -rf $BACKUPDIR
      fi

    fi

    ### end of REV01MOD01

  elif [[ $rev == 2 ]]
  then
    #########Make changes for Rev02 here###########
    echo "Backing out changes for $PATCHBASE-02"


    ### REV02MOD01: backout changes to client data...

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

      getPassword "Directory Manager"
      DIR_MGR_PASSWORD=$PASSWORD
  
      #
      # First, remove all existing client data...
      #
      BACKUP_LDIF_FILENAME=sunAMClient_data_backup_$PATCHBASE-02.ldif
      ETC_BACKUP_LDIF=${ROOTDIR}/etc/opt/SUNWam/config/ldif/$BACKUP_LDIF_FILENAME
      TMP_DUMP_LDIF=/tmp/dump.ldif
      TMP_DELETE_LDIF=/tmp/delete.ldif

      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_DUMP_LDIF
        LDAP_STAT=$?

        if [ $LDAP_STAT = 0 ]
        then
          $EGREP '^dn:.*ou=SunAMClientData' $TMP_DUMP_LDIF | \
            $AWK '{ print $0 ; print "changetype: delete\n" }' \
              >$TMP_DELETE_LDIF

          $LDAPMODIFY -h $LDAP_HOST -p $LDAP_PORT \
            -D "$DIR_MGR_DN" -w "$DIR_MGR_PASSWORD" \
            -f $TMP_DELETE_LDIF \
            >/dev/null 2>&1
          LDAP_STAT=$?
          if [ $LDAP_STAT != 0 ]
          then
            $ECHO "Unable to delete current client data."
          fi
        fi
      else
        $ECHO "Client data backup does not exist."
        $ECHO "Skipping restore."
      fi
      $RM -f $TMP_DUMP_LDIF
      $RM -f $TMP_DELETE_LDIF
  
      #
      #  Now..., restore previous client data...
      #
      if [ $LDAP_STAT = 0 -a -f $ETC_BACKUP_LDIF ]
      then
        $LDAPMODIFY -a -h $LDAP_HOST -p $LDAP_PORT \
          -D "$DIR_MGR_DN" -w "$DIR_MGR_PASSWORD" \
          -f $ETC_BACKUP_LDIF \
          >/dev/null 2>&1
  
        if [ $? = 0 ]
        then
          $RM -f $ETC_BACKUP_LDIF
        else
          echo "Failure during restoration of previous client data."
        fi
      else
        echo "Client data was not restored."
      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 > 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

#
# Done
#

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

trap ''
