#!/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.

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

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


SERVER_URI="$SERVER_PROTOCOL://$SERVER_HOST:$SERVER_PORT"
notification_url=$SERVER_PROTOCOL://$SERVER_HOST:$SERVER_PORT$SERVER_DEPLOY_URI/notificationservice

AS81_HOSTNAME=`echo $AS81_HOST |nawk -F. '{print $1}'`
AS81_CONFIG_BASE=${AS81_INSTANCE_DIR}/config
LIB_DIR=${PKGDIR}/lib

# add path for asadmin
PATH=${AS81_HOME}/bin:$JAVA_HOME/bin:$PATH
export PATH
LD_LIBRARY_PATH=$JSS_SO_PATH:$NSS_SO_PATH:$NSPR_SO_PATH:${PKGDIR}/lib:${PKGDIR}/ldaplib/ldapsdk:$AS81_HOME/lib
if [ "$OSTYPE" = "Linux" ]; then
	LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${JAVA_HOME}/jre/lib/i386/native_threads
fi
export LD_LIBRARY_PATH

CLASSPATH=${AS81_HOME}/lib:$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
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

backupConfig()
{
  BACKUP_DIR=${AS81_INSTANCE_DIR}/config/.dsame
  if [ ! -d $BACKUP_DIR ];then
    mkdir -p $BACKUP_DIR
  fi
  cp -r ${AS81_INSTANCE_DIR}/config/domain.xml $BACKUP_DIR
  cp -r ${AS81_INSTANCE_DIR}/config/server.policy $BACKUP_DIR
}

setJavaOptions()
{
  # Check if SDK with container config install
  if [ "x$1" = "xSDK" -o $DEPLOY_LEVEL -eq 2 ]; then
     FLAG=false
  else
     FLAG=true
  fi 
  # Use this ONLY when we have appended AM's endorsed dir to AS's endorsed dirs 
#    $AS81_HOME/bin/asadmin delete-jvm-options --user $AS81_ADMIN --passwordfile $FILE_AS81_ADMINPASSWD --host $AS81_HOST --port $AS81_ADMINPORT $SECURE_OPTION --target $AS81_INSTANCE '-Djava.endorsed.dirs=${com.sun.aas.installRoot}/lib/endorsed'
  
  # create the jvm options using asadmin command
  if [ "$NEW_INSTANCE" = "true" ];then
    $AS81_HOME/bin/asadmin create-jvm-options --user $AS81_ADMIN --passwordfile $FILE_AS81_ADMINPASSWD --host $AS81_HOST --port $AS81_ADMINPORT $SECURE_OPTION --target $AS81_INSTANCE -DLOG_COMPATMODE=Off:-Djava.protocol.handler.pkgs=com.iplanet.services.comm:-Ds1is.java.util.logging.config.class=com.sun.identity.log.s1is.LogConfigReader:-Dcom.iplanet.am.serverMode=${FLAG}:-Dserver.name=$AS81_INSTANCE
  else
    $AS81_HOME/bin/asadmin create-jvm-options --user $AS81_ADMIN --passwordfile $FILE_AS81_ADMINPASSWD --host $AS81_HOST --port $AS81_ADMINPORT $SECURE_OPTION --target $AS81_INSTANCE -DLOG_COMPATMODE=Off:-Djava.protocol.handler.pkgs=com.iplanet.services.comm:-Ds1is.java.util.logging.config.class=com.sun.identity.log.s1is.LogConfigReader:-Dcom.iplanet.am.serverMode=${FLAG}
  fi

}

configureServerPolicy()
{
  if [ "$OSTYPE" = "Linux" ]; then
	MOBILEACCESS_PKG=sun-mobileaccess
        SERVER_PREFIX=`echo $SERVER_DEPLOY_URI | awk -F/ '{print $NF}'`
        CONSOLE_PREFIX=`echo $CONSOLE_DEPLOY_URI | awk -F/ '{print $NF}'`
        PASSWORD_PREFIX=`echo $PASSWORD_DEPLOY_URI | awk -F/ '{print $NF}'`
  else
	MOBILEACCESS_PKG=SUNWma
        SERVER_PREFIX=`echo $SERVER_DEPLOY_URI | nawk -F/ '{print $NF}'`
        CONSOLE_PREFIX=`echo $CONSOLE_DEPLOY_URI | nawk -F/ '{print $NF}'`
        PASSWORD_PREFIX=`echo $PASSWORD_DEPLOY_URI | nawk -F/ '{print $NF}'`
  fi
  getFilePathFromPackage $MOBILEACCESS_PKG mobile_services.jar
  MOBILE_ACCESS_LIB_DIR=`echo $FILE_PATH | sed -e "s#/mobile_services.jar##g"`


# modifying server.policy
   file=${AS81_CONFIG_BASE}/server.policy
   cat <<EOF >> $file
   // Access Manager RELATED ADDITIONS
   grant codeBase "file:${PKGDIR}/lib/am_sdk.jar" {
     permission java.net.SocketPermission "*", "connect,accept,resolve";
     permission java.util.PropertyPermission "*", "read, write";
   };
   grant codeBase "file:${PKGDIR}/lib/am_services.jar" {
     permission java.net.SocketPermission "*", "connect,accept,resolve";
     permission java.util.PropertyPermission "*", "read, write";
   };
   grant codeBase "file:${PKGDIR}/lib/swec.jar" {
       permission java.security.AllPermission;
   };
   grant codeBase "file:${MOBILE_ACCESS_LIB_DIR}/-" {
     permission java.net.SocketPermission "*", "connect,accept,resolve";
     permission java.util.PropertyPermission "*", "read, write";
   };
   grant codeBase "file:\${com.sun.aas.instanceRoot}/applications/j2ee-modules/${SERVER_PREFIX}/-" {
     permission java.net.SocketPermission "*", "connect,accept,resolve";
     permission java.util.PropertyPermission "*", "read, write";
   };
   grant codeBase "file:\${com.sun.aas.instanceRoot}/applications/j2ee-modules/${CONSOLE_PREFIX}/-" {
     permission java.net.SocketPermission "*", "connect,accept,resolve";
     permission java.util.PropertyPermission "*", "read, write";
   };
   grant codeBase "file:\${com.sun.aas.instanceRoot}/applications/j2ee-modules/${PASSWORD_PREFIX}/-" {
     permission java.net.SocketPermission "*", "connect,accept,resolve";
     permission java.util.PropertyPermission "*", "read, write";
   };
   grant {
    permission java.lang.RuntimePermission "modifyThreadGroup";
    permission java.lang.RuntimePermission "setFactory";
    permission java.lang.RuntimePermission "accessClassInPackage.*";
    permission java.util.logging.LoggingPermission "control";
    permission java.lang.RuntimePermission "shutdownHooks";
    permission javax.security.auth.AuthPermission "insertProvider.Mozilla-JSS";
    permission java.security.SecurityPermission "putProviderProperty.Mozilla-JSS";
    permission javax.security.auth.AuthPermission "getLoginConfiguration";
    permission javax.security.auth.AuthPermission "setLoginConfiguration";
    permission javax.security.auth.AuthPermission "modifyPrincipals";
    permission javax.security.auth.AuthPermission "createLoginContext.*";
    permission java.security.SecurityPermission "insertProvider.Mozilla-JSS";
    permission javax.security.auth.AuthPermission "putProviderProperty.Mozilla-JSS";
    permission java.io.FilePermission "<<ALL FILES>>", "execute";
    permission java.io.FilePermission "$VAR_SUBDIR/logs/*", "delete,write";
    permission java.util.PropertyPermission "java.util.logging.config.class", "write";
    permission java.security.SecurityPermission "removeProvider.SUN";
    permission java.security.SecurityPermission "insertProvider.SUN";
    permission java.security.SecurityPermission "removeProvider.Mozilla-JSS";
    permission javax.security.auth.AuthPermission "doAs";
    permission java.util.PropertyPermission "java.security.krb5.realm", "write";
    permission java.util.PropertyPermission "java.security.krb5.kdc", "write";
    permission java.util.PropertyPermission "java.security.auth.login.config", "write";
    permission java.util.PropertyPermission "user.language", "write";
    permission javax.security.auth.kerberos.ServicePermission "*", "accept";
    permission javax.net.ssl.SSLPermission "setHostnameVerifier";
    permission java.security.SecurityPermission "putProviderProperty.IAIK";
    permission java.security.SecurityPermission "removeProvider.IAIK";
    permission java.security.SecurityPermission "insertProvider.IAIK";
   };
   // END OF ADDITIONS FOR Access Manager

   // Begin PORTALMA
   // MA RELATED ADDITIONS
   grant {
     permission java.util.PropertyPermission "com.hp.hpl.mesa.rdf.jena.reader.RDF/XML", "write";
   };
   // End PORTALMA
EOF
}

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
}

  # Begin PORTALMA
  # Add MA required jar files to the classpath
  if [ "$OSTYPE" = "Linux" ]; then
	MOBILEACCESS_PKG=sun-mobileaccess
  else
	MOBILEACCESS_PKG=SUNWma
  fi

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

  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/xmlsec.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/am_logging.jar:$LIB_DIR/jaas.jar:$LIB_DIR/jce1_2_1.jar:$LIB_DIR/jdk_logging.jar:$MOBILE_ACCESS_JARS"

   JWSDP_CLASSES="$LIB_DIR/mail.jar:$LIB_DIR/activation.jar"

setClassPath() 
{
  LIB_DIR=${PKGDIR}/lib

  cd ${AS81_CONFIG_BASE}
 
    #step1: Get the classpathsuffix from domain.xml
    initialclasspath=`$AS81_HOME/bin/asadmin get --user $AS81_ADMIN --passwordfile $FILE_AS81_ADMINPASSWD --host $AS81_HOST --port $AS81_ADMINPORT $SECURE_OPTION $AS81_INSTANCE.java-config.classpath-suffix | nawk ' BEGIN { FS="=" } { print $2 } '`
    classpath=`echo $initialclasspath | sed 's/ *//'`

    #step2: Call the classpath editor function in amutils
    classpathAdd $classpath $JVM_CLASSPATH_CLASSES

    #step3: Set the returned classpath to the Classpathsuffix in domain.xml
    $AS81_HOME/bin/asadmin set --user $AS81_ADMIN --passwordfile $FILE_AS81_ADMINPASSWD --host $AS81_HOST --port $AS81_ADMINPORT $SECURE_OPTION $AS81_INSTANCE.java-config.classpath-suffix="$classpathadded" 

    #step4: As done in step1 through step3, the similar approach is used to get and 
    #set the classpath-prefix. Get the classpathprefix from domain.xml
    classpathprefix=`$AS81_HOME/bin/asadmin get --user $AS81_ADMIN --passwordfile $FILE_AS81_ADMINPASSWD --host $AS81_HOST --port $AS81_ADMINPORT $SECURE_OPTION  $AS81_INSTANCE.java-config.classpath-prefix | nawk ' BEGIN { FS="=" } { print $2 } '`
    classpathpref=`echo $classpathprefix | sed 's/ *//'`

    #step5: Call the classpath editor function in amutils
    classpathAdd $classpathpref $JWSDP_CLASSES

    #step6: Set the returned classpath to the Classpathprefix in domain.xml
    $AS81_HOME/bin/asadmin set --user $AS81_ADMIN --passwordfile $FILE_AS81_ADMINPASSWD --host $AS81_HOST --port $AS81_ADMINPORT $SECURE_OPTION $AS81_INSTANCE.java-config.classpath-prefix="$classpathadded" 

}

reconfigureAS81()
{
  # Since we have modified server config file, we need to reconfigure.
  $AS81_HOME/bin/asadmin reconfig --user $AS81_ADMIN --passwordfile $FILE_AS81_ADMINPASSWD --host $AS81_HOST --port $AS81_ADMINPORT $SECURE_OPTION $AS81_INSTANCE > /dev/null 2>&1
  if [ $? != 0 ]; then
       echo "Reconfiguration was not successful. Please reconfigure through application server console or manually."
  fi
  if [ "$NEW_INSTANCE" = "true" ];then
    # create new AMConfig-instance.properties
    # update the platform server list
    if [ ! -f $CONFIG_DIR/AMConfig-$INSTANCE.properties ]; then
        configNewInstance
    fi
  fi
}

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

}

configNewInstance()
{
  cd $CONFIG_DIR
  NORMALIZED_INSTANCE_HOST=`echo $AS81_INSTANCE | sed -e "s/\./_/g"`
  cp -p AMConfig.properties AMConfig-$NORMALIZED_INSTANCE_HOST.properties
  file=AMConfig-$NORMALIZED_INSTANCE_HOST.properties
  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 }'`

  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\\$uri2\/namingservice" "com.iplanet.am.naming.url=$OLDPROTOCOL:\/\/$SERVER_HOST:$SERVER_PORT\\$uri2\/namingservice"
  replace_line "$file" "com.iplanet.am.notification.url=$OLDPROTOCOL:\/\/$SERVER_HOST:$OLDPORT\\$uri2\/notificationservice" "com.iplanet.am.notification.url=$OLDPROTOCOL:\/\/$SERVER_HOST:$SERVER_PORT\\$uri2\/notificationservice"
  replace_line "$file" "com.iplanet.am.localserver.port=$OLDPORT" "com.iplanet.am.localserver.port=$SERVER_PORT"  
  replace_line "$file" "com.sun.identity.liberty.interaction.wspRedirectHandler=$OLDPROTOCOL:\/\/$SERVER_HOST:$OLDPORT\\$uri2\/WSPRedirectHandler" com.sun.identity.liberty.interaction.wspRedirectHandler=$OLDPROTOCOL:\/\/$SERVER_HOST:$SERVER_PORT\\$uri2\/WSPRedirectHandler

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

}

# configure s1as
configureAS81()
{
  echo "Checking if App Server is already configured with Access Manager "
  initialclasspath=`$AS81_HOME/bin/asadmin get --user $AS81_ADMIN --passwordfile $FILE_AS81_ADMINPASSWD --host $AS81_HOST --port $AS81_ADMINPORT $SECURE_OPTION $AS81_INSTANCE.java-config.classpath-suffix | nawk ' BEGIN { FS="=" } { print $2 } '`
  classpath=`echo $initialclasspath | sed 's/ *//'`

  exist=0
  classpathToken=`echo $currentToken | grep "am_sdk.jar"`

  if [ "$classpathToken" != "" ]; then
    exist=1
  fi

  if [ $exist -ne 1 ];then        # not configured yet
    echo "Configuring Application Server 8.1"
    backupConfig
    # $1 - null if full install  
    # $1 - SDK if sdk install
    setJavaOptions $1
#    configureEndorsedDirs
    configureServerPolicy
    setClassPath
    # End PORTALMA
    reconfigureAS81

    # online help link to the docroot
    if [ ! -h $AS81_DOCS_DIR/online_help ]; then
      ln -s ${PKGDIR}/public_html/online_help $AS81_DOCS_DIR/online_help 2>/dev/null
    fi
    if [ ! -h $AS81_DOCS_DIR/api ]; then
      ln -s ${PKGDIR}/docs $AS81_DOCS_DIR/api 2>/dev/null
    fi

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

doDeploy()
{

  echo "deploying $warfile in instance $AS81_INSTANCE"
  DEPLOY_WARPREFIX=`echo $CURRENT_DEPLOY_URI |nawk -F/ '{print $NF}'`

  echo "$AS81_HOME/bin/asadmin deploy --user $AS81_ADMIN --passwordfile XXXXXXXX --host $AS81_HOST --port $AS81_ADMINPORT $SECURE_OPTION --contextroot $DEPLOY_WARPREFIX --name $DEPLOY_WARPREFIX --target $AS81_INSTANCE ${PKGDIR}/${warfile}"


  $AS81_HOME/bin/asadmin deploy --user $AS81_ADMIN --passwordfile $FILE_AS81_ADMINPASSWD --host $AS81_HOST --port $AS81_ADMINPORT $SECURE_OPTION  --contextroot $DEPLOY_WARPREFIX --name $DEPLOY_WARPREFIX --target $AS81_INSTANCE ${PKGDIR}/${warfile}
 
  if [ $? -eq 0 ];then
    echo "Successfully deployed $CURRENT_DEPLOY_URI"
  else
    echo "Failed to deploy $CURRENT_DEPLOY_URI"
  fi 
}

# deploy Access Manager to webcontainer
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

  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"


  doDeploy

  if [ -d /etc/init.d ]
  then
    if [ -f ${PKGDIR}/bin/amserver ];then
      cp ${PKGDIR}/bin/amserver /etc/init.d
      chmod +x /etc/init.d/amserver
    fi
  fi

}


unconfigureAS81()
{

  # Check if SDK with container config install
  if [ "x$1" = "xSDK" -o $DEPLOY_LEVEL -eq 12 ]; then
     FLAG=false
  else
     FLAG=true
  fi 

  # Get the classpathsuffix from domain.xml
  classpath=`$AS81_HOME/bin/asadmin get --user $AS81_ADMIN --passwordfile $FILE_AS81_ADMINPASSWD --host $AS81_HOST --port $AS81_ADMINPORT $AS81_INSTANCE.java-config.classpath-suffix | nawk ' BEGIN { FS="=" } { print $2} '`

  # Call the classpath editor function in amutils
  classpathRemove $classpath $JVM_CLASSPATH_CLASSES

  # unconfig ias81 and remove all Access Manager related config
  cd ${AS81_CONFIG_BASE}

  #Delete the jvm-options and unset the classpath that are set in domain.xml while deploying.
  if [ "$NEW_INSTANCE" = "true" ];then
#    $AS81_HOME/bin/asadmin delete-jvm-options --user $AS81_ADMIN --passwordfile $FILE_AS81_ADMINPASSWD --host $AS81_HOST --port $AS81_ADMINPORT $SECURE_OPTION --target $AS81_INSTANCE '-Djava.endorsed.dirs=${com.sun.aas.installRoot}/lib/endorsed\:'${BASEDIR:-/opt}/${PRODUCT_DIR:-SUNWam}/lib/endorsed:-DLOG_COMPATMODE=Off:-Djava.protocol.handler.pkgs=com.iplanet.services.comm:-Ds1is.java.util.logging.config.class=com.sun.identity.log.s1is.LogConfigReader:-Dcom.iplanet.am.serverMode=${FLAG}:-Dserver.name=$AS81_INSTANCE
    $AS81_HOME/bin/asadmin delete-jvm-options --user $AS81_ADMIN --passwordfile $FILE_AS81_ADMINPASSWD --host $AS81_HOST --port $AS81_ADMINPORT $SECURE_OPTION --target $AS81_INSTANCE -DLOG_COMPATMODE=Off:-Djava.protocol.handler.pkgs=com.iplanet.services.comm:-Ds1is.java.util.logging.config.class=com.sun.identity.log.s1is.LogConfigReader:-Dcom.iplanet.am.serverMode=${FLAG}:-Dserver.name=$AS81_INSTANCE
  else
#    $AS81_HOME/bin/asadmin delete-jvm-options --user $AS81_ADMIN --passwordfile $FILE_AS81_ADMINPASSWD --host $AS81_HOST --port $AS81_ADMINPORT $SECURE_OPTION --target $AS81_INSTANCE '-Djava.endorsed.dirs=${com.sun.aas.installRoot}/lib/endorsed\:'${BASEDIR:-/opt}/${PRODUCT_DIR:-SUNWam}/lib/endorsed:-DLOG_COMPATMODE=Off:-Djava.protocol.handler.pkgs=com.iplanet.services.comm:-Ds1is.java.util.logging.config.class=com.sun.identity.log.s1is.LogConfigReader:-Dcom.iplanet.am.serverMode=${FLAG}
    $AS81_HOME/bin/asadmin delete-jvm-options --user $AS81_ADMIN --passwordfile $FILE_AS81_ADMINPASSWD --host $AS81_HOST --port $AS81_ADMINPORT $SECURE_OPTION --target $AS81_INSTANCE -DLOG_COMPATMODE=Off:-Djava.protocol.handler.pkgs=com.iplanet.services.comm:-Ds1is.java.util.logging.config.class=com.sun.identity.log.s1is.LogConfigReader:-Dcom.iplanet.am.serverMode=${FLAG}
  fi

# Use this ONLY when we have appended AM's endorsed dir to AS's endorsed dirs 
#  $AS81_HOME/bin/asadmin create-jvm-options --user $AS81_ADMIN --passwordfile $FILE_AS81_ADMINPASSWD --host $AS81_HOST --port $AS81_ADMINPORT $SECURE_OPTION --target $AS81_INSTANCE '-Djava.endorsed.dirs=${com.sun.aas.installRoot}/lib/endorsed'


  $AS81_HOME/bin/asadmin set --user $AS81_ADMIN --passwordfile $FILE_AS81_ADMINPASSWD --host $AS81_HOST --port $AS81_ADMINPORT $SECURE_OPTION $AS81_INSTANCE.java-config.classpath-suffix="$classpathremoved" 

  # Get the classpathprefix from domain.xml
  classpathprefix=`$AS81_HOME/bin/asadmin get --user $AS81_ADMIN --passwordfile $FILE_AS81_ADMINPASSWD --host $AS81_HOST --port $AS81_ADMINPORT $SECURE_OPTION $AS81_INSTANCE.java-config.classpath-prefix | nawk ' BEGIN { FS="=" } { print $2} '`

  # Call the classpath editor function in amutils
  classpathRemove $classpathprefix $JWSDP_CLASSES

  # Set the original classpathprefix into domain.xml
  $AS81_HOME/bin/asadmin set  --user $AS81_ADMIN --passwordfile $FILE_AS81_ADMINPASSWD --host $AS81_HOST --port $AS81_ADMINPORT $SECURE_OPTION $AS81_INSTANCE.java-config.classpath-prefix="$classpathremoved" 

  # restore the as 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

  BACKUP_DIR=${AS81_INSTANCE_DIR}/config/.dsame
  rm -fr $BACKUP_DIR 2>/dev/null

    # deleting permission settings in server.policy
    file="server.policy"
    line=`grep -n "Access Manager RELATED ADDITIONS" $file | nawk ' BEGIN { FS=":" } { print $1}'`
    last_line=`grep -n "End PORTALMA" $file | nawk ' BEGIN { FS=":" } { print $1}'`
    number=`expr $last_line - $line + 1`
    count=1
    while [ $count -le $number ]
    do
	sz=`wc -l $file |nawk '{print $1}'`
	if [ $sz -ge $line ];then
        	delete_line_by_number "$file" "$line"
	fi
        count=`expr $count + 1`
    done
  reconfigureAS81
}

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

  UNDEPLOY_URI=`echo $CURRENT_DEPLOY_URI |nawk -F/ '{print $NF}'`
  echo "undeploying $CURRENT_DEPLOY_URI"

  echo "$AS81_HOME/bin/asadmin undeploy --user $AS81_ADMIN --passwordfile $FILE_AS81_ADMINPASSWD --host $AS81_HOST --port $AS81_ADMINPORT $SECURE_OPTION --target $AS81_INSTANCE $UNDEPLOY_URI"


  $AS81_HOME/bin/asadmin undeploy --user $AS81_ADMIN --passwordfile $FILE_AS81_ADMINPASSWD --host $AS81_HOST --port $AS81_ADMINPORT $SECURE_OPTION --target $AS81_INSTANCE $UNDEPLOY_URI

  if [ $? -eq 0 ];then
    echo "Successfully undeployed $CURRENT_DEPLOY_URI ..."
  else
    echo "Failed to undeploy $CURRENT_DEPLOY_URI ..."
  fi
}

deploy_all()
{
  deploy_it 1
  deploy_it 2
  deploy_it 3
  #Check the AM_REALM flag in sample silent flag
  flag=`echo "$AM_REALM" | tr "[a-z]" "[A-Z]"`

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

undeploy_all()
{
  undeploy_it 3 "no"
  undeploy_it 2 "no"
  undeploy_it 1 "no"
  #Check the AM_REALM flag in sample silent flag
  flag=`echo "$AM_REALM" | tr "[a-z]" "[A-Z]"`

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


# start appserver
start_as81()
{
 if [ $AS81_IS_SECURE = "true" ];then
  $AS81_INSTANCE_DIR/bin/startserv <<EOF
$SSL_PASSWORD
EOF
 else
  $AS81_INSTANCE_DIR/bin/startserv
 fi
}

# stop appserver 
stop_as81()
{
  $AS81_INSTANCE_DIR/bin/stopserv
}

check_ports()
{
if [ $DEPLOY_LEVEL -eq 10 -o $DEPLOY_LEVEL -eq 0 -o $DEPLOY_LEVEL -eq 6 ];then #       full as81 install
        x="*.$AS81_PORT"
        yesorno=1
        yesorno=`netstat -an | grep "*.$AS81_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 $AS81_PORT is busy, please check it and rerun $0"
                exit 0
        fi
fi

}

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

create_password_files

PWD=`pwd`
# check system env. 
check_env

# Check if the admin is in secure mode
# Defualt is secure=true
if [ $AS81_ADMIN_IS_SECURE = "false" ];then
   SECURE_OPTION="--secure=false"
else
   SECURE_OPTION=""
fi

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


