#!/bin/ksh

trap 2

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

PATCHID="119532-02"
VERSION="AMMA6.3.1p2"
rel_ver="25.2"

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

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

#######################################################################################
#
# Static ENV vars
#
SED=/bin/sed
GREP=/bin/grep
EGREP=/bin/egrep
UNIQ=/usr/bin/uniq
ECHO=/bin/echo
MKDIR=/bin/mkdir
MV=/bin/mv
CP=/bin/cp
DATE=/bin/date
CHOWN=/bin/chown
CHMOD=/bin/chmod
RM=/bin/rm
STTY=/bin/stty
LS=/bin/ls
JAR=/usr/jdk/entsys-j2se/bin/jar

PWD=$(pwd)
PATCHREV=`$ECHO ${PATCHID} | /usr/bin/awk ' BEGIN { FS="-" } {print $2 } '`
PATCHBASE=`$ECHO ${PATCHID} | /usr/bin/awk ' BEGIN { FS="-" } {print $1 }'`
ISMACORE="N"
ISAMMA="N"
BASEDIR="/opt/sun"

# Get value of a key in a flatfile and assign it to ANSWER
$ECHO " PrePatch Processing ..."
GrabConfig() {
  local FILE=$1
  local KEY=$2
  local SEPARATOR=$3

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


#########################################################################################
#
# preinstall processing
#
#

rpm -qa | $GREP sun-mobileaccess-1.0 > /dev/null 2>&1
if [ $? -eq 0 ]; then
  ISMACORE="Y" 

  STATE_FILE="/etc/opt/sun/mobileaccess/config.properties"
  if [ ! -f $STATE_FILE ]; then
    $ECHO "Error: $STATE_FILE does not exist. "
    exit 1
  fi
fi # end of checking for core package

rpm -qa | $GREP sun-identity-mobileaccess-6.2 > /dev/null 2>&1
if [ $? -eq 0 ]; then
  ISAMMA="Y"

  STATE_FILE="/etc/opt/sun/identity/config/AMConfig.properties"
  if [ ! -f $STATE_FILE ]; then
    $ECHO "Error: $STATE_FILE does not exist. "
    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."
     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
  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=""

fi # 


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

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
}


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

  #$CP $file $file-orig-$$
  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
}





#######################################################################################
#
# Installing RPM
#

updateRPMs() {

  ## first see if the patch was ever applied before by checking if backup directory is present
  ## if the backup directory is present dont backup new files else back them up

  BACKDIR=/var/spool/backup/$PATCHID
  if [ -d $BACKDIR ]; then
        ## get the prefix to use for updating the rpms because it can be installed in
        ## non default location

        if [ "$ISAMMA" == "Y" ]; then
                BASEDIR=`echo $IS_INSTALL_DIR|sed 's%/identity.*%%'`
        fi
        echo "Using Prefix $BASEDIR"

        ## upgrade rpms without backing up
        ## update rpm only if it is already present on the system

        for eaRPM in `ls $PWD | grep ".rpm"`
        do
                rpmname=`$ECHO $eaRPM | cut -d - -f-3`;
                rpm -q $rpmname >/dev/null 2>&1 ;
                if [ $? = 0 ]; then
                        $ECHO "Updating  $eaRPM ...."
			## do not relocate rpm that ship config files under /etc/opt
                        echo $eaRPM|$EGREP -q 'sun-.*-config-'
                        if [ "$?" \!= 0 ]; then
                                rpm -Uvh --force --relocate /opt/sun=$BASEDIR $eaRPM
                        else
                                rpm -Uvh --force $eaRPM
                        fi

                fi
        done

  else

	## first check if macros file  is present and has repackage directory specified
        FILE="/usr/lib/rpm/macros"
        FILECHECK=n;
        if [ -f $FILE ]; then
                 FILECHECK=y;
                 $CP $FILE $FILE.pre$PATCHBASE-$PATCHREV
                 $GREP -i "repackage_dir" $FILE >> /dev/null
                 if [ $? = 0 ]; then
                        replace_line $FILE "%_repackage_dir" "%_repackage_dir         /var/spool/backup/$PATCHID"
                 else
                        $ECHO  "%_repackage_dir         /var/spool/backup/$PATCHID" >> $FILE
                 fi
		 chmod 755 $FILE
		 rm -fr /var/spool/backup/$PATCHID
		 mkdir -p /var/spool/backup/$PATCHID
        else
                $ECHO ""
                $ECHO ""
                $ECHO "   /usr/lib/rpm/macros cannot be found"
                $ECHO "   It is needed for valid backup "
                $ECHO "   Do you want to continue without backup"
                $ECHO "   If you Continue, patch cannot be backed out"
                $ECHO ""
                $ECHO "     [C]ontinue       [Q]uit"
                read ans
                if [ $ans = 'q' ] || [ $ans = 'Q' ]; then
                        $ECHO "Exitting patch install"
                        exit 1;
                fi
                if [ $ans = 'c'  ] || [ $ans = 'C' ]; then
                        $ECHO
                else
                        while [ $ans ]
                        do
                                $ECHO "Answer not understood"
                                $ECHO "  \n\t[C]ontinue\t\t[Q]uit"
                                read ans
                                if [ $ans = 'q' ] || [ $ans = 'Q' ]; then
                                        $ECHO "Exitting patch install..."
                                        exit 1;
                                fi
                                if [ $ans = 'c'  ] || [ $ans = 'C' ]; then
                                 break
                                fi
                        done
                fi
        fi
	## get the prefix to use for updating the rpms because it can be installed in 
        ## non default location
	
        if [ "$ISAMMA" == "Y" ]; then
                BASEDIR=`echo $IS_INSTALL_DIR|sed 's%/identity.*%%'`
        fi
	echo "Using Prefix $BASEDIR"
        ### update rpms by keeping valid backup
        ## update rpm only if it is already present on the system
       
        for eaRPM in `ls $PWD | grep ".rpm"`
        do
                rpmname=`$ECHO $eaRPM | cut -d - -f-3`;
                rpm -q $rpmname >/dev/null 2>&1 ;
                if [ $? = 0 ]; then
                        $ECHO "Updating  $eaRPM ...."
			## do not relocate rpm that ship config files under /etc/opt
                        echo $eaRPM|$EGREP -q 'sun-.*-config-'
			if [ "$?" \!= 0 ]; then
                        	rpm -Uvh --repackage --force --relocate /opt/sun=$BASEDIR $eaRPM
			else
				rpm -Uvh --repackage --force $eaRPM
			fi
                fi
        done

        ### restore the original macrosfile
        if [ "$FILECHECK" = "y" ]; then
               $CP $FILE.pre$PATCHID $FILE
	       chmod 755 $FILE
        fi
 fi

}

###############################################################################################
#
# postinstall utiltity
#


# function call_rev_mods() calls rev_mods for every revision between the current
#   revision on the system, and the revision of the rpm 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
}

###############################################################################################
#
# Backup AM auth JSPs found in AM web-src...
#
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
  )
}

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

backup_client_data() {
  BACKUP_LDIF_FILENAME=sunAMClient_data_backup_$PATCHBASE-$1.ldif
  ETC_BACKUP_LDIF=/etc/opt/sun/identity/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
}



######################################################################################
#
# rev_mods handles all profile updates file manipulation and anything else which may
#   be required by the patch itself. 
#

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

    if [ $ISAMMA -eq "true" ]; 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
    ###


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


    ### REV02MOD01  update client data...

    if [ "$ISAMMA" -eq "Y" ]; 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 /etc/opt/sun/identity/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 
    ###

elif [[ $rev == 3 ]]
then
#########Make changes for Rev03 here###########
echo "Making changes for $PATCHBASE-03..."

fi ## end of big if block

}

## get the last rev on the system before upgrading the rpms
setlastrev() {

        if [ "$ISAMMA" == "Y" ]; then
                last_rel=`rpm -qa sun-identity-mobileaccess | cut -d - -f5 `
                last_rev=` echo "$last_rel." | cut -d . -f2`
        fi
        if [ "$last_rev" == "" ]; then
                last_rev=0;
	fi
}


postinstall() {
	##  get the last version install
	patch_rev=`echo $rel_ver | cut -d . -f2`;
        typeset -i last_rev=$last_rev;

	call_rev_mods $patch_rev $last_rev
}

	
	
	
	


#######################################################################################
#
# Main processing
#
setlastrev
updateRPMs
postinstall

trap ''
