#!/bin/ksh 
# Copyright 07/24/01 Sun Microsystems, Inc. All Rights Reserved.

trap 2

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

PATCHID=121914-01
VERSION=PS7.0p1

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

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
CHOWN=/usr/bin/chown
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
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
GETFACL=/usr/bin/getfacl
SETFACL=/usr/bin/setfacl

/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 }`
HAS_IDENTITY_SUPER_ADMIN_PASSWORD="n"
PSPresent=1
SRAPresent=1

if [ $# -gt 0 ]; then
 	RMFLAG=$1
	if [[ $RMFLAG == "-r" ]]; then
	   echo "This option needs to be used after removing the patch"
	   echo "If you have used this option accidentally, Press Control-C immediately and Exit.."
	   sleep 5
	   echo "Reverting the changes done by $PATCHID"
	else
	   echo "Usage : doPatchUpdate [-r]"
	   exit 1
	fi
else
	RMFLAG="-a"
fi


# Get value of a key in a flatfile and assign it to ANSWER

GrabConfig() {
  local FILE=$1
  local KEY=$2
  local SEPARATOR=$3

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

BELL_CHAR='\a'
pkginfo -q SUNWportal-admin
if [ $? -eq 0 ]; then
  INSTALL_DIR=`pkginfo -r SUNWportal-admin`
else
   echo "Looks like your system is different from 7.0 "
   echo "Abort"
   exit
fi # End of checking for Portal Server node

pkginfo -q SUNWportal-base
if [ $? -eq 0 ]; then
  PSPresent=0
fi

pkginfo -q SUNWportal-sracommon
if [ $? -eq 0 ]; then
  SRAPresent=0
fi

echo "Have you restarted all your servers (cacao, webcontainer)?[y/n]"
read ANS

if [[ $ANS == "n" ]]; then
	echo "Please restart all your servers"
	echo "Aborting .."
	exit
fi

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

# TODO: Update in PSVersion 

updateVersionString() {
    VERSION="$VERSION,`/usr/bin/date`"
    VERSION_FILE=$INSTALL_DIR/SUNWportal/lib/PSversion.properties
    $ECHO "patch=$PATCHID,$VERSION" >> $VERSION_FILE
}

# 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 PASSWDFILE=$1
  $INSTALL_DIR/SUNWportal/bin/psadmin -V -u amadmin -f $PASSWDFILE 
  if [ $? -eq 1 ]; then
    $ECHO "Authentication failed ..."
    BIND_SUCCESS=n
  else
    $ECHO "Authentication Success .."
    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
  echo $PASSWORD > $INSTALL_DIR/SUNWportal/bin/pwdfile
  test_bind $INSTALL_DIR/SUNWportal/bin/pwdfile 
  ((fail_count=$fail_count + 1))
  if (( $fail_count == 3 )); then
    $ECHO "Failed to authenticate 3 times..."
    $ECHO "Exiting .."
    $RM -f $INSTALL_DIR/SUNWportal/bin/pwdfile
    exit 1
  fi
done

HAS_IDENTITY_SUPER_ADMIN_PASSWORD="y"
}

ReplaceMacrosTokens() {
  local FILES=$*
  for FILE in $FILES; do
    if [ -f $FILE ]; then
      if [ ! -f $FILE.pre$PATCHID ]; then
        $CP $FILE $FILE.pre$PATCHID
      fi
      $SED -e "s#%PS_BASEDIR%#$PS_INSTALL_DIR#g" \
           -e "s#%PS_PRODUCT_DIR%#$PS_PRODUCT_DIR#g" \
           -e "s#GATEWAY_IPADDR#$GW_IP#g" \
           -e "s#%PS_CONFIG_DIR%#$PS_CONFIG_DIR#g" \
           -e "s#SUNPORTALDESKTOPDEFAULTCHANNEL#JSPTabContainer#g" \
           -e "s#\[PS_CONFIG_DIR\]#$PS_CONFIG_DIR#g" \
           -e "s#%PS_VAR_DIR%#$PS_VAR_DIR#g" \
           -e "s#\${BASE_DIR}#$PS_INSTALL_DIR#g" \
           -e "s#\${IDSAME_BASE_DIR}#$IS_INSTALL_DIR#g" \
           -e "s#\${PRODUCT_DIR}#SUNWps#g" \
           -e "s#%IDSAME_VAR_DIR%#$IDSAME_VAR_DIR#g" $FILE > $FILE.tmp
      $MV $FILE.tmp $FILE
    fi
  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
}

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

  if [ $PSPresent -eq 0 ] ; then

  GetIdentitySuperAdminPassword
  PSADMIN=$INSTALL_DIR/SUNWportal/bin/psadmin
  PWDFILE=$INSTALL_DIR/SUNWportal/bin/pwdfile
  IS_INSTALL_DIR=`pkginfo -r SUNWamsdk`/SUNWam

  #$GREP -i "com.sun.identity.jss.donotInstallAtHighestPriority" $IS_INSTALL_DIR/lib/AMConfig.properties > /dev/null
  #if [ $? -eq 1 ]; then
#	insert_line $IS_INSTALL_DIR/lib/AMConfig.properties "com.iplanet.am.jssproxy.trustAllServerCerts" "com.sun.identity.jss.donotInstallAtHighestPriority=true"
#  else
	#replace_line $IS_INSTALL_DIR/lib/AMConfig.properties "com.sun.identity.jss.donotInstallAtHighestPriority" "com.sun.identity.jss.donotInstallAtHighestPriority=true"
#  fi

  #Find the portalid and redeploy them

  echo "Finding the portals in the system ..."

  PORTALS=`$PSADMIN list-portals -u amadmin -f $PWDFILE | $GREP "Portal:" | $AWK -F":" '{print $2}' | $SED 's/[ ]//g'`

  for portalid in `echo $PORTALS`
  do

	echo "Commencing processing for portal $portalid..\n"	

  	echo "Redeploying community portlet .."

	echo "Please Enter the domain to deploy this portlet {'g' for global or give the exact dn 'o=Dev,dc=india,dc=sun,dc=com'}:"
	read ANSWER

	if [[ $ANSWER == "g" ]]; then 
		DOMAIN="-g"
	else
		DOMAIN="-d $ANSWER"
	fi

	echo "using $DOMAIN .."

	CMD="$PSADMIN undeploy-portlet -u amadmin -f $PWDFILE -p $portalid $DOMAIN communityportlets"
  	echo $CMD
	`$CMD`
	CMD="$PSADMIN deploy-portlet -u amadmin -f $PWDFILE -p $portalid $DOMAIN $INSTALL_DIR/SUNWportal/portlet/communityportlets.war"
	echo $CMD
	`$CMD`

	echo "Done !"
	echo ""
	echo "Redeploying wsssoportlet .."

	echo "Please Enter the domain to deploy this portlet {'g' for global or give the exact dn 'o=Dev,dc=india,dc=sun,dc=com'}:"
	read ANSWER

	if [[ $ANSWER == "g" ]]; then 
		DOMAIN="-g"
	else
		DOMAIN="-d $ANSWER"
	fi

	echo "using $DOMAIN.."

	CMD="$PSADMIN undeploy-portlet -u amadmin -f $PWDFILE -p $portalid $DOMAIN  wsssoportlet"
	echo $CMD
	`$CMD`
	CMD="$PSADMIN deploy-portlet -u amadmin -f $PWDFILE -p $portalid $DOMAIN $INSTALL_DIR/SUNWportal/portlet/wsssoportlet.war"
	echo $CMD
	`$CMD`

	echo "Done !"
	echo ""

	echo "Redeploying the portal war .."

        CMD="$PSADMIN redeploy -u amadmin -f $PWDFILE -p $portalid"
	echo $CMD
	`$CMD`
	
	echo "Done !"
	echo ""

	# Find the instances of the portal
        
	# INSTANCES=`$PSADMIN list-portals -u amadmin -f $PWDFILE -p $portalid | $GREP "Instance:" | $GREP -vi "Webcontainer" | $AWK -F":" '{print $2}' | $SED 's/[ ]//g'`
	
	# for instanceid in `echo $INSTANCES`
	# do
	#	echo "Redeploying portal ..."
	#	echo "InstanceID: $instanceid"
	#	$PSADMIN redeploy -u amadmin -f $PWDFILE -p $portalid -i $instanceid
	#done

	# Modifying properties in desktopconfig.properties
        DESKTOPCFG="/var/opt/SUNWportal/portals/$portalid/config/desktopconfig.properties"

        if [[ $RMFLAG == "-r" ]]; then
                echo "Restoring desktopconfig.properties file ..."
                $MV $DESKTOPCFG.pre$PATCHID $DESKTOPCFG
        else
                echo "Modifying the parallel processing mode property in desktopconfig.properties ..."
                $CP $DESKTOPCFG $DESKTOPCFG.pre$PATCHID
                replace_line $DESKTOPCFG "portletRenderModeParallel" "portletRenderModeParallel=false"
        fi
 
        echo "Done !"
        echo ""

	echo "Completed processing for portal $portalid.."
	echo ""

  done

  # Find search servers and deploy them
  if [[ $RMFLAG != "-r" ]]; then	

  SEARCHSRVS=`$PSADMIN list-search-servers -u amadmin -f $PWDFILE | $GREP "Search Server:" | $AWK -F":" '{print $2}' | $SED 's/[ ]//g'`

	for searchid in `echo $SEARCHSRVS`
	do
		echo "Redeploying Search server $searchid"
		$PSADMIN redeploy-search-server -u amadmin -f $PWDFILE -s $searchid
	done
   fi

   $RM $PWDFILE

  fi
  #########End of changes for Rev01##############
  elif [[ $rev == 2 ]]
  then
  #########Make changes for Rev02 here###########
  echo "Making changes for $PATCHBASE-02..."
  #########End of changes for Rev02##############
  fi
} # End of rev_mods

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

  call_rev_mods '01' '00'
} 


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

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

echo ""
echo "Completed patch update"
echo "Restart all your servers"

trap ' '
