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

###########################################################
# Finds amutils and sources it. This function is identical
# in all scripts. Any changes made here need to made in
# other scripts too.
source_amutils()
{
	# Try to guess the location of amutils
	if [ "$BASEDIR" != "" -a "$PRODUCT_DIR" != "" -a -f $BASEDIR/$PRODUCT_DIR/bin/amutils ]; then
		AMUTILS=$BASEDIR/$PRODUCT_DIR/bin/amutils
	elif [ "$BASEDIR" != "" -a "$PRODUCT_DIR" != "" -a -f $BASEDIR/$PRODUCT_DIR/share/bin/amutils ]; then
		AMUTILS=$BASEDIR/$PRODUCT_DIR/share/bin/amutils
	elif [ -f ./amutils ]; then
		AMUTILS=./amutils
	elif [ -f `dirname $0`/amutils ]; then
		AMUTILS=`dirname $0`/amutils
	elif [ -f /opt/SUNWam/bin/amutils ]; then
		AMUTILS=/opt/SUNWam/bin/amutils
	elif [ -f /opt/SUNWam/share/bin/amutils ]; then
		AMUTILS=/opt/SUNWam/share/bin/amutils ]
	elif [ -f /opt/sun/identity/bin/amutils ]; then
		AMUTILS=/opt/sun/identity/bin/amutils
	elif [ -f /opt/sun/identity/share/bin/amutils ]; then
		AMUTILS=/opt/sun/identity/share/bin/amutils ]
	else
		echo "$0: FATAL: Could not find amutils. Exiting."
		exit 1
	fi

	# Source it!
	echo "$0: Sourcing $AMUTILS"
	. $AMUTILS
}

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 
    fi 
    IS_SILENT_INSTALL_FILE=$2 
    export IS_SILENT_INSTALL_FILE 
else 
    echo "Please use amconfig to configure Access Manager." 
    exit 
fi

source_amutils

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

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

AS70_HOSTNAME=`echo $AS70_HOST |nawk -F. '{print $1}'`
AS70_CONFIG_BASE=${AS70_INSTANCE_DIR}/config
LIB_DIR=${PKGDIR}/lib
if [ "$OSTYPE" = "Linux" ]; then
	JSS_JAR_FILE=${JSS_JAR_PATH:-/opt/sun/private/share/lib}/jss3.jar
else
	JSS_JAR_FILE=${JSS_JAR_PATH:-/usr/share/lib/mps/secv1}/jss3.jar
fi

# add path for asadmin
PATH=${AS70_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:$AS70_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=${AS70_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
PASSWORD_DIR=$WEBAPPS_SOURCE_DIR/password
COMMON_DIR=$WEBAPPS_SOURCE_DIR/common
SERVICES_DIR=$WEBAPPS_SOURCE_DIR/services

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

setJavaOptions()
{
  # create the jvm options using asadmin command

  if [ "$NEW_INSTANCE" = "true" ];then
#    $AS70_HOME/bin/asadmin create-jvm-options --user $AS70_ADMIN --passwordfile $FILE_AS70_ADMINPASSWD --host $AS70_HOST --port $AS70_ADMINPORT --instance $AS70_INSTANCE -- -Djava.endorsed.dirs=${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=true:-Dserver.name=$AS70_INSTANCE 
    $AS70_HOME/bin/asadmin create-jvm-options --user $AS70_ADMIN --passwordfile $FILE_AS70_ADMINPASSWD --host $AS70_HOST --port $AS70_ADMINPORT --instance $AS70_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=true:-Dserver.name=$AS70_INSTANCE 
  else
#    $AS70_HOME/bin/asadmin create-jvm-options --user $AS70_ADMIN --passwordfile $FILE_AS70_ADMINPASSWD --host $AS70_HOST --port $AS70_ADMINPORT --instance $AS70_INSTANCE -- -Djava.endorsed.dirs=${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=true 
    $AS70_HOME/bin/asadmin create-jvm-options --user $AS70_ADMIN --passwordfile $FILE_AS70_ADMINPASSWD --host $AS70_HOST --port $AS70_ADMINPORT --instance $AS70_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=true 
  fi

}

configureServerPolicy()
{
# modifying server.policy
   file=${AS70_CONFIG_BASE}/server.policy
   cat <<EOF >> $file
   // Access Manager RELATED ADDITIONS
   grant codeBase "file:${PKGDIR}/lib/am_sdk.jar" {
     permission java.net.SocketPermission "localhost:*", "connect,accept,resolve";
   };
   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 javax.security.auth.kerberos.ServicePermission "*", "accept";
   };
   // 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
        MOBILE_ACCESS_LIB_DIR=/opt/sun/mobileaccess/share/lib
  else
        MOBILE_ACCESS_LIB_DIR=/opt/SUNWma/lib
  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/xalan.jar:$LIB_DIR/xmlsec.jar:$LIB_DIR/xercesImpl.jar:$LIB_DIR/dom4j.jar:$LIB_DIR/jakarta-log4j-1.2.6.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:$LIB_DIR/namespace.jar:$LIB_DIR/relaxngDatatype.jar:$LIB_DIR/xsdlib.jar:$MOBILE_ACCESS_JARS"

   JWSDP_CLASSES="$LIB_DIR/sax.jar:$LIB_DIR/dom.jar:$LIB_DIR/saaj-api.jar:$LIB_DIR/jaxrpc-api.jar:$LIB_DIR/jaxrpc-impl.jar:$LIB_DIR/jaxrpc-spi.jar:$LIB_DIR/common-logging.jar:$LIB_DIR/saaj-impl.jar:$LIB_DIR/jaxp-api.jar:$LIB_DIR/mail.jar:$LIB_DIR/activation.jar:$LIB_DIR/jax-qname.jar:$LIB_DIR/jaxm-api.jar:$LIB_DIR/jaxm-runtime.jar:$LIB_DIR/jaxb-api.jar:$LIB_DIR/jaxb-impl.jar:$LIB_DIR/jaxb-libs.jar:$LIB_DIR/jaxb-xjc.jar"

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

    cd ${AS70_CONFIG_BASE}
 
    #step1: Get the classpathsuffix from server.xml
    initialclasspath=`$AS70_HOME/bin/asadmin get "$AS70_INSTANCE".java-config.classpathsuffix --user $AS70_ADMIN --passwordfile $FILE_AS70_ADMINPASSWD --host $AS70_HOST --port $AS70_ADMINPORT | 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 server.xml
    $AS70_HOME/bin/asadmin set "$AS70_INSTANCE".java-config.classpathsuffix="$classpathadded" --user $AS70_ADMIN --passwordfile $FILE_AS70_ADMINPASSWD --host $AS70_HOST --port $AS70_ADMINPORT

    #step4: As done in step1 through step3, the similar approach is used to get and set the classpath-prefix. Get the classpathprefix from server.xml
    classpathprefix=`$AS70_HOME/bin/asadmin get "$AS70_INSTANCE".java-config.classpathprefix --user $AS70_ADMIN --passwordfile $FILE_AS70_ADMINPASSWD --host $AS70_HOST --port $AS70_ADMINPORT | 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 server.xml
   $AS70_HOME/bin/asadmin set "$AS70_INSTANCE".java-config.classpathprefix="$classpathadded" --user $AS70_ADMIN --passwordfile $FILE_AS70_ADMINPASSWD --host $AS70_HOST --port $AS70_ADMINPORT
}

reconfigureAS70()
{
  # Since we have modified server config file, we need to reconfigure.
  $AS70_HOME/bin/asadmin reconfig --user $AS70_ADMIN --passwordfile $FILE_AS70_ADMINPASSWD --host $AS70_HOST --port $AS70_ADMINPORT $AS70_INSTANCE > /dev/null 2>&1
  if [ $? != 0 ]; then
       echo "Reconfiguration is not successful. Please reconfigure either through application server console or manually."
  fi
  if [ "$NEW_INSTANCE" = "true" ];then
    # create new AMConfig-instance.properties
    # update the platform server list
    configNewInstance
  fi
}

tagSwap()
{

EDIT_FILES="
${CONFIG_DIR}/AMConfig.properties
${PKGDIR}/bin/amserver
${PKGDIR}/bin/am2bak
${PKGDIR}/bin/bak2am
${PKGDIR}/share/bin/amserver.instance_template
${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"

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#false#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#${AS70_CONFIG_BASE}#g" \
      -e "s#CONTAINER_CERTDB_PREFIX##g" \
      -e "s#WEB_CONTAINER#IAS7.0#g" \
      -e "s#BASEDIR/PRODUCT_DIR/config#${CONFIG_DIR}#g" \
      -e "s#SUNAPPSERVER_INSTANCE_DIR_TAG#${AS70_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 $AS70_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
configureAS70()
{
  echo "Checking if App Server is already configured with Access Manager "
  check_server_xml $AS70_INSTANCE_DIR/config/server.xml xml as70
  if [ $? -ne 1 ];then        # not configured yet
  echo "Configing App Server "
  backupConfig
  setJavaOptions
  #configureEndorsedDirs
  configureServerPolicy
  configureJvmPolicy
  setClassPath
  # Begin PORTALMA
  # MA mime types
  addMimeTypes
  # End PORTALMA
  reconfigureAS70

  # online help link to the docroot
  ln -s ${PKGDIR}/public_html/online_help $AS70_DOCS_DIR/online_help 2>/dev/null
  ln -s ${PKGDIR}/docs $AS70_DOCS_DIR/api 2>/dev/null
  fi
  
  # Update the server entry.  
  if [ "$NEW_INSTANCE" = "true" ]; then
    addServerEntry $AS70_INSTANCE
  elif [ "$DIRECTORY_MODE" = "4" ]; then
    addServerEntry
  fi
  
}

doDeploy()
{

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

  echo "$AS70_HOME/bin/asadmin deploy --user $AS70_ADMIN --passwordfile XXXXXXXX --host $AS70_HOST --port $AS70_ADMINPORT --type web --contextroot $DEPLOY_WARPREFIX --name $DEPLOY_WARPREFIX --instance $AS70_INSTANCE ${PKGDIR}/${warfile}"

  $AS70_HOME/bin/asadmin deploy --user $AS70_ADMIN --passwordfile $FILE_AS70_ADMINPASSWD --host $AS70_HOST --port $AS70_ADMINPORT --type web --contextroot $DEPLOY_WARPREFIX --name $DEPLOY_WARPREFIX --instance $AS70_INSTANCE ${PKGDIR}/${warfile}
 
  if [ $? -eq 0 ];then
    echo "Successfully deployed $CURRENT_DEPLOY_URI"
  else
    echo "Failed deploying $CURRENT_DEPLOY_URI"
  fi 
}

# deploy Access Manager to webcontainer
deploy_it()
{
  ma_auth_files=""
  idx=${1:-0}
  case $idx in
   0)
        CURRENT_DEPLOY_URI=${uri1:-/amconsole}  # /amconsole default
        warfile=amconsole.war
        DEPLOY_SRC=$CONSOLE_DIR
        DEPLOY_DIR=$CONSOLE_DEPLOY_DIR
        CURRENT_WEB_APP="applications"
        ;;
   1)
        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)
        CURRENT_DEPLOY_URI=${uri3:-/ampassword} # /ampassword default
        warfile=password.war
        DEPLOY_SRC=$PASSWORD_DIR
        DEPLOY_DIR=$PASSWORD_DEPLOY_DIR
        CURRENT_WEB_APP="password"
        ;;
   3)
        CURRENT_DEPLOY_URI=${uri4:-/amcommon}   # /amcommon default
        warfile=introduction.war
        DEPLOY_SRC=$COMMON_DIR
        DEPLOY_DIR=$COMMON_DEPLOY_DIR
        CURRENT_WEB_APP="common"
        ;;
  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
    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 done making warfile..."
  else
      echo "Failed in making 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

}

unconfigureAS70()
{

  # Get the classpathsuffix from server.xml
  classpath=`$AS70_HOME/bin/asadmin get "$AS70_INSTANCE".java-config.classpathsuffix --user $AS70_ADMIN --passwordfile $FILE_AS70_ADMINPASSWD --host $AS70_HOST --port $AS70_ADMINPORT | nawk ' BEGIN { FS="=" } { print $2} '`

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

  # unconfig ias70 and remove all Access Manager related config
  cd ${AS70_CONFIG_BASE}

  #Delete the jvm-options and unset the classpath that are set in server.xml while deploying.
  if [ "$NEW_INSTANCE" = "true" ];then
#    $AS70_HOME/bin/asadmin delete-jvm-options --user $AS70_ADMIN --passwordfile $FILE_AS70_ADMINPASSWD --host $AS70_HOST --port $AS70_ADMINPORT --instance $AS70_INSTANCE -- -Djava.endorsed.dirs=${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=true:-Dserver.name=$AS70_INSTANCE
    $AS70_HOME/bin/asadmin delete-jvm-options --user $AS70_ADMIN --passwordfile $FILE_AS70_ADMINPASSWD --host $AS70_HOST --port $AS70_ADMINPORT --instance $AS70_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=true:-Dserver.name=$AS70_INSTANCE
  else
#    $AS70_HOME/bin/asadmin delete-jvm-options --user $AS70_ADMIN --passwordfile $FILE_AS70_ADMINPASSWD --host $AS70_HOST --port $AS70_ADMINPORT --instance $AS70_INSTANCE -- -Djava.endorsed.dirs=${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=true
    $AS70_HOME/bin/asadmin delete-jvm-options --user $AS70_ADMIN --passwordfile $FILE_AS70_ADMINPASSWD --host $AS70_HOST --port $AS70_ADMINPORT --instance $AS70_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=true
  fi

  # Begin PORTALMA
  # Remove mime types added by MA
  map_mime_id="map_mime"
  $AS70_HOME/bin/asadmin delete-mime --user $AS70_ADMIN --passwordfile $FILE_AS70_ADMINPASSWD --host $AS70_HOST --port $AS70_ADMINPORT --instance $AS70_INSTANCE $map_mime_id
  # End PORTALMA
  
  $AS70_HOME/bin/asadmin set "$AS70_INSTANCE".java-config.classpathsuffix="$classpathremoved" --user $AS70_ADMIN --passwordfile $FILE_AS70_ADMINPASSWD --host $AS70_HOST --port $AS70_ADMINPORT

  # Get the classpathprefix from server.xml
  classpathprefix=`$AS70_HOME/bin/asadmin get "$AS70_INSTANCE".java-config.classpathprefix --user $AS70_ADMIN --passwordfile $FILE_AS70_ADMINPASSWD --host $AS70_HOST --port $AS70_ADMINPORT | nawk ' BEGIN { FS="=" } { print $2} '`

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

  # Set the original classpathprefix into server.xml
  $AS70_HOME/bin/asadmin set "$AS70_INSTANCE".java-config.classpathprefix="$classpathremoved" --user $AS70_ADMIN --passwordfile $FILE_AS70_ADMINPASSWD --host $AS70_HOST --port $AS70_ADMINPORT

  # 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=${AS70_INSTANCE_DIR}/config/.dsame
  rm -fr $BACKUP_DIR 2>/dev/null

    # deleting permission settings in server.policy
    file="server.policy"
    line=`cat $file | grep -n "Access Manager RELATED ADDITIONS" | nawk ' BEGIN { FS=":" } { print $1}'`
    count=1
    while [ $count -lt 38 ]
    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

  reconfigureAS70
}

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"

  $AS70_HOME/bin/asadmin undeploy --user $AS70_ADMIN --passwordfile $FILE_AS70_ADMINPASSWD --host $AS70_HOST --port $AS70_ADMINPORT --instance $AS70_INSTANCE --type web $UNDEPLOY_URI

  if [ $? -eq 0 ];then
    echo "Successfully done undeploying $CURRENT_DEPLOY_URI ..."
  else
    echo "Failed undeploying $CURRENT_DEPLOY_URI ..."
  fi
}

deploy_all()
{
  deploy_it 0
  deploy_it 1
  deploy_it 2
  deploy_it 3
}

undeploy_all()
{
  undeploy_it 3 "no"
  undeploy_it 2 "no"
  undeploy_it 1 "no"
  undeploy_it 0 "yes"
}


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

# stop appserver 
stop_as70()
{
  $AS70_INSTANCE_DIR/bin/stopserv
}

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

}

# Begin PORTALMA
# This method adds wml and wbmp to app server mime types
addMimeTypes() {
  # Do not proceed if SUNWamma / sun-identity-mobileaccess is not installed
  is_pkg_installed $MA_PKGNAME
  if [ $? -ne 0 ]; then
  	return
  fi

  mime_ids=`$AS70_HOME/bin/asadmin list-mimes --user $AS70_ADMIN --passwordfile $FILE_AS70_ADMINPASSWD --host $AS70_HOST --port $AS70_ADMINPORT $AS70_INSTANCE`
  map_mime_id="map_mime"
  mime_present="false"
  map_mime_file="$CONFIG_DIR/map_mime.types"

  if [ $? -eq 0 ] && [ ! -z $mime_ids ]; then
      #Check if mime id is present 
      for mime_id in $mime_ids
      do
        if [ "$mime_id" = "$map_mime_id"  ]; then
	  mime_present="true"
	fi
      done

      if [ "$mime_present" = "false" ]; then
	 $AS70_HOME/bin/asadmin create-mime --user $AS70_ADMIN --passwordfile $FILE_AS70_ADMINPASSWD --host $AS70_HOST --port $AS70_ADMINPORT --instance $AS70_INSTANCE --mimefile $map_mime_file $map_mime_id
      else
         echo "$map_mime_id is already present in mimes list of instance $AS70_INSTANCE"
      fi
  fi
}

# End PORTALMA

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

create_password_files

PWD=`pwd`
# check system env. 
check_env

create_password_files
# DEPLOY_LEVEL level range from 10 ~ 99 of following meaning
case $DEPLOY_LEVEL in
	1)	# full install
		deploy_all
                configureAS70
		;;
	2)	# console only
		deploy_it 0
		deploy_it 2
                configureAS70
		;;
	4)	# sdk with container config
                configureAS70
		tagSwap
		;;
	5)	# federation only
                deploy_it 3
                configureAS70
		;;
	6)	# server only
                deploy_it 1
                deploy_it 3
                configureAS70
		;;
	7)	# container config
                configureAS70
		tagSwap
		;;
	11)	# uninstall full
		undeploy_all
                unconfigureAS70
		;;
	12)	# uninstall console only
		undeploy_it 0
		undeploy_it 2
                unconfigureAS70
		;;
	14)	# uninstall sdk with container config 
                unconfigureAS70
		;;
	15)	# uninstall federation
		undeploy_it 3
                unconfigureAS70
		;;
	16)	# uninstall server
		undeploy_it 3
		undeploy_it 1
                unconfigureAS70
		;;
	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


