#!/bin/sh 

# Copyright 08/02/00 Sun Microsystems, Inc. All Rights Reserved.
# @(#)postpatch	1.10 00/08/02 Sun Microsystems

AWK=/usr/bin/awk
NAWK=/usr/bin/nawk
ECHO=/usr/bin/echo
MV=/usr/bin/mv
CP=/usr/bin/cp
RM=/bin/rm
GREP=/bin/grep
#GREP=/usr/bin/grep
SED=/usr/bin/sed
HEAD=/usr/bin/head
TAIL=/usr/bin/tail
CHMOD=/usr/bin/chmod
LS=/bin/ls
FIND=/usr/bin/find
WC=/usr/bin/wc
CUT=/usr/bin/cut

VERSION_FILE=.version
PATCH_ID=120091-12
BKFILESUFFIX=-pre-$PATCH_ID

##############################################################
#
# Test if the sdk package is installed.
#
##############################################################
check_for_sdk() {
   pkginfo -q SUNWamsdk
   if [ $? -eq 0 ]; then
      sdk="yes"
   else
      sdk="no"
   fi
}

##############################################################
#
# Test if the services package is installed.
#
##############################################################
check_for_svc() {
   pkginfo -q SUNWamsvc
   if [ $? -eq 0 ]; then
      svc="yes"
   else
      svc="no"
   fi
}

##############################################################
#
# Test if the console package is installed.
#
##############################################################
check_for_con() {
   pkginfo -q SUNWamcon
   if [ $? -eq 0 ]; then
      con="yes"
   else
      con="no"
   fi
}

##############################################################
#
# Test if the console sdk package is installed.
#
##############################################################
check_for_consdk() {
   pkginfo -q SUNWamconsdk
   if [ $? -eq 0 ]; then
      consdk="yes"
   else
      consdk="no"
   fi
}

check_server_xml()
{
conf_file=${1:-server.xml}
file_type=${2:-xml}
container=${3:-ws61}

if [ "$container" = "ws61" ];then
 suffixstring="classpathsuffix"
elif [ "$container" = "as70" ];then
 suffixstring="classpath-suffix"
elif [ "$container" = "was51" ];then
 suffixstring="classpath"
fi

  exist=0
  #step1: grep for classpath suffix in server.xml
  file=$conf_file
  classpath=`grep $suffixstring $file`

  #step2: Get the number of tokens in the <JAVA> .. </JAVA>
  var=`echo $classpath | nawk ' { print NF } '`

  #step3: Add our classpath to the existing Classpathsuffix in server.xml
  count=1
  newline=""
  while [ $count -le $var ]
  do
      currentToken=`echo $classpath | cut -f$count -d " "`
      classpathToken=`echo $currentToken | cut -f$count -d " " | grep "$suffixstring" |grep "am_sdk.jar"`
      if [ "$classpathToken" != "" ]; then
          exist=1
      fi
      count=`expr $count + 1`
  done

return $exist
}

###############################################
# determine web container type
###############################################

check_web_container() {
  WEB_CONTAINER=`$GREP com.sun.identity.webcontainer= $AMCONFIG | sed -e "s#com.sun.identity.webcontainer=##"`
  $ECHO
  if [ $WEB_CONTAINER = "IAS7.0" ]; then
    AS7_INSTANCE=`$GREP '^com.iplanet.am.admin.cli.certdb.dir' $AMCONFIG \
        | $SED -e 's/com.iplanet.am.admin.cli.certdb.dir=//g' \
        | $SED -e 's/\/config//g'`
    while [ 1 ]; do
      $ECHO "What is the path of Application Server instance [$AS7_INSTANCE] \c"
      read ANS
      if [ x$ANS != "x" ]; then
        AS7_INSTANCE=$ANS
      fi
      if [ -x $AS7_INSTANCE/bin/startserv ]; then
        break
      else
        $ECHO "\nBad AS INSTANCE entered !"
        $ECHO
      fi
    done

  # WS6.1
  else
    while [ 1 ]; do
      WS61_INSTANCE="https-`hostname`.`domainname`"
      WS61_DIR="$BASE_DIR/SUNWwbsvr/$WS61_INSTANCE"
      $ECHO "What is the path of the WS 6.1 instance [$WS61_DIR] \c"
      read ANS
      if [ x$ANS != "x" ]; then
        WS61_DIR=$ANS
      fi
      if [ -x $WS61_DIR/start ]; then
        break
      else
        $ECHO "\nBad WS 6.x basedir entered !"
        $ECHO
      fi
    done
  fi

  # shared values
  IS_SERVICES_URI=`$GREP "^com.iplanet.am.services.deploymentDescriptor" $AMCONFIG | $SED -e 's/com.iplanet.am.services.deploymentDescriptor=\///g'`

  IS_CONSOLE_URI=`$GREP "^com.iplanet.am.console.deploymentDescriptor" $AMCONFIG | $SED -e 's/com.iplanet.am.console.deploymentDescriptor=\///g'`
}

##############################################################
#
# Test if common domain services package is installed.
#
##############################################################
check_for_fcd() {
   pkginfo -q SUNWamfcd
   if [ $? -eq 0 ]; then
      fcd="yes"
   else
      fcd="no"
   fi
}

##############################################################
#
# Test if cross domain sso package is installed.
#
##############################################################
check_for_cds() {
   pkginfo -q SUNWamcds
   if [ $? -eq 0 ]; then
      cds="yes"
   else
      cds="no"
   fi
}

##############################################################
#
# Test if samples are installed.
#
##############################################################
check_for_sam() {
   pkginfo -q SUNWamsam
   if [ $? -eq 0 ]; then
      sam="yes"
   else
      sam="no"
   fi
}

##############################################################
#
# Test if console is deployed on app server.
#
##############################################################
check_for_sac() {
   pkginfo -q SUNWamsac
   if [ $? -eq 0 ]; then
      sac="yes"
   else
      sac="no"
   fi
}

##############################################################
#
# Test if console is deployed on web logic.
#
##############################################################
check_for_wlc() {
   pkginfo -q SUNWamwlc
   if [ $? -eq 0 ]; then
      wlc="yes"
   else
      wlc="no"
   fi
}

##############################################################
#
# Test if console is deployed on web sphere.
#
##############################################################
check_for_wsc() {
   pkginfo -q SUNWamwsc
   if [ $? -eq 0 ]; then
      wsc="yes"
   else
      wsc="no"
   fi
}

##############################################################
#
# Find a block of code from start position to end position 
# and save to a file
#
##############################################################
find_block() {
  FILE=$1
  START_TAG=$2
  END_TAG=$3
  SAVE_IN_FILE=$4

  $NAWK '
    BEGIN {
      IN_REPLACE = 0;
    };
    {
      if (index($0, START_TAG) > 0) {
        printf("%s\n", $0);
        IN_REPLACE = 1;
      }
      else if (index($0, END_TAG) > 0) {
        if (IN_REPLACE == 1) {
          printf("%s\n", $0);
        }
        IN_REPLACE = 0;
      }
      else {
        if (IN_REPLACE == 1) {
          printf("%s\n", $0);
        }
      }
    };
    END {};
  ' START_TAG="$START_TAG" END_TAG="$END_TAG" $FILE > $SAVE_IN_FILE
}

##############################################################
#
# Replaces block of code from start position to end.
#
##############################################################
replace_block() {
  FILE=$1
  START_TAG=$2
  END_TAG=$3
  NEW_TEXT_FILE=$4

  $CP $FILE $FILE-tmp
  $NAWK 'BEGIN {
           IN_REPLACE = 0;
         };
         {
           if (index($0, START_TAG) > 0) {
            while (getline str < NEW_TEXT_FILE > 0) {
              if (length(str) > 0) {
                printf("%s\n", str);
              }
            }
             IN_REPLACE = 1;
           } else if (index($0, END_TAG) > 0) {
             if (IN_REPLACE == 0) {
               printf("%s\n", $0);
             }
             IN_REPLACE = 0;
           } else {
             if (IN_REPLACE == 0) {
               printf("%s\n", $0);
             }
           }
         };
         END {};' START_TAG="$START_TAG" END_TAG="$END_TAG" NEW_TEXT_FILE="$NEW_TEXT_FILE" $FILE-tmp > $FILE
  $RM -f $FILE-tmp
}

##############################################################
#
# Inserts block of text at starting position.
#
##############################################################
insert_block() {
  FILE=$1
  TAG=$2
  NEW_TEXT_FILE=$3

  $CP $FILE $FILE-tmp
  $NAWK 'BEGIN {};
         {
           if (index($0, TAG) > 0) {
             while (getline str < NEW_TEXT_FILE > 0) {
               if (length(str) > 0) {
                 printf("%s\n", str);
               }
             }
             printf("%s\n", $0);
           } else {
             printf("%s\n", $0);
           }
         };
         END {};' TAG="$TAG" NEW_TEXT_FILE="$NEW_TEXT_FILE" $FILE-tmp > $FILE
  $RM -f $FILE-tmp
}

##############################################################
#
# copies the named file to a backup copy to be restored if
# patch is removed.
#
##############################################################
backup_file() {
  file=$1
  if [ ! -f $file$BKFILESUFFIX ]; then
    r=`$ECHO $file | $CUT -d/ -f1`
    if [ x$r = "x" ]; then
      $ECHO "Backing up $file"
    else
      $ECHO "Backing up `pwd`/$file"
    fi
    $CP $file $file$BKFILESUFFIX
  fi
}

##############################################################
#
# replaces a line in the specified 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
$RM $file-orig-$$
}


##############################################################
#
# Replace all the occurences of the string in the file.
#
##############################################################
replace_all() {
  file=$1
  match=$2
  new=$3
  cp $file $file-orig-$$
  $SED -e "s/$match/$new/g" $file > $file-tmp
  cp $file-tmp $file
  rm $file-orig-$$ $file-tmp
}

##############################################################
#
# Gets the base install dir of the product.
#
##############################################################
get_base_dir() {
  check_for_sdk
  if [ "$sdk" = "yes" ]; then
    pkg="SUNWamsdk"
  else
     check_for_fcd
     if [ "$fcd" = "yes" ]; then
        pkg="SUNWamfcd"
     else
         check_for_cds
         if [ "$cds" = "yes" ]; then
           pkg="SUNWamcds"
         else
           exit
         fi
     fi
  fi

  BASE_DIR=`pkginfo -r $pkg`
}

##############################################################
#
# update the .version string
#
##############################################################
update_version_string() {
  cd /etc/opt/SUNWam/config
  if [ ! -f $VERSION_FILE ]; then
    $ECHO "Sun Java System Identity Server version 2004Q2" > $VERSION_FILE
  fi
  backup_file $VERSION_FILE
  $ECHO "$PATCH_ID" >> $VERSION_FILE
}

##############################################################
#
# Run an ldap search sending the results to the specified file
#
##############################################################
get_ldap_command() {
  DIR_MANAGER="cn=Directory Manager"
  $ECHO
  $ECHO "What is the dn of the Directory Manager [$DIR_MANAGER] \c"
  read ANS
  if [ "$ANS" != "" ]; then
    DIR_MANAGER=$ANS
  fi

  while [ 1 ]; do
    $ECHO "What is the password for the Directory Manager [] \c"
    stty -echo
    read PASSWORD_ANS
    stty echo
    if [ "$PASSWORD_ANS" != "" ]; then
	PASSWORD=$PASSWORD_ANS
	$ECHO
      break
    else
      $ECHO "\nPlease enter the password \c"
    fi
    $ECHO
  done

  ROOT_SUFFIX=`$GREP com.iplanet.am.rootsuffix $AMCONFIG | \
    $AWK ' BEGIN { FS="=" } { ORS="" } { print $2; for (i=3;i<=NF;i++ ) print "=" $i } `

  LDAPSEARCH=$INSTALL_DIR/bin/ldapsearch
  LDAPMODIFY=$INSTALL_DIR/bin/ldapmodify
  WHP="-w $PASSWORD -h $DS_HOST -p $DS_PORT"
  if [ "$DS_SSL" = "true" ]; then
    LDAPSEARCH="$LDAPSEARCH -Z -B -P $CERTDB $WHP"
    LDAPMODIFY="$LDAPMODIFY -Z -c -P $CERTDB $WHP"
  else
    LDAPSEARCH="$LDAPSEARCH -B $WHP"
    LDAPMODIFY="$LDAPMODIFY -c $WHP"
  fi
}

ldap_search() {
#  $ECHO "$LDAPSEARCH -D \"$DIR_MANAGER\" -b \"ou=1.$3,ou=$1,ou=services,$ROOT_SUFFIX\" \"(objectclass=*)\" sunserviceschema > $2"
  $LDAPSEARCH -D "$DIR_MANAGER" -b "ou=1.$3,ou=$1,ou=services,$ROOT_SUFFIX" "(objectclass=*)" sunserviceschema > $2
}

##############################################################
#
# Run an ldap modify command.
#
##############################################################
ldap_modify() {
  `$LDAPMODIFY -D "$DIR_MANAGER" -f $1 > /dev/null 2>&1`
}

ldap_modify_schema() {
  BASE64="$JDK/bin/java -classpath $INSTALL_DIR/lib/am_sdk.jar com.iplanet.services.util.Base64"
  ENCODED=`$BASE64 $XMLFILE.1`
  if [ $? -ne 0 ]; then
    $ECHO "Failed to base64 encode service schema"
    $ECHO
    return
  fi

  $ECHO "dn: $SERVICE_BASE
changetype: modify
replace: sunserviceschema
sunserviceschema:: $ENCODED" > $XMLFILE
  ldap_modify $XMLFILE
}

# keep the old xml encoding setting in modified service xml file
keep_xml_encoding() {
  FILE=$1
  cd /etc/opt/SUNWam/config/xml/
  HASIT=`$GREP " encoding=" $FILE$BKFILESUFFIX | $GREP version= | \
    $GREP -v XML_ENCODING | $WC -l | $SED -e 's/ //g'`
  if [ $HASIT != "1" ]; then
    $ECHO "$FILE does not have a proper xml encoding setting"
    return
  fi

  $CP $FILE $FILE.1
  $GREP " encoding=" $FILE$BKFILESUFFIX | $GREP version= | \
    $GREP -v XML_ENCODING > $FILE
  $GREP -v " encoding=" $FILE.1 >> $FILE
  $RM $FILE.1
}

##############################################################
#
# Modify iplanet-am-auth-login-success-url of iPlanetAMAuthService
#
##############################################################
modifyServiceSchema() {
  pkginfo -q SUNWamsvcconfig
  if [ $? -ne 0 ]; then
    return
  fi

  if [ -d $BASE_DIR/SUNWam/ldaplib/ldapsdk ]; then
    LD_LIBRARY_PATH=$BASE_DIR/SUNWam/ldaplib/ldapsdk:$BASE_DIR/SUNWam/lib/jss:/usr/lib/mps/secv1:/usr/lib/mps
    export LD_LIBRARY_PATH

    DIR_MANAGER=`$GREP "DIR_MANAGER=" /tmp/.patch.ans |tail -1| $SED -e "s/DIR_MANAGER=//g"`
    PASSWORD=`$GREP "PASSWORD=" /tmp/.patch.ans |tail -1| $SED -e "s/DS_PASSWORD=//g"`
    DS_HOST=`$GREP com.iplanet.am.directory.host $AMCONFIG | $AWK ' BEGIN { FS="=" } {print $2}`
    DS_PORT=`$GREP com.iplanet.am.directory.port $AMCONFIG | $AWK ' BEGIN { FS="=" } {print $2}`
    DS_SSL=`$GREP com.iplanet.am.directory.ssl.enabled $AMCONFIG | $SED -e "s/com.iplanet.am.directory.ssl.enabled=//g"`
    CERTDB_DIR=`$GREP "^com.iplanet.am.admin.cli.certdb.dir" $AMCONFIG | $SED -e "s/com.iplanet.am.admin.cli.certdb.dir=//g"`
    CERTDB_PREFIX=`$GREP "^com.iplanet.am.admin.cli.certdb.prefix" $AMCONFIG | $SED -e "s/com.iplanet.am.admin.cli.certdb.prefix=//g"`
    CERTDB=$CERTDB_DIR/"$CERTDB_PREFIX"cert8.db
    XMLFILE=/tmp/iPlanetAMServiceSchema.xml.$$
    NEWTMPFILE=/tmp/.new_file
    get_ldap_command
    modifyAuthService
    modifyProviderConfigService
    modifyAuthSafeWordService
    modifyAdminConsoleService
    addAttributeAMAuthService
    $RM $XMLFILE $XMLFILE.1 $NEWTMPFILE
  fi
}

modifyAuthService() {
  $ECHO
  $ECHO "Modify iplanet-am-auth-login-success-url of service schema iPlanetAMAuthService to be /${IS_CONSOLE_URI:-amconsole}"
  keep_xml_encoding amAuth.xml
  ldap_search iPlanetAMAuthService $XMLFILE 0

  SERVICE_BASE=`$HEAD -1 $XMLFILE`
  BEGIN=`$GREP "^sunserviceschema=" $XMLFILE`
  $SED -n -e "/$BEGIN/,/<\/ServicesConfiguration>/p" $XMLFILE | $SED -e "s/sunserviceschema=//g" > $XMLFILE.1
  $ECHO "                <AttributeSchema cosQualifier=\"default\"  i18nKey=\"a133\"  name=\"iplanet-am-auth-login-success-url\"  syntax=\"string\"  type=\"list\" >
                    <DefaultValues><Value>/${IS_CONSOLE_URI:-amconsole}</Value></DefaultValues>
                </AttributeSchema>" > $NEWTMPFILE
  replace_block $XMLFILE.1 iplanet-am-auth-login-success-url AttributeSchema $NEWTMPFILE
  replace_block amAuth.xml iplanet-am-auth-login-success-url AttributeSchema $NEWTMPFILE
  ldap_modify_schema

  $ECHO "Do you want to change all sunkeyvalue of iplanet-am-auth-login-success-url to be /${IS_CONSOLE_URI:-amconsole} at org/suborg level? y/n [n] \c"
  read ANS
  if [ x$ANS != "xy" ]; then
    $RM $XMLFILE $XMLFILE.1 $NEWTMPFILE
    return
  fi
      
  # get auth core service settings of org/suborg
  DNS=`$LDAPSEARCH -D "$DIR_MANAGER" -b "$ROOT_SUFFIX" "(&(ou=1.0)(ou=iPlanetAMAuthService))" nsrole`
  for DN in $DNS
  do
    DN=ou=default,ou=OrganizationConfig,$DN
    $ECHO "Modify sunkeyvalue of iplanet-am-auth-login-success-url in $DN to be /${IS_CONSOLE_URI:-amconsole}"
    # find and remove sunkeyvalue of iplanet-am-auth-login-success-url
    SKV=`$LDAPSEARCH -D "$DIR_MANAGER" -b "$DN" "(objectclass=*)" sunkeyvalue | $GREP iplanet-am-auth-login-success-url | $CUT -d= -f2-`
    if [ x$SKV != "x" ]; then
      $ECHO "dn: $DN
changetype: modify
delete: sunkeyvalue
sunkeyvalue: $SKV" > $NEWTMPFILE
      ldap_modify $NEWTMPFILE
    fi

    # add the new sunkeyvalue back
    $ECHO "dn: $DN
changetype: modify
add: sunkeyvalue
sunkeyvalue: iplanet-am-auth-login-success-url=/${IS_CONSOLE_URI:-amconsole}" > $NEWTMPFILE
    ldap_modify $NEWTMPFILE
  done
}

modifyProviderConfigService() {
  $ECHO
  $ECHO "Add new AttributeSchema sunIdentityServerProviderAssertionIssuer of SubSchema EntityDescriptor/Provider/LocalConfiguration of service schema iPlanetAMProviderConfigService"
  keep_xml_encoding amProviderConfig.xml
  ldap_search iPlanetAMProviderConfigService $XMLFILE 1

  HASIT=`$GREP "sunIdentityServerProviderAssertionIssuer" $XMLFILE | \
    $WC -l | $SED -e 's/ //g'`
  if [ $HASIT != "0" ]; then
    $ECHO "AttributeSchema sunIdentityServerProviderAssertionIssuer exists"
    return
  fi

  SERVICE_BASE=`$HEAD -1 $XMLFILE`
  BEGIN=`$GREP "^sunserviceschema=" $XMLFILE`
  $SED -n -e "/$BEGIN/,/<\/ServicesConfiguration>/p" $XMLFILE | $SED -e "s/sunserviceschema=//g" > $XMLFILE.1

  $ECHO "                                                <AttributeSchema name=\"sunIdentityServerProviderAssertionIssuer\"  type=\"single\"  syntax=\"string\"  i18nKey=\"a239\">
                                                </AttributeSchema>" > $NEWTMPFILE
  insert_block $XMLFILE.1 iplanet-am-assertion-limit $NEWTMPFILE
  ldap_modify_schema
}

modifyAuthSafeWordService() {
  $ECHO
  $ECHO "Modify service schema iPlanetAMAuthSafeWordService with following:"
  keep_xml_encoding amAuthSafeWord.xml
  ldap_search iPlanetAMAuthSafeWordService $XMLFILE 0
  DIR=`$GREP '/auth/safeword/safe.log' amAuthSafeWord.xml$BKFILESUFFIX | \
    $CUT -d">" -f2 | $CUT -d"<" -f1 | $SED "s#/auth/safeword/safe.log##g"`
  $SED "s#IS_INSTALL_VARDIR/IS_PRODNAME#$DIR#g" amAuthSafeWord.xml > amAuthSafeWord.xml.1
  $MV amAuthSafeWord.xml.1 amAuthSafeWord.xml

  HASIT=`$GREP "iplanet-am-auth-safeword-log-enable" $XMLFILE | \
    $WC -l | $SED -e 's/ //g'`
  if [ $HASIT != "0" ]; then
    $ECHO "iPlanetAMAuthSafeWordService was updated already"
    return
  fi

  SERVICE_BASE=`$HEAD -1 $XMLFILE`
  BEGIN=`$GREP "^sunserviceschema=" $XMLFILE`
  $SED -n -e "/$BEGIN/,/<\/ServicesConfiguration>/p" $XMLFILE | $SED -e "s/sunserviceschema=//g" > $XMLFILE.1

  $ECHO "1> Change i18nKey of AttributeSchema iplanet-am-auth-safeword-auth-level from a105 to a110" 
  $SED -e "s/i18nKey=\"a105/i18nKey=\"a110/" $XMLFILE.1 > $XMLFILE.2
  $MV $XMLFILE.2 $XMLFILE.1

  $ECHO "2> Change i18nKey of AttributeSchema iplanet-am-auth-safeword-log-path from a104 to a105"
  $SED -e "s/i18nKey=\"a104/i18nKey=\"a105/" $XMLFILE.1 > $XMLFILE.2
  $MV $XMLFILE.2 $XMLFILE.1

  $ECHO "3> Replace AttributeSchema iplanet-am-auth-safeword-log-level with a new one and add five new AttributeSchema iplanet-am-auth-safeword-timeout, iplanet-am-auth-safeword-client-type, iplanet-am-auth-safeword-eassp-version, iplanet-am-auth-safeword-minimum-strength and iplanet-am-auth-safeword-log-enable"
  $ECHO "                <AttributeSchema name=\"iplanet-am-auth-safeword-log-enable\"
                    type=\"single\"
                    syntax=\"boolean\"
                    i18nKey=\"a103\">
                   <DefaultValues>
                         <Value>true</Value>
                   </DefaultValues>
                 </AttributeSchema>
               <AttributeSchema name=\"iplanet-am-auth-safeword-log-level\"
                     type=\"single_choice\"
                     syntax=\"string\"
                     i18nKey=\"a104\">
                   <ChoiceValues>
                         <ChoiceValue i18nKey=\"none\">NONE</ChoiceValue>
                         <ChoiceValue i18nKey=\"info\">INFO</ChoiceValue>
                         <ChoiceValue i18nKey=\"error\">ERROR</ChoiceValue>
                         <ChoiceValue i18nKey=\"debug\">DEBUG</ChoiceValue>
                     </ChoiceValues>
		    <DefaultValues>
                        <Value>DEBUG</Value>
		    </DefaultValues>
                </AttributeSchema>
                <AttributeSchema name=\"iplanet-am-auth-safeword-timeout\"
                    type=\"single\"
                    syntax=\"number\"
                    i18nKey=\"a106\">
                    <DefaultValues>
                        <Value>120</Value>
                    </DefaultValues>
                </AttributeSchema>
                 <AttributeSchema name=\"iplanet-am-auth-safeword-client-type\"
                     type=\"single\"
                     syntax=\"string\"
                     i18nKey=\"a107\">
                     <DefaultValues>
                      <Value></Value>
                     </DefaultValues>
              </AttributeSchema>
              <AttributeSchema name=\"iplanet-am-auth-safeword-eassp-version\"
                     type=\"single_choice\"
                     syntax=\"number\"
                     i18nKey=\"a108\">
                     <ChoiceValues>
                          <ChoiceValue>101</ChoiceValue>
                          <ChoiceValue>200</ChoiceValue>
                          <ChoiceValue>201</ChoiceValue>
                     </ChoiceValues>
                     <DefaultValues>
                      <Value>201</Value>
                     </DefaultValues>
               </AttributeSchema>
               <AttributeSchema name=\"iplanet-am-auth-safeword-minimum-strength\"
                     type=\"single\"
                     syntax=\"number\"
                     i18nKey=\"a109\">
                     <DefaultValues>
                      <Value>15</Value>
                     </DefaultValues>
               </AttributeSchema>" > $NEWTMPFILE
  replace_block $XMLFILE.1 iplanet-am-auth-safeword-log-level AttributeSchema $NEWTMPFILE
  ldap_modify_schema
}

modifyAdminConsoleService() {
  $ECHO
  $ECHO "Add default value to iplanet-am-admin-console-pre-post-processing-modules of service schema iPlanetAMAdminConsoleService"
  keep_xml_encoding amAdminConsole.xml

  ldap_search iPlanetAMAdminConsoleService $XMLFILE 0
  SERVICE_BASE=`$HEAD -1 $XMLFILE`
  BEGIN=`$GREP "^sunserviceschema=" $XMLFILE`
  $SED -n -e "/$BEGIN/,/<\/ServicesConfiguration>/p" $XMLFILE | $SED -e "s/sunserviceschema=//g" > $XMLFILE.1

  find_block $XMLFILE.1 iplanet-am-admin-console-pre-post-processing-modules AttributeSchema $NEWTMPFILE
  HASIT=`$GREP com.sun.identity.policy.plugins.SubjectReferentialIntegrityPlugin $NEWTMPFILE | $WC -l | $SED -e 's/ //g'` 
  if [ $HASIT = "1" ]; then
    $ECHO "com.sun.identity.policy.plugins.SubjectReferentialIntegrityPlugin exists as the default value of iplanet-am-admin-console-pre-post-processing-modules"
    return
  fi

  HASIT=`$GREP DefaultValues $NEWTMPFILE | $WC -l | $SED -e 's/ //g'`
  # DefaultValues exists
  VALUES=
  if [ $HASIT != "0" ]; then
    VALUES=`$GREP '<Value>' $NEWTMPFILE | \
      $AWK 'BEGIN { FS="<" } { for (i=2; i<NF; i++) printf("<%s\n", $i) }' | \
      $GREP -v DefaultValues | \
      $AWK '{ printf("%s", $0) }' `
  fi

  $ECHO "                <AttributeSchema cosQualifier=\"default\"  i18nKey=\"d124\"  name=\"iplanet-am-admin-console-pre-post-processing-modules\"  syntax=\"string\"  type=\"list\" >
                    <DefaultValues><Value>com.sun.identity.policy.plugins.SubjectReferentialIntegrityPlugin</Value>$VALUES</DefaultValues>
                </AttributeSchema>" > $NEWTMPFILE
  replace_block $XMLFILE.1 iplanet-am-admin-console-pre-post-processing-modules AttributeSchema $NEWTMPFILE
  ldap_modify_schema
  replace_block amAdminConsole.xml iplanet-am-admin-console-pre-post-processing-modules AttributeSchema $NEWTMPFILE

  # add to default org
  DN="ou=default,ou=OrganizationConfig,ou=1.0,ou=iPlanetAMAdminConsoleService,ou=services,$ROOT_SUFFIX"
  HASIT=`$LDAPSEARCH -D "$DIR_MANAGER" -b "$DN" "sunkeyvalue=*" | \
    $GREP com.sun.identity.policy.plugins.SubjectReferentialIntegrityPlugin | \
    $WC -l | $SED -e 's/ //g'`
  if [ $HASIT = "0" ]; then
    $ECHO "Add com.sun.identity.policy.plugins.SubjectReferentialIntegrityPlugin to iplanet-am-admin-console-pre-post-processing-modules at the default org level"
    $ECHO "dn: $DN
changetype: modify
add: sunkeyvalue
sunkeyvalue: iplanet-am-admin-console-pre-post-processing-modules=com.sun.identity.policy.plugins.SubjectReferentialIntegrityPlugin" > $NEWTMPFILE
    ldap_modify $NEWTMPFILE
  fi
}

addAttributeAMAuthService() {
  $ECHO
  $ECHO "Add new AttributeSchema iplanet-am-auth-callback-plugins of service schema iPlanetAMAuthService "
  keep_xml_encoding amAuth.xml
  ldap_search iPlanetAMAuthService $XMLFILE 0

  HASIT=`$GREP "iplanet-am-auth-callback-plugins" $XMLFILE | \
    $WC -l | $SED -e 's/ //g'`
  if [ $HASIT != "0" ]; then
    $ECHO "AttributeSchema iplanet-am-auth-callback-plugins exists"
    return
  fi

  SERVICE_BASE=`$HEAD -1 $XMLFILE`
  BEGIN=`$GREP "^sunserviceschema=" $XMLFILE`
  $SED -n -e "/$BEGIN/,/<\/ServicesConfiguration>/p" $XMLFILE | $SED -e "s/sunserviceschema=//g" > $XMLFILE.1
  $ECHO "                                               <AttributeSchema name=\"iplanet-am-auth-callback-plugins\" type=\"list\" syntax=\"string\" i18nKey=\"a142\">
                                    </AttributeSchema>" > $NEWTMPFILE

  insert_block $XMLFILE.1 iplanet-am-auth-username-generator-class $NEWTMPFILE
  ldap_modify_schema
}

###############################################################
#
#Configure the endorsed dirs
#
###############################################################
config_endorsed_dir()
{
if [ ! -d ${INSTALL_DIR}/lib/endorsed ];then
      mkdir -p ${INSTALL_DIR}/lib/endorsed
fi
#rm -f ${INSTALL_DIR}/lib/endorsed/jaxp-api.jar
#rm -f ${INSTALL_DIR}/lib/endorsed/dom.jar
#rm -f ${INSTALL_DIR}/lib/endorsed/sax.jar
#rm -f ${INSTALL_DIR}/lib/endorsed/xsltc.jar

cd ${INSTALL_DIR}/lib/
#move_file jaxp-api.jar
#move_file dom.jar
#move_file sax.jar
#move_file xsltc.jar

  ln -s "${INSTALL_DIR}/lib/xml-apis.jar" "${INSTALL_DIR}/lib/endorsed/xml-apis.jar" 2>/dev/null
# ln -s "${INSTALL_DIR}/lib/xalan.jar" "${INSTALL_DIR}/lib/endorsed/xalan.jar" 2>/dev/null
# ln -s "${INSTALL_DIR}/lib/xercesImpl.jar" "${INSTALL_DIR}/lib/endorsed/xercesImpl.jar" 2>/dev/null

}

###############################################
# Update AS7 policy
###############################################

config_server_policy() {
  cd $AMSERVERDIR
  file=index.html
  $ECHO
  $ECHO "Updating $file"
  backup_file $file
  $MV $file $file-tmp
  $SED -e "s/DEPLOY_URI/\/${IS_SERVICES_URI:-amserver}/g" $file-tmp > $file
  $RM $file-tmp

  if [ $WEB_CONTAINER != "IAS7.0" ]; then
    return
  fi

  cd $AS7_INSTANCE/config
  file=server.policy
  $ECHO
  $ECHO "Validating & modifying $file ..."
  if [ -f $file ]; then
    thisline=`$GREP FilePermission $file | $GREP SUNWam | $WC -l | $SED -e 's/ //g'`
    if [ $thisline = "1" ]; then
      backup_file $file
      total=`$WC -l $file | $AWK '{print $1}'`
      thisline=`$GREP -n "ALL FILES" $file | $TAIL -1 | $AWK -F: '{print $1}'`
      $MV $file $file-tmp
      rest=`expr $total - $thisline`
      head -$thisline $file-tmp > $file
      $ECHO "    permission java.io.FilePermission \"/var/opt/SUNWam/logs/\*\", \"delete,write\";" >> $file
      $TAIL -$rest $file-tmp >> $file
      $RM $file-tmp
    fi
  fi
}

###############################################
# Update java classpath in server.xml
###############################################

update_classpath() {
  LIBPATH=$INSTALL_DIR/lib
  if [ $WEB_CONTAINER != "IAS7.0" ]; then
    cd $WS61_DIR/config
  else
    cd $AS7_INSTANCE/config
  fi

  SXML_FILE=server.xml
  if [ ! -w $SXML_FILE ]; then
    return 1
  fi
  backup_file server.xml

  $ECHO
  $ECHO "Updating classpath in `pwd`/$SXML_FILE"
  backup_file $SXML_FILE
  SXML_TMP_FILE=SXML_FILE.$$
  $SED -e "s;jaxp-api.jar;xml-apis.jar;g" \
       -e "s;$LIBPATH/dom.jar;;g" \
       -e "s;$LIBPATH/sax.jar;;g" \
       -e "s;$LIBPATH/xsltc.jar;;g" \
       -e "s;$LIBPATH/iaik_ssl.jar;$LIBPATH/iaik_ssl.jar:$LIBPATH/iaik_jce_full.jar;g" \
       -e "s;::;:;g" \
       $SXML_FILE > $SXML_TMP_FILE
  $MV $SXML_TMP_FILE $SXML_FILE
}

###############################################
# Replace am_auth_ui.jar and jsp files
###############################################

config_services_cp() {
  # am_auth_ui.jar
  backup_file WEB-INF/lib/am_auth_ui.jar
  $CP $TMPDIR/WEB-INF/lib/am_auth_ui.jar WEB-INF/lib/.
  # jsp files
  backup_file config/auth/default/membership.jsp
  $CP $TMPDIR/config/auth/default/membership.jsp config/auth/default/.
  backup_file config/auth/default/Login.jsp
  $CP $TMPDIR/config/auth/default/Login.jsp config/auth/default/.
  backup_file config/auth/default/new_org.jsp
  $CP $TMPDIR/config/auth/default/new_org.jsp config/auth/default/.
}

config_services() {
  $ECHO
  $ECHO "Updating am_auth_ui.jar, Login.jsp, membership.jsp and new_org.jsp"
  check_for_svc
  if [ "$svc" = "no" ]; then
    $ECHO "SUNWamsvc is not installed, no services.war ..."
    return
  fi

  cd $INSTALL_DIR 
  backup_file services.war
  cd $TMPDIR
  $JAR xf $INSTALL_DIR/services.war

  cd $INSTALL_DIR/web-src/services/
  config_services_cp

  if [ $WEB_CONTAINER = "IAS7.0" ]; then
    AMSERVERDIR=$AS7_INSTANCE/applications/j2ee-modules/${IS_SERVICES_URI:-amserver}_1
  else
    AMSERVERDIR=$WS61_DIR/is-web-apps/services
  fi

  while [ ! -f $AMSERVERDIR/WEB-INF/lib/am_auth_ui.jar ]
  do
    $ECHO
    $ECHO "What is the path of the deployment directory of /${IS_SERVICES_URI:-amserver} [$AMSERVERDIR] ? \c"
    read ANS
    if [ x$ANS != "x" ]; then
      AMSERVERDIR=$ANS
    fi
  done
  cd $AMSERVERDIR
  config_services_cp
  config_server_policy
}

###############################################
# Replace am_console.jar
###############################################

config_console() {
  $ECHO
  $ECHO "Updating amconsole.jar"
  check_for_con
  if [ "$con" = "no" ]; then
    $ECHO "SUNWamcon is not installed, no am_console.jar ..."
    return
  fi

  if [ $WEB_CONTAINER = "IAS7.0" ]; then
    file=$AS7_INSTANCE/applications/j2ee-modules/${IS_CONSOLE_URI:-amconsole}_1
  else
    file=$WS61_DIR/is-web-apps/applications
  fi

  while [ ! -f $file/WEB-INF/lib/am_console.jar ]
  do
    $ECHO
    $ECHO "What is the path of the deployment directory of /${IS_CONSOLE_URI:-amconsole} [$file] ? \c"
    read ANS
    if [ x$ANS != "x" ]; then
      file=$ANS
    fi
  done

  cd $file/WEB-INF/lib
  backup_file am_console.jar
  $CP /usr/share/lib/identity/console-war/WEB-INF/lib/am_console.jar .
}

###############################################
# Update AMConfig.properties
###############################################

update_amconfig() {
  backup_file $AMCONFIG

  # bug 2124848
  replace_line $AMCONFIG "com.sun.identity.sm.smptpport=25" "com.iplanet.am.smtpport=25"

  # bug 5015054
  defined=`$GREP com.sun.identity.url.redirect $AMCONFIG | wc -l | $SED -e "s/ //g"`
  if [ $defined = "0" ]; then
    $ECHO '/**
 * The following key are used to configure the redirect url returned by
 * Access Manager so that you can add a load balancer in front of the
 * server to handle ssl requests. AM will use the configured protocol
 * whenever request needs to be redirected to configured host.
 * The format of the value should be "protocol,hostname", for example
 * com.sun.identity.url.redirect=https,www.sun.com
 */
com.sun.identity.url.redirect=
' >> $AMCONFIG
  fi

  # bug 5060560
  defined=`$GREP com.sun.am.event.connection.idle.timeout $AMCONFIG | wc -l | $SED -e "s/ //g"`
  if [ $defined = "0" ]; then
    $ECHO '/**
 * The following properties can be used when a Load Balancer/Firewall
 * is in between the agents and the Directory Server and the persistent
 * search connections are dropped by them when TCP idle timeout happens.
 *
 * These properties make sure that the persistent searches restart
 * in such cases when the connections are dropped.
 *
 * The property 'com.sun.am.event.connection.idle.timeout' specifies
 * timeout value in minutes after which the persistent searches will be
 * restarted. Ideally, this value should be lower than the Load Balancer/
 * Firewall TCP timeout, to make sure that the persistent searches are
 * restarted before the connections are dropped. A value of '0' indicates
 * that these searches will not be restarted. By default the value is '0'
 * Note: only the connections that are timed out will be reset.
 */
com.sun.am.event.connection.idle.timeout=0
' >> $AMCONFIG
  fi

  # bug 6204178
  defined=`$GREP com.sun.identity.authentication.special.users $AMCONFIG | wc -l | $SED -e "s/ //g"`
  if [ $defined = "0" ]; then
    $ECHO '/**
 * Identifies the special user(s) for this Sun Java System Identity Server,
 * Authentication component.This user is used by Remote (Client) SDK to
 * authenticate remote Applications to Identity Server using as the full user DN
 * The user will be authenticated against the local directory server.
 * Multiple values of this special user DN are separated by "|".
 * NOTE: Usage of this property is restricted to Authentication component only
 * com.sun.identity.authentication.special.users=cn=dsameuser,ou=DSAME Users,ORG_BASE|cn=amService-UrlAccessAgent,ou=DSAME Users,ORG_BASE
 * replace ORG_BASE acoording to the domain settings
 */
com.sun.identity.authentication.special.users=
' >> $AMCONFIG
  fi
}

##############################################################
#
# Main processing
#
##############################################################

# check for sdk only installation, if console package is not installed exit
check_for_con

get_base_dir
INSTALL_DIR=$BASE_DIR/SUNWam
AMCONFIG=/etc/opt/SUNWam/config/AMConfig.properties
if [ "$con" = "no" ]; then
  AMCONFIG=/opt/SUNWam/lib/AMConfig.properties
fi

JDK=`$GREP com.iplanet.am.jdk.path $AMCONFIG | $SED -e "s/com.iplanet.am.jdk.path=//g"`
JAR="$JDK/bin/jar"

TMPDIR=/tmp/AM62-$PATCH_ID
/usr/bin/mkdir -p $TMPDIR

if [ "$con" = "no" ]; then
  # since SDK only installation update version string and AMConfig
  update_version_string
  update_amconfig 
  exit 0
fi

check_web_container
modifyServiceSchema
config_services
config_console
config_endorsed_dir
update_classpath
update_amconfig
update_version_string

