#!/bin/sh

# Copyright  2005 Sun Microsystems, Inc.  All rights reserved.
#
# Sun Microsystems, Inc. has intellectual property rights relating to
# technology embodied in the product that is described in this document.
# In particular, and without limitation, these intellectual property rights
# may include one or more of the U.S. patents listed at
# http://www.sun.com/patents and one or more additional patents or pending
# patent applications in the U.S. and in other countries.
#
# U.S. Government Rights - Commercial software.  Government users are subject
# to the Sun Microsystems, Inc. standard license agreement and applicable
# provisions of the FAR and its supplements.
#
# Use is subject to license terms.
#
# This distribution may include materials developed by third parties.Sun,
# Sun Microsystems and  the Sun logo are trademarks or registered trademarks
# of Sun Microsystems, Inc. in the U.S. and other countries.  
#
# Copyright  2005 Sun Microsystems, Inc. Tous droits rservs.
# Sun Microsystems, Inc. dtient les droits de proprit intellectuels relatifs
#  la technologie incorpore dans le produit qui est dcrit dans ce document.
# En particulier, et ce sans limitation, ces droits de proprit
# intellectuelle peuvent inclure un ou plus des brevets amricains lists
#  l'adresse http://www.sun.com/patents et un ou les brevets supplmentaires
# ou les applications de brevet en attente aux Etats - Unis et dans les
# autres pays.
#
# L'utilisation est soumise aux termes du contrat de licence.
#
# Cette distribution peut comprendre des composants dvelopps par des
# tierces parties.
#
# Sun,  Sun Microsystems et  le logo Sun sont des marques de fabrique ou des
# marques dposes de Sun Microsystems, Inc. aux Etats-Unis et dans
# d'autres pays.


# assume that Access Manager instance installed locally on this box
# and this script is to deploy it further to weblogic server 8.1 and 
# make further necessary changes to Access Manager & weblogic server 8.1 site
#

if [ ${#} -eq 0 ]; then
     echo "Please use amconfig to configure Access Manager." 
     exit 
elif [ ${#} -eq 2 -a $1 = "-s" ]; then
    if [ ! -f $2 ]; then 
        echo "Silent file not found: $2" 
        exit 1
    fi 
    IS_SILENT_INSTALL_FILE=$2 
    export IS_SILENT_INSTALL_FILE 
else 
    echo "Please use amconfig to configure Access Manager." 
    exit 
fi

# Verify that amutils variable is set
if [ "$AMUTILS" = "" ]; then
  if [ "$OSTYPE" = "Linux" ]; then
    if [ -f /opt/sun/identity/bin/amutils ]; then
      AMUTILS=/opt/sun/identity/bin/amutils
    else
      echo "Please use amconfig to configure Access Manager."
      exit 1
    fi
  else
      if [ -f /opt/SUNWam/bin/amutils ]; then
        AMUTILS=/opt/SUNWam/bin/amutils
      else
        echo "Please use amconfig to configure Access Manager."
        exit 1
      fi
  fi 
fi
. $AMUTILS

# variables needed for this script

SERVER_URI="$SERVER_PROTOCOL://$SERVER_HOST:$SERVER_PORT"


uri1="${CONSOLE_DEPLOY_URI:-/amconsole}"
uri2="${SERVER_DEPLOY_URI:-/amserver}"
uri3="${PASSWORD_DEPLOY_URI:-/ampassword}"
uri4="${COMMON_DEPLOY_URI:-/amcommon}"

if [ $DEPLOY_LEVEL -eq 2 -o $DEPLOY_LEVEL -eq 12 ]; then
    CONSOLE_DEPLOY_URI=$uri2
    uri1=$uri2
fi

# WL8.1 variables need to be set and used here

WL8_HOSTNAME=`$ECHO $WL8_HOST |nawk -F. '{print $1}'`
WL8_CONFIG_BASE=$WL8_CONFIG_LOCATION/$WL8_DOMAIN
export WL8_CONFIG_BASE
WL8_INSTANCE_HOST=$WL8_HOSTNAME
export WL8_INSTANCE_HOST
WL8_CONFILES="$WL8_CONFIG_BASE/startWebLogic.sh $WL8_CONFIG_BASE/startManagedWebLogic.sh"
export WL8_CONFILES
BACKUP_DIR=$WL8_CONFIG_BASE/.dsame
export BACKUP_DIR

# add path for wdeploy
LIB_DIR=${PKGDIR}/lib

# add path for asadmin
PATH=${WL8_INSTANCE}/bin:${WL8_CONFIG_BASE}:$JAVA_HOME/bin:$PATH
export PATH
LD_LIBRARY_PATH=$JSS_SO_PATH:$NSS_SO_PATH:$NSPR_SO_PATH

if [ "$OSTYPE" = "Linux" ]; then
        LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${JAVA_HOME}/jre/lib/i386/native_threads:${JAVA_HOME}/jre/lib/i386/server:${JAVA_HOME}/jre/lib/i386
else
        LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${PKGDIR}/lib:${PKGDIR}/ldaplib/ldapsdk:$WL8_HOME/server/lib
fi
export LD_LIBRARY_PATH

CLASSPATH=$LIB_DIR/am_sdk.jar:$LIB_DIR/ldapjdk.jar:$LIB_DIR/am_services.jar:$LIB_DIR:$PKGDIR/locale:$JSS_JAR_FILE:$LIB_DIR/jaas.jar:$LIB_DIR/jaxp-api.jar:$LIB_DIR/sax.jar:$LIB_DIR/xercesImpl.jar:$LIB_DIR/dom.jar:/$CONFIG_DIR:${WL8_INSTANCE}/server/lib/weblogic.jar
export CLASSPATH
WEBAPPS_SOURCE_DIR=$PKGDIR/web-src
CONSOLE_DIR=$WEBAPPS_SOURCE_DIR/applications
CONSOLE_ONLY_DEPLOY_DIR=$WEBAPPS_SOURCE_DIR/remote_console
PASSWORD_DIR=$WEBAPPS_SOURCE_DIR/password
COMMON_DIR=$WEBAPPS_SOURCE_DIR/common
SERVICES_DIR=$WEBAPPS_SOURCE_DIR/services
CONSOLE_DEPLOY_DIR=$WL8_DEPLOY_DIR/applications
PASSWORD_DEPLOY_DIR=$WL8_DEPLOY_DIR/password
COMMON_DEPLOY_DIR=$WL8_DEPLOY_DIR/common
SERVICES_DEPLOY_DIR=$WL8_DEPLOY_DIR/services
notification_url=$SERVER_PROTOCOL://$SERVER_HOST:$SERVER_PORT$SERVER_DEPLOY_URI/notificationservice

backupConfig()
{
 
  if [ ! -d $BACKUP_DIR ];then
    mkdir -p $BACKUP_DIR
  fi
  for file in $WL8_CONFILES
  do
   if [ ! -f $BACKUP_DIR/$file ];then
  	cp -f $file $BACKUP_DIR/
   fi
  done
}

setJavaOptions()
{
  # create ${WL8_CONFIG_BASE}/.java.login.config

  file="${WL8_CONFIG_BASE}/.java.login.config"

cat <<EOF > $file
{
  weblogic.security.internal.ServerLoginModule required debug=true;
};
EOF
}

configureJavaSecurity()
{
# change java.security of weblogic jdk
file=${WL8_JDK_HOME}/jre/lib/security/java.security
cat <<EOF >> $file
login.configuration.provider=com.sun.identity.authentication.config.AMConfiguration
EOF
}

configureServerPolicy()
{
  # modifying weblogic.policy
  file="$WL8_INSTANCE/server/lib/weblogic.policy"
  add_to_end "$file" "// Access Manager RELATED ADDITIONS"
  add_to_end "$file" "grant {"
  add_to_end "$file" "    permission java.lang.RuntimePermission \"modifyThreadGroup\";"
  add_to_end "$file" "    permission java.lang.RuntimePermission \"setFactory\";"
  add_to_end "$file" "    permission java.lang.RuntimePermission \"accessClassInPackage.*\";"
  add_to_end "$file" "    permission java.lang.RuntimePermission \"shutdownHooks\";"
  add_to_end "$file" "    permission java.util.logging.LoggingPermission \"control\";"
  add_to_end "$file" "    permission java.util.PropertyPermission \"java.util.logging.config.class\", \"write\";"
  add_to_end "$file" "    permission java.security.AllPermission;"
  add_to_end "$file" "    permission java.io.FilePermission \"<<ALL FILES>>\", \"execute,delete\";"
  add_to_end "$file" "    permission javax.security.auth.AuthPermission \"getLoginConfiguration\";"
  add_to_end "$file" "    permission javax.security.auth.AuthPermission \"setLoginConfiguration\";"
  add_to_end "$file" "    permission javax.security.auth.AuthPermission \"modifyPrincipals\";"
  add_to_end "$file" "    permission javax.security.auth.AuthPermission \"createLoginContext.*\";"
  add_to_end "$file" "    permission java.security.securityPermission \"insertProvider.Mozilla-JSS\";"
  add_to_end "$file" "    permission javax.security.auth.AuthPermission \"putProviderProperty.Mozilla-JSS\";"
  add_to_end "$file" "    permission java.security.SecurityPermission \"putProviderProperty.Mozilla-JSS\";"
  add_to_end "$file" "    permission java.security.SecurityPermission \"insertProvider.Mozilla-JSS\";"
  add_to_end "$file" "    permission java.security.SecurityPermission \"removeProvider.SUN\";"
  add_to_end "$file" "    permission java.security.SecurityPermission \"insertProvider.SUN\";"
  add_to_end "$file" "    permission java.security.SecurityPermission \"removeProvider.Mozilla-JSS\";"
  add_to_end "$file" "    permission javax.security.auth.AuthPermission \"doAs\";"
  add_to_end "$file" "    permission java.util.PropertyPermission \"java.security.krb5.realm\", \"write\";"
  add_to_end "$file" "    permission java.util.PropertyPermission \"java.security.krb5.kdc\", \"write\";"
  add_to_end "$file" "    permission java.util.PropertyPermission \"java.security.auth.login.config\", \"write\";"
  add_to_end "$file" "    permission javax.security.auth.kerberos.ServicePermission \"*\", \"accept\";"
  add_to_end "$file" "};"
  add_to_end "$file" "// END OF ADDITIONS FOR IS"
}

configureEndorsedDirs()
{
  if [ ! -d ${LIB_DIR}/endorsed ];then
      mkdir -p ${LIB_DIR}/endorsed
  fi
  ln -s "${LIB_DIR}/xalan.jar" "${LIB_DIR}/endorsed/xalan.jar" 2>/dev/null
  ln -s "${LIB_DIR}/xercesImpl.jar" "${LIB_DIR}/endorsed/xercesImpl.jar" 2>/dev/null
  ln -s "${LIB_DIR}/sax.jar" "${LIB_DIR}/endorsed/sax.jar" 2>/dev/null
  ln -s "${LIB_DIR}/dom.jar" "${LIB_DIR}/endorsed/dom.jar" 2>/dev/null
  ln -s "${LIB_DIR}/xsltc.jar" "${LIB_DIR}/endorsed/xsltc.jar" 2>/dev/null
}

# configure weblogic
configureWL8()
{
  $ECHO "Checking if WebLogic is already configured for Access Manager."
  entry=`grep am_sdk.jar $WL8_CONFIG_BASE/startWebLogic.sh`
  if [ "$entry" = "" ];then
    $ECHO "Not previously configured. Configuring WebLogic for Access Manager"
    backupConfig
    setJavaOptions
    configureServerPolicy
    #configureJavaSecurity
    #configureEndorsedDirs
    setClassPath
    # update_saml_config

    # online help link to webserver doc root
    # ln -s $PKGDIR/public_html/online_help $WL8_HOME/docs/online_help    2>/dev/null
  fi

  # Update the server entry.
  if [ "$NEW_INSTANCE" = "true" -a "$DIRECTORY_MODE" = "4" ]; then
    addServerEntry
  elif [ "$DIRECTORY_MODE" = "2" ]; then
    addServerEntry
  fi

  # change the AMConfig.properties at the end
  enable_jce
}

update_saml_config()
{
currpwd=`pwd`
samldir=/tmp/samlconfig-$$
if [ -d $samldir ];then
 rm -fr $samldir
fi
mkdir -p $samldir
cd $samldir
file="META-INF/services/javax.xml.soap.SOAPConnectionFactory"
${WL8_JDK_HOME}/bin/jar -xf ${WL8_INSTANCE}/server/lib/webservices.jar $file

rm -f $file
$ECHO "javax.xml.soap.SOAPConnectionFactory" > $file

${WL8_JDK_HOME}/bin/jar -uf ${WL8_INSTANCE}/server/lib/webservices.jar $file

cd $currpwd
rm -fr $samldir
}

restore_saml_config()
{
currpwd=`pwd`
samldir=/tmp/samlconfig-$$
if [ -d $samldir ];then
 rm -fr $samldir
fi
mkdir -p $samldir
cd $samldir
file="META-INF/services/javax.xml.soap.SOAPConnectionFactory"
${WL8_JDK_HOME}/bin/jar -xf ${WL8_INSTANCE}/server/lib/webservices.jar $file

rm -f $file
$ECHO "weblogic.webservice.core.soap.SOAPConnectionFactoryImpl" > $file

${WL8_JDK_HOME}/bin/jar -uf ${WL8_INSTANCE}/server/lib/webservices.jar $file

cd $currpwd
rm -fr $samldir
}

setClassPath()
{

  LIB_DIR=${PKGDIR}/lib

  # Begin PORTALMA
if [ "$OSTYPE" = "Linux" ]; then
	MOBILEACCESS_PKG=sun-mobileaccess
	JAVAHELP_PKG=sun-javahelp
else
	MOBILEACCESS_PKG=SUNWma
	JAVAHELP_PKG=SUNWjhrt
fi

getFilePathFromPackage $MOBILEACCESS_PKG mobile_services.jar
MOBILE_ACCESS_LIB_DIR=`echo $FILE_PATH | sed -e "s#/mobile_services.jar##g"`
getFilePathFromPackage $JAVAHELP_PKG jhall.jar
JAVA_HELPER=$FILE_PATH

#define server.name for new instance
if [ "$NEW_INSTANCE" = "true" ]; then
   NEW_SERVER_INSTANCE=" -Dserver.name=$INSTANCE"
else
   NEW_SERVER_INSTANCE=""
fi


  MOBILE_ACCESS_JARS="$MOBILE_ACCESS_LIB_DIR/wireless_rendering.jar:$MOBILE_ACCESS_LIB_DIR/wireless_rendering_util.jar:$MOBILE_ACCESS_LIB_DIR/mobile_services.jar:$MOBILE_ACCESS_LIB_DIR/ccpp-1_0.jar:$MOBILE_ACCESS_LIB_DIR/ccpp-ri-1_0.jar:$MOBILE_ACCESS_LIB_DIR/jena-1.4.0.jar:$MOBILE_ACCESS_LIB_DIR/rdffilter.jar:$MOBILE_ACCESS_LIB_DIR/locale"
  is_pkg_installed $MA_PKGNAME
  if [ $? -eq 0 ]; then
      	MOBILE_ACCESS_JARS="$MOBILE_ACCESS_JARS:$LIB_DIR/mobile_identity.jar"
  fi
  # End PORTALMA

  JVM_CLASSPATH_CLASSES="$LIB_DIR/jax-qname.jar:$LIB_DIR/namespace.jar:$LIB_DIR/jaxrpc-api.jar:$LIB_DIR/jaxrpc-spi.jar:$LIB_DIR/jaxrpc-impl.jar:$LIB_DIR/commons-logging.jar:$LIB_DIR/xalan.jar:$LIB_DIR/xmlsec.jar:$LIB_DIR/xercesImpl.jar:$LIB_DIR/dom.jar:$LIB_DIR/saaj-api.jar:$LIB_DIR/saaj-impl.jar:$CONFIG_DIR:$LIB_DIR:$PKGDIR/locale:$JSS_JAR_FILE:$LIB_DIR/am_sdk.jar:${LIB_DIR}/ldapjdk.jar:${LIB_DIR}/am_services.jar:${LIB_DIR}/am_sso_provider.jar:$LIB_DIR/swec.jar:$LIB_DIR/acmecrypt.jar:$LIB_DIR/iaik_ssl.jar:$LIB_DIR/iaik_jce_full.jar:$LIB_DIR/mail.jar:$LIB_DIR/activation.jar:${LIB_DIR}/am_logging.jar:$LIB_DIR/jaas.jar:$LIB_DIR/jaxm-api.jar:$LIB_DIR/jaxm-runtime.jar:$LIB_DIR/jce1_2_1.jar:$LIB_DIR/jdk_logging.jar:$LIB_DIR/xsltc.jar:$LIB_DIR/relaxngDatatype.jar:$LIB_DIR/xsdlib.jar:$LIB_DIR/jaxb-api.jar:$LIB_DIR/jaxb-impl.jar:$LIB_DIR/jaxb-libs.jar:$LIB_DIR/jaxb-xjc.jar:$MOBILE_ACCESS_JARS:$JAVA_HELPER"

  cd ${WL8_CONFIG_BASE}

 LIB_DIR=${PKGDIR}/lib
 for file in $WL8_CONFILES; do

sed -e "/^CLASSPATH/{
a\\
### Access Manager classes added to CLASSPATH
a\\
CLASSPATH=${CONFIG_DIR}:${JVM_CLASSPATH_CLASSES}:\$CLASSPATH
a\\

a\\
### Access Manager related enviornment variables
a\\
IS_OPTIONS=\"-Djava.security.auth.login.config=${WL8_CONFIG_BASE}/.java.login.config -DLOG_COMPATMODE=Off -Ds1is.java.util.logging.config.class=com.sun.identity.log.s1is.LogConfigReader -Djava.protocol.handler.pkgs=com.iplanet.services.comm -Dcom.iplanet.am.serverMode=true$NEW_SERVER_INSTANCE\" 
a\\

a\\
### Access Manager related libraries added to LD_LIBRARY_PATH
a\\
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:\$LD_LIBRARY_PATH
a\\

}" $file >${WL8_CONFIG_BASE}/tempFile126743


## Replace JAVA_OPTIONS} with JAVA_OPTIONS} ${IS_OPTIONS}

 sed "`grep -n "{JAVA_OPTIONS}" ${WL8_CONFIG_BASE}/tempFile126743 | cut -d: -f1 | tail -1` s/JAVA_OPTIONS}/JAVA_OPTIONS} \${IS_OPTIONS} /" ${WL8_CONFIG_BASE}/tempFile126743 > $file

# echo "Removing TempFile"
 rm ${WL8_CONFIG_BASE}/tempFile126743

done

# add IS_OPTIONS to startup line
  lineno=`grep -n weblogic.Server $file|nawk -F: '{print $1}'`
  total_line=`wc -l $file |nawk '{print $1}'`
  idx=1
  newfile=$file-$$
  rm -f $newfile;touch $newfile
  
  while [ $idx -le $total_line ];do
   if [ $idx -ne $lineno ];then
        line=`head -$idx $file|tail -1`
        $ECHO "$line" >>$newfile
   else # need to modify line
        line=`head -$idx $file|tail -1`
        line=`$ECHO $line | nawk '{for(i=1;i<=NF;i++)if(index($i,"JAVA_OPTIONS")!=0) printf("%s ${IS_OPTIONS} ",$i) ;else printf ("%s ",$i);}'`
        $ECHO "$line" >>$newfile
   fi
   idx=`expr $idx \+ 1`
  done
  
  cp -f $newfile $file
  rm -f $newfile

}

configNewInstance()
{
  cd $CONFIG_DIR
  NORMALIZED_INSTANCE_HOST=`$ECHO $WL8_SERVER | sed -e "s/\./_/g"`
  cp -p AMConfig.properties AMConfig-$NORMALIZED_INSTANCE_HOST.properties
  CURRENT_AMCONFIG_FILE="AMConfig-$NORMALIZED_INSTANCE_HOST.properties"
  export CURRENT_AMCONFIG_FILE
  file=$CURRENT_AMCONFIG_FILE
  OLDPORT=`cat $CONFIG_DIR/AMConfig.properties | grep "^com.iplanet.am.server.port" | /usr/bin/awk ' BEGIN { FS = "=" } { print $2 }'`
  OLDPROTOCOL=`cat $CONFIG_DIR/AMConfig.properties | grep "^com.iplanet.am.server.protocol" | /usr/bin/awk ' BEGIN { FS = "=" } { print $2 }'`
  OLDSERV_URI=`grep "^com.iplanet.am.naming.url" $CONFIG_DIR/AMConfig.properties | nawk -F/ '{if (NF>3)print $4;else print $NF}'`

  replace_line "$file" "com.iplanet.am.server.port=$OLDPORT" "com.iplanet.am.server.port=$SERVER_PORT"
  replace_line "$file" "com.iplanet.am.console.port=$OLDPORT" "com.iplanet.am.console.port=$CONSOLE_PORT"
  replace_line "$file" "com.iplanet.am.profile.port=$OLDPORT" "com.iplanet.am.profile.port=$SERVER_PORT"
  replace_line "$file" "com.iplanet.am.localserver.port=$OLDPORT" "com.iplanet.am.localserver.port=$SERVER_PORT"

  replace_line "$file" "com.iplanet.am.naming.url=$OLDPROTOCOL:\/\/$SERVER_HOST:$OLDPORT\/$OLDSERV_URI\/namingservice" "com.iplanet.am.naming.url=$WL8_PROTOCOL:\/\/$SERVER_HOST:$SERVER_PORT\/$SERVER_DEPLOY_URI\/namingservice"
  replace_line "$file" "com.iplanet.am.notification.url=$OLDPROTOCOL:\/\/$SERVER_HOST:$OLDPORT\/$OLDSERV_URI\/notificationservice" "com.iplanet.am.notification.url=$WL8_PROTOCOL:\/\/$SERVER_HOST:$SERVER_PORT\/$SERVER_DEPLOY_URI\/notificationservice"
  replace_line "$file" "com.iplanet.am.localserver.port=$OLDPORT" "com.iplanet.am.localserver.port=$SERVER_PORT" "com.iplanet.am.localserver.port=$SERVER_PORT"
  replace_line "$file" "com.sun.identity.liberty.interaction.wspRedirectHandler=$OLDPROTOCOL:\/\/$SERVER_HOST:$OLDPORT\/$OLDSERV_URI\/WSPRedirectHandler" "com.sun.identity.liberty.interaction.wspRedirectHandler=$OLDPROTOCOL:\/\/$SERVER_HOST:$SERVER_PORT\/$SERVER_DEPLOY_URI\/WSPRedirectHandler"

  rm -f $CONFIG_DIR/AMConfig-$NORMALIZED_INSTANCE_HOST.properties-orig*

}

unconfigureWL8()
{
  $ECHO "Removing Access Manager configuration from WebLogic"
  # restore the ws and Access Manager to its init stage (config)
  rm -f ${BASEDIR}/${PRODUCT_DIR}/lib/endorsed/dom.jar
  rm -f ${BASEDIR}/${PRODUCT_DIR}/lib/endorsed/sax.jar
  rm -f ${BASEDIR}/${PRODUCT_DIR}/lib/endorsed/xalan.jar
  rm -f ${BASEDIR}/${PRODUCT_DIR}/lib/endorsed/xercesImpl.jar

 # unconfig weblogic and remove all Access Manager related config
 cd ${WL8_CONFIG_BASE}

 #rm -f $WL8_HOME/docs/online_help

 for file in $WL8_CONFILES; do
 
  libline=`cat $file | grep -n "### Access Manager" | nawk ' BEGIN { FS=":" } { print $1}'`
  count=0
  for temp in $libline;
   do
    lineNum=`expr $temp - $count`
    delete_line_by_number $file $lineNum
    delete_line_by_number $file $lineNum
    delete_line_by_number $file $lineNum
    count=`expr $count + 3`
  done
 optLine=`cat $file | grep IS_OPTIONS |egrep -v "weblogic.Server"`
  newOptLine=`$ECHO $optLine | nawk '{
         line=$0
         size = split(line, arrays, " ")
         for(i=1; i <= size; i++) {
          if ((index($i, "IS_OPTIONS") == 0)) {
            printf("%s ", $i)
          }
         }

   }'`
  #append_line "$file" "IS_OPTIONS" "$newOptLine"
  #delete_line "$file" "IS_OPTIONS"

 #sed -e 's/{CLASSPATH}/CLASSPATH/g' \
 #$file > ${file}-tmp
 #cp ${file}-tmp $file
 #rm ${file}-tmp

 sed -e 's/{JAVA_OPTIONS} \${IS_OPTIONS}/{JAVA_OPTIONS}/g' \
 $file > ${file}-tmp
 cp ${file}-tmp $file
 rm ${file}-tmp

 done

  # deleting permission settings in weblogic.policy
  file="$WL8_INSTANCE/server/lib/weblogic.policy"
  line=`cat $file | grep -n "Access Manager RELATED ADDITIONS" | nawk ' BEGIN { FS=":" } { print $1}'`
  count=1
  while [ $count -lt 29 ]
  do
      delete_line_by_number "$file" "$line"
      count=`expr $count + 1`
  done

 # restore java.security of weblogic
 #file="${WL8_JDK_HOME}/jre/lib/security/java.security"
 #delete_line "$file" "login.configuration.provider=com.sun.identity.authentication.config.AMConfiguration"

# delete IS_OPTIONS from startup line
 
 for file in $WL8_CONFILES; do
 
  lineno=`grep -n weblogic.Server $file|nawk -F: '{print $1}'`
  total_line=`wc -l $file |awk '{print $1}'`
  idx=1
  newfile=$file-$$
  rm -f $newfile;touch $newfile
 
  while [ $idx -le $total_line ];do
       if [ $idx -ne $lineno ];then
               line=`head -$idx $file|tail -1`
               $ECHO "$line" >>$newfile
       else   # need to modify line
               line=`head -$idx $file|tail -1`
               line=`$ECHO $line | nawk '{for(i=1;i<=NF;i++)if(index($i,"IS_OPTIONS")!=0) printf("");else printf ("%s ",$i);}'`
               $ECHO "$line" >>$newfile
       fi
       idx=`expr $idx \+ 1`
  done
       cp -f $newfile $file
       rm -f $newfile
 done

 # restore weblogic 8.1 saml config
 # restore_saml_config
}

# start weblogic server
start_wl81()
{
  # check to see if weblogic is already running
  pid=`ps -ef|grep "$WL8_HOME"|egrep -v grep|nawk '{print $2}'`
  if [ -z ${pid:-""} ];then
    if [ -x $WL8_CONFIG_BASE/startWebLogic.sh ];then
      $ECHO "Starting weblogic 8.1 ..."
      currdir=`pwd`
      cd $WL8_CONFIG_BASE
      ./startWebLogic.sh >AMwebLogic.log &
      check_and_wait
      cd $currdir
    else
      $ECHO "Weblogic 8.1 ($WL8_CONFIG_BASE) startup script not executable!"
      exit 0
    fi
    $ECHO "Weblogic 8.1 started."
  else
    $ECHO "Weblogic 8.1 already running."
  fi
}

# stop weblogic 
stop_wl81()
{
      $ECHO "Weblogic 8.1 may require restarting!"
# pid=`ps -ef|grep "$WL8_HOME"|egrep -v grep|nawk '{print $2}'`
# if [ ! -z ${pid:-""} ];then
#        echo "Stopping weblogic 8.1 ..."
#        kill -9 ${pid:-99999999} > /dev/null 2>&1
# fi
}

check_ports()
{
if [ $DEPLOY_LEVEL -eq 4 ];then #       full wl81 install
        x="*.$WL8_PORT"
        yesorno=1
        yesorno=`netstat -an | grep "*.$WL8_PORT" | egrep -v grep | nawk -v v=$x -v i=0 '{if (length(v)==length($1)) i++; print i}'`
        if [ ${yesorno:-0} -ne 0 ];then
                $ECHO "Port $WL8_PORT is busy, please check it and rerun $0"
                exit 0
        fi
fi

}
check_and_wait()
{
 yesorno=0
 x="*.$WL8_PORT"
 while [ ${yesorno:-0} -eq 0 ];do
  yesorno=`netstat -an | grep "*.$WL8_PORT" | egrep -v grep | wc -l`
#  if [ ${yesorno:-0} -ne 0 ];then
#   yesorno=`netstat -an | grep "*.$WL8_PORT" | egrep -v grep | nawk -v v=$x -v i=0 '{if (length(v)==length($1)) i++; print i}'`
#  fi
  sleep 3
 done

}

tagSwap()
{
if [ -f ${USR_DIR}/share/lib/identity/console-war/WEB-INF/web.xml.template ]; then
  $CP ${USR_DIR}/share/lib/identity/console-war/WEB-INF/web.xml.template ${USR_DIR}/share/lib/identity/console-war/WEB-INF/web.xml
fi
if [ -f ${USR_DIR}/share/lib/identity/console-war/WEB-INF/ias-web.xml.template ]; then
  $CP ${USR_DIR}/share/lib/identity/console-war/WEB-INF/ias-web.xml.template ${USR_DIR}/share/lib/identity/console-war/WEB-INF/ias-web.xml
fi
if [ -f ${USR_DIR}/share/lib/identity/console-war/WEB-INF/sun-web.xml.template ]; then
  $CP ${USR_DIR}/share/lib/identity/console-war/WEB-INF/sun-web.xml.template ${USR_DIR}/share/lib/identity/console-war/WEB-INF/sun-web.xml
fi

if [ "$NEW_INSTANCE" = "false" -o "$NEW_INSTANCE" = "" ]; then
EDIT_FILES="
${CONFIG_DIR}/AMConfig.properties
${PKGDIR}/bin/amserver
${PKGDIR}/bin/am2bak
${PKGDIR}/bin/bak2am
${COMMON_DIR}/WEB-INF/classes/FSIntroConfig.properties
${COMMON_DIR}/WEB-INF/web.xml
${USR_DIR}/share/lib/identity/console-war/WEB-INF/web.xml
${USR_DIR}/share/lib/identity/console-war/WEB-INF/ias-web.xml
${USR_DIR}/share/lib/identity/console-war/WEB-INF/sun-web.xml"
else
EDIT_FILES="
${CONFIG_DIR}/AMConfig-$INSTANCE.properties
${PKGDIR}/bin/amserver.$INSTANCE
${PKGDIR}/bin/am2bak.$INSTANCE
${PKGDIR}/bin/bak2am.$INSTANCE
${COMMON_DIR}/WEB-INF/classes/FSIntroConfig.properties
${COMMON_DIR}/WEB-INF/web.xml
${USR_DIR}/share/lib/identity/console-war/WEB-INF/web.xml
${USR_DIR}/share/lib/identity/console-war/WEB-INF/ias-web.xml
${USR_DIR}/share/lib/identity/console-war/WEB-INF/sun-web.xml"
fi

for file in $EDIT_FILES; do
  if [ ! -f $file ];then
      continue
  fi
  cp $file $file+
  sed -e "s#CONSOLE_DEPLOY_URI#$CONSOLE_DEPLOY_URI#g" \
      -e "s#SERVER_DEPLOY_URI#$SERVER_DEPLOY_URI#g" \
      -e "s#PASSWORD_DEPLOY_URI#$PASSWORD_DEPLOY_URI#g" \
      -e "s#COMMON_URI#$COMMON_DEPLOY_URI#g" \
      -e "s#WEBAPPSDIR#${SERVICES_DIR}#g" \
      -e "s#COOKIE_ENCODE#true#g" \
      -e "s#NOTIFICATION_URL#$notification_url#g" \
      -e "s#COOKIE_DOMAIN#${COOKIE_DOMAIN_LIST:-.iplanet.com}#g" \
      -e "s#JSSHOME#${JSS_ROOTDIR}#g" \
      -e "s#NSSHOME#${NSS_ROOTDIR}#g" \
      -e "s#NSPRHOME#${NSPR_ROOTDIR}#g" \
      -e "s#CONTAINER_CERTDB_DIR#${AS81_CONFIG_BASE}#g" \
      -e "s#CONTAINER_CERTDB_PREFIX##g" \
      -e "s#WEB_CONTAINER#BEA8.1#g" \
      -e "s#BASEDIR/PRODUCT_DIR/config#${CONFIG_DIR}#g" \
      -e "s#SUNAPPSERVER_INSTANCE_DIR_TAG#${AS81_INSTANCE_DIR}#g" \
      -e "s#PKGDIR/web-apps/introduction#${PKGDIR}/web-src/common#g" \
      -e "s#IS_INSTALL_ETCDIR#${IS_INSTALL_ETCDIR}#g" \
      -e "s#IS_INSTALL_VARDIR#${IS_INSTALL_VARDIR}#g" \
      -e "s#IS_PRODNAME#${PRODUCT_DIR}#g" \
      $file+ > $file
  rm -f $file+
done
}


undeploy_all()
{
$ECHO "Undeploy all 4 web-apps."
# Check to see if Realm mode is enabled from silent file
flag=`echo "$AM_REALM" | tr "[a-z]" "[A-Z]"`

if [ "x$flag" != "xENABLED" ]; then
  undeploy_it 0
fi
undeploy_it 1
undeploy_it 2
undeploy_it 3
}

undeploy_it()
{
 idx=${1:-0}
 case $idx in
   0)
        CURRENT_DEPLOY_URI=${uri1:-/amconsole}  # console deploy with diff variable
        ;;
   1)
        CURRENT_DEPLOY_URI=${uri2:-/amserver}   # /amserver default
        ;;
   2)
        CURRENT_DEPLOY_URI=${uri3:-/ampassword} # /ampassword default
        ;;
   3)
        CURRENT_DEPLOY_URI=${uri4:-/amcommon}   # /amcommon default
        ;;
 esac

 wl8_classpath="$LIB_DIR/jax-qname.jar:$LIB_DIR/namespace.jar:$LIB_DIR/jaxrpc-api.jar:$LIB_DIR/jaxrpc-spi.jar:$LIB_DIR/jaxrpc-impl.jar:$LIB_DIR/commons-logging.jar:/opt/SUNWma/lib/mobile_services.jar:/opt/SUNWma/lib/wireless_rendering.jar:/opt/SUNWma/lib/wireless_rendering_util.jar:$WL8_INSTANCE/server/lib/weblogic.jar:$LIB_DIR/xalan.jar:$LIB_DIR/xmlsec.jar:$LIB_DIR/xercesImpl.jar:$LIB_DIR/sax.jar:$LIB_DIR/dom.jar:$LIB_DIR/dom4j.jar:$LIB_DIR/saaj-api.jar:$LIB_DIR/saaj-impl.jar:$CONFIG_DIR:$LIB_DIR:$PKGDIR/locale:$JSS_JAR_FILE:$LIB_DIR/am_sdk.jar:${LIB_DIR}/ldapjdk.jar:${LIB_DIR}/am_services.jar:${LIB_DIR}/am_sso_provider.jar:$LIB_DIR/swec.jar:$LIB_DIR/acmecrypt.jar:$LIB_DIR/iaik_ssl.jar:$LIB_DIR/iaik_jce_full.jar:$LIB_DIR/jaxp-api.jar:$LIB_DIR/mail.jar:$LIB_DIR/activation.jar:${LIB_DIR}/am_logging.jar:$LIB_DIR/jaas.jar:$LIB_DIR/jaxm-api.jar:$LIB_DIR/jaxm-runtime.jar:$LIB_DIR/jce1_2_1.jar:$LIB_DIR/jdk_logging.jar:$LIB_DIR/xsltc.jar:$LIB_DIR/relaxngDatatype.jar:$LIB_DIR/xsdlib.jar:$LIB_DIR/jaxb-api.jar:$LIB_DIR/jaxb-impl.jar:$LIB_DIR/jaxb-libs.jar:$LIB_DIR/jaxb-xjc.jar:$MOBILE_ACCESS_JARS"

 WEB_APP=`$ECHO $CURRENT_DEPLOY_URI |nawk -F/ '{print $NF}'`
 $WL8_JDK_HOME/bin/java -classpath $wl8_classpath weblogic.Deployer -undeploy -adminurl ${WL8_PROTOCOL}://${WL8_HOST}:${WL8_PORT} -username ${WL8_ADMIN} -password ${WL8_PASSWORD} -name $WEB_APP -targets $WL8_SERVER
 if [ $? -eq 0 ];then
	$ECHO "Successfully undeployed $WEB_APP ."
 else
	$ECHO "Failed to undeploy $WEB_APP ."
 fi
}

deploy_all()
{
deploy_it 1
deploy_it 2
deploy_it 3
# Check to see if Realm mode is enabled from silent file
flag=`echo "$AM_REALM" | tr "[a-z]" "[A-Z]"`

if [ "x$flag" != "xENABLED" ]; then
  deploy_it 4
fi
}

deploy_it()
{
  ma_auth_files=""
  idx=${1:-0}
  case $idx in
   0)
        # Console only deployment will deploy remote console in Enhanced mode
        CURRENT_DEPLOY_URI=${uri2:-/amserver}	# /amserver default
        warfile=console.war
        DEPLOY_SRC=$CONSOLE_ONLY_DEPLOY_DIR
        DEPLOY_DIR=$CONSOLE_DEPLOY_DIR
        CURRENT_WEB_APP="remote_console"
        ;;
   1)
        # This deployment will deploy console/server in Enhanced mode
        CURRENT_DEPLOY_URI=${uri2:-/amserver}   # /amserver default
        warfile=services.war
        DEPLOY_SRC=$SERVICES_DIR
        DEPLOY_DIR=$SERVICES_DEPLOY_DIR
        CURRENT_WEB_APP="services"
        # Begin PORTALMA
        # MA auth jsps
        ma_auth_files=mobile_auth_jsps.jar
        # End PORTALMA
        ;;
   2)
        # This deployment will deploy password application
        CURRENT_DEPLOY_URI=${uri3:-/ampassword} # /ampassword default
        warfile=password.war
        DEPLOY_SRC=$PASSWORD_DIR
        DEPLOY_DIR=$PASSWORD_DEPLOY_DIR
        CURRENT_WEB_APP="password"
        ;;
   3)
        # This deployment will deploy common application
        CURRENT_DEPLOY_URI=${uri4:-/amcommon}   # /amcommon default
        warfile=introduction.war
        DEPLOY_SRC=$COMMON_DIR
        DEPLOY_DIR=$COMMON_DEPLOY_DIR
        CURRENT_WEB_APP="common"
        ;;
    4)
       # This deployment is required for Legacy mode and will
       # deploy AM 6.3 console
       CURRENT_DEPLOY_URI=${uri1:-/amconsole}  # /amconsole default
       warfile=amconsole.war
       DEPLOY_SRC=$CONSOLE_DIR
       DEPLOY_DIR=$CONSOLE_DEPLOY_DIR
       CURRENT_WEB_APP="applications"
       ;;

  esac

  # explode the war. If the directory already exists it is assumed the war is already
  # exploded. This directory will be the template directory for this web application.
  # all edits to the war should be done here, when deploy function is called it
  # will war up these directories and deploy them

  if [ -f $PKGDIR/$warfile ]; then
    mkdir -p $DEPLOY_SRC
    mkdir -p /tmp/.war.tmp

    cd /tmp/.war.tmp
    if [ "$idx" = "1" ]; then
        if [ -f $PKGDIR/console.war ]; then
           jar xf $PKGDIR/console.war
        fi
    fi
    jar xf $PKGDIR/$warfile
    cp -rf * $DEPLOY_SRC
    cd $DEPLOY_SRC
    rm -rf /tmp/.war.tmp

    # Begin PORTALMA
    # Add the MA auth files to the services web application
    if [ -f "$PKGDIR/$ma_auth_files" ]; then
        jar xf $PKGDIR/$ma_auth_files
        rm $PKGDIR/$ma_auth_files
    fi
    # End PORTALMA
  fi

  if [ $idx -eq 1 ];then
	cp -f $PKGDIR/web-src/services/WEB-INF/web.xml /tmp/.am63.svc.web.xml
	file=$PKGDIR/web-src/services/WEB-INF/web.xml
	newfile=$file.$$;rm -fr $newfile;touch $newfile
	line1=`grep -n "<filter>" $file |nawk -F: '{print $1}'`
	line2=`grep -n "</filter-mapping>" $file |nawk -F: '{print $1}'`
	i=1; status=0; total=`wc -l $file |nawk '{print $1}'`
	while [ $i -le $total ];do
		if [ $i -eq $line1 ];then
			status=1
		elif [ $i -gt $line2 ];then
			status=0
		fi
		if [ $status -eq 0 ];then
			head -$i $file |tail -1 >> $newfile
		fi
		i=`expr $i \+ 1`
	done
	cp -f $newfile $file; rm -f $newfile
  fi

  tagSwap

  cd ${WEBAPPS_SOURCE_DIR}
  ${PKGDIR}/share/bin/amwar -n $CURRENT_WEB_APP -u $CURRENT_DEPLOY_URI -d $PKGDIR
  if [ $? -eq 0 ];then
      $ECHO "Successfully completed making warfile $warfile..."
  else
      $ECHO "Failed to make warfile $warfile !"
  fi
  warfile=`$ECHO ${CURRENT_DEPLOY_URI} | sed -e "s#/*##"`".war"
  if [ $idx -eq 1 ];then
	cp -f /tmp/.am63.svc.web.xml $PKGDIR/web-src/services/WEB-INF/web.xml 2>/dev/null
  fi

  doDeploy
}


doDeploy()
{

  $ECHO "Deploying $warfile in instance $WL8_SERVER."
  DEPLOY_WARPREFIX=`$ECHO $CURRENT_DEPLOY_URI |nawk -F/ '{print $NF}'`
 wl8_classpath="$LIB_DIR/jax-qname.jar:$LIB_DIR/namespace.jar:$LIB_DIR/jaxrpc-api.jar:$LIB_DIR/jaxrpc-spi.jar:$LIB_DIR/jaxrpc-impl.jar:/opt/SUNWma/lib/mobile_services.jar:/opt/SUNWma/lib/wireless_rendering.jar:/opt/SUNWma/lib/wireless_rendering_util.jar:$WL8_INSTANCE/server/lib/weblogic.jar:$LIB_DIR/xalan.jar:$LIB_DIR/xmlsec.jar:$LIB_DIR/xercesImpl.jar:$LIB_DIR/sax.jar:$LIB_DIR/dom.jar:$LIB_DIR/dom4j.jar:$LIB_DIR/saaj-api.jar:$LIB_DIR/saaj-impl.jar:$CONFIG_DIR:$LIB_DIR:$PKGDIR/locale:$JSS_JAR_FILE:$LIB_DIR/am_sdk.jar:${LIB_DIR}/ldapjdk.jar:${LIB_DIR}/am_services.jar:${LIB_DIR}/am_sso_provider.jar:$LIB_DIR/swec.jar:$LIB_DIR/acmecrypt.jar:$LIB_DIR/iaik_ssl.jar:$LIB_DIR/iaik_jce_full.jar:$LIB_DIR/jaxp-api.jar:$LIB_DIR/mail.jar:$LIB_DIR/activation.jar:${LIB_DIR}/am_logging.jar:$LIB_DIR/jaas.jar:$LIB_DIR/jaxm-api.jar:$LIB_DIR/jaxm-runtime.jar:$LIB_DIR/jce1_2_1.jar:$LIB_DIR/jdk_logging.jar:$LIB_DIR/xsltc.jar:$LIB_DIR/relaxngDatatype.jar:$LIB_DIR/xsdlib.jar:$LIB_DIR/jaxb-api.jar:$LIB_DIR/jaxb-impl.jar:$LIB_DIR/jaxb-libs.jar:$LIB_DIR/jaxb-xjc.jar:$MOBILE_ACCESS_JARS:$WL8_INSTANCE/server/lib/weblogic.jar:$CLASSPATH"

#  echo "Use classpath $wl8_classpath .."
  if [ -f $WL8_JDK_HOME/bin/java ];then
   WEB_APP=`$ECHO $CURRENT_DEPLOY_URI |nawk -F/ '{print $NF}'`
   $WL8_JDK_HOME/bin/java -classpath $wl8_classpath weblogic.Deployer -adminurl ${WL8_PROTOCOL}://${WL8_HOST}:${WL8_PORT} -name $WEB_APP -username $WL8_ADMIN -password $WL8_PASSWORD -targets $WL8_SERVER -deploy ${PKGDIR}/$warfile
  else
   $ECHO "WL8.1 built-in jdk not found at $WL8_JDK_HOME/bin/java!"
   exit 1
  fi

  if [ $? -eq 0 ];then
    $ECHO "Successfully deployed $CURRENT_DEPLOY_URI"
  else
    $ECHO "Failed to deploy $CURRENT_DEPLOY_URI"
  fi
  $ECHO ""
}

#############################################################################
# Start of main program
#############################################################################

PWD=`pwd`
# check system env. 
check_env

# DEPLOY_LEVEL level range from 1 ~ 99 of following meaning
case $DEPLOY_LEVEL in
	1)	# full container config
		stop_wl81
                configureWL8
		#start_wl81
		deploy_all
		;;
	2)	# console only container config
		stop_wl81
                configureWL8
		#start_wl81
		deploy_it 0
		deploy_it 2
		;;
	4)	# sdk only container config
                configureWL8
		tagSwap
		;;
	5)	# federation only container config
		deploy_it 3
		;;
	6)	# server only container config
		stop_wl81
                configureWL8
		#start_wl81
		deploy_it 1
		deploy_it 3
		;;
	7)	# container config
                configureWL8
		tagSwap
		;;
	11)	# undeploy full with container config
		#start_wl81
		undeploy_all
                unconfigureWL8
		cleanLogConfig
		;;
	12)	# undeploy console only with container config
		#start_wl81
		undeploy_it 0
		undeploy_it 2
                unconfigureWL8
		;;
	14)	# undeploy sdk only with container config
                unconfigureWL8
		;;
	15)	# undeploy federation only with container config
		#start_wl81
		undeploy_it 3
		;;
	16)	# undeploy server only with container config
		#start_wl81
		undeploy_it 3
		undeploy_it 1
                unconfigureWL8
		;;
	17)	# undeploy container config
                unconfigureWL8
		;;
	21)	# redeploy full with container config
		#start_wl81
		undeploy_all
                unconfigureWL8
		stop_wl81
                configureWL8
		#start_wl81
		deploy_all
		;;
        22*)    # redeploy console
		#start_wl81
                undeploy_it 0 "yes"
                deploy_it 0
                ;;
        23*)    # redeploy server
		#start_wl81
                undeploy_it 1 "yes"
                deploy_it 1
                ;;
        24*)    # redeploy password
		#start_wl81
                undeploy_it 2 "yes"
                deploy_it 2
                ;;
        25*)    # redeploy common
		#start_wl81
                undeploy_it 3 "yes"
                deploy_it 3
                ;;
        26*)    # undeploy all
		#start_wl81
                undeploy_all
                ;;
        27*)    # undeploy console
		#start_wl81
                undeploy_it 0 "yes"
		;;
        28*)    # undeploy password
		#start_wl81
                undeploy_it 2 "yes"
                ;;
        29*)    # undeploy services
		#start_wl81
                undeploy_it 1 "yes"
                ;;
        30*)    # undeploy common
		#start_wl81
                undeploy_it 3 "yes"
                ;;
	31*)	# config Access Manager SDK only
                configureWL8
		;;
	*)	$ECHO "Unsupported DEPLOY_LEVEL value" 
		exit 0 ;;
esac



