#!/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=115766-07
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
}


##############################################################
#
# 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
    $ECHO "Backing up `pwd`/$file"
    $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() {
  $LDAPSEARCH -D "$DIR_MANAGER" -b "ou=1.0,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`
}

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

  BASE64="$JDK/bin/java -classpath $INSTALL_DIR/lib/am_sdk.jar com.iplanet.services.util.Base64"
  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/iPlanetAMAuthService.xml.$$
    get_ldap_command
    $ECHO "Modify iplanet-am-auth-login-success-url of service schema iPlanetAMAuthService to be /${IS_CONSOLE_URI:-amconsole}"
    ldap_search iPlanetAMAuthService $XMLFILE
    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>" > /tmp/.new_file
    replace_block $XMLFILE.1 iplanet-am-auth-login-success-url AttributeSchema /tmp/.new_file
    cd /etc/opt/SUNWam/config/xml
    backup_file amAuth.xml
    replace_block amAuth.xml iplanet-am-auth-login-success-url AttributeSchema /tmp/.new_file
    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

    $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 /tmp/.new_file
      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" > /tmp/.new_file
        ldap_modify /tmp/.new_file
      fi

      # add the new sunkeyvalue back
      $ECHO "dn: $DN
changetype: modify
add: sunkeyvalue
sunkeyvalue: iplanet-am-auth-login-success-url=/${IS_CONSOLE_URI:-amconsole}" > /tmp/.new_file
      ldap_modify /tmp/.new_file
    done
    $RM $XMLFILE $XMLFILE.1 /tmp/.new_file
  fi
}

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

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

get_base_dir
INSTALL_DIR=$BASE_DIR/SUNWam
AMCONFIG=/etc/opt/SUNWam/config/AMConfig.properties
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

check_web_container
modifyAuthService
config_services
config_console
config_endorsed_dir
update_classpath
update_version_string

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