#!/bin/sh

# Copyright © 2004 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, the Sun logo, Java and Sun[tm] ONE are trademarks or
# registered trademarks of Sun Microsystems, Inc. in the U.S. and other
# countries. 
# 
# Copyright © 2004 Sun Microsystems, Inc. Tous droits réservés. Sun
# Microsystems, Inc. détient les droits de propriété intellectuels relatifs
# à la technologie incorporée dans le produit qui est décrit dans ce document.
# En particulier, et ce sans limitation, ces droits de propriété
# intellectuelle peuvent inclure un ou plus des brevets américains listés
# à l'adresse http://www.sun.com/patents et un ou les brevets supplémentaires
# 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 développés par des
# tierces parties.
# 
# Sun, Sun Microsystems, le logo Sun, Java et Sun[tm] ONE sont des marques
# de fabrique ou des marques déposées de Sun Microsystems, Inc. aux
# Etats-Unis et dans d'autres pays.


# assume that Identity Server instance installed locally on this box
# and this script is to deploy it further to webserver 6.1 and 
# make further necessary changes to IS & webserver 6.1 site
#
# Variables imported into this script
# CONSOLE_DEPLOY_URI
# SERVER_DEPLOY_URI
# PASSWORD_DEPLOY_URI
# COMMON_DEPLOY_URI
# WS61_HOST
# WS61_HOME
# WS61_INSTANCE

###########################################################
# 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
	INSTALL_FILE_NOT_REQUIRED=true
	source_amutils
	do_interactive
	set -- -s $IS_SILENT_INSTALL_FILE
	INSTALL_FILE_NOT_REQUIRED=false
elif [ $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 "Usage: amws61config [ -s <silent> ]" 
    exit 
fi


source_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}"


WS61_HOSTNAME=`echo $WS61_HOST |nawk -F. '{print $1}'`
WS61_CONFIG_BASE=${WS61_HOME}/${WS61_INSTANCE}/config
WS61_INSTANCE_HOST=`echo $WS61_INSTANCE | sed -e "s/https-//"`
WS61_DEPLOY_DIR=${WS61_HOME}/${WS61_INSTANCE}/is-web-apps

# add path for wdeploy
JSS_JAR_FILE=${JSS_JAR_PATH}/jss3.jar
LIB_DIR=${PKGDIR}/lib
PATH=${WS61_HOME}/bin/https/httpadmin/bin:${JAVA_HOME}/bin:/bin:/usr/bin
export PATH
LD_LIBRARY_PATH=${JSS_SO_PATH}:${NSS_SO_PATH}:${NSPR_SO_PATH}:${WS61_HOME}/bin/https/lib
if [ "$OSTYPE" = "Linux" ]; then
	LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${JAVA_HOME}/jre/lib/i386/native_threads
fi
export LD_LIBRARY_PATH
CLASSPATH=$LIB_DIR/am_sdk.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:$LIB_DIR/servlet.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
CONSOLE_DEPLOY_DIR=$WS61_DEPLOY_DIR/applications
PASSWORD_DEPLOY_DIR=$WS61_DEPLOY_DIR/password
COMMON_DEPLOY_DIR=$WS61_DEPLOY_DIR/common
SERVICES_DEPLOY_DIR=$WS61_DEPLOY_DIR/services


backupConfig()
{
  WS61_CONFILES="$WS61_CONFIG_BASE/server.xml $WS61_CONFIG_BASE/server.policy "
  BACKUP_DIR=$WS61_CONFIG_BASE/.dsame
 
  if [ ! -d $BACKUP_DIR ];then
    mkdir -p $BACKUP_DIR
  fi
  cp -f $WS61_CONFILES $BACKUP_DIR/
}

setJavaOptions()
{
  # changes in server.xml for adding -D options

  file="$WS61_CONFIG_BASE/server.xml"

  insert_line $file "java.util.logging.manager" "<!-- End of addition for IS -->"
  insert_line $file "java.util.logging.manager" "<JVMOPTIONS>-Djava.util.logging.config.class=com.sun.identity.log.s1is.LogConfigReader</JVMOPTIONS>"
  insert_line $file "java.util.logging.manager" "<JVMOPTIONS>-DLOG_COMPATMODE=Off</JVMOPTIONS>"
  insert_line $file "java.util.logging.manager" "<JVMOPTIONS>-Djava.protocol.handler.pkgs=com.iplanet.services.comm</JVMOPTIONS>"
  insert_line $file "java.util.logging.manager" "<JVMOPTIONS>-Djava.endorsed.dirs=${PKGDIR}/lib/endorsed</JVMOPTIONS>"
  if [ $DEPLOY_LEVEL -eq 1 -o $DEPLOY_LEVEL -eq 21 -o $DEPLOY_LEVEL -eq 6 ];then
   insert_line $file "java.util.logging.manager" "<JVMOPTIONS>-Dcom.iplanet.am.serverMode=true</JVMOPTIONS>"
  fi
  insert_line $file "java.util.logging.manager" "<!-- Adding JVM Options for IS -->"
  insert_line $file "java.security.auth.login.config" "<JVMOPTIONS>-Ds1is.java.util.logging.config.class=com.sun.identity.log.s1is.LogConfigReader</JVMOPTIONS>"
  insert_line $file "java.security.auth.login.config" "<JVMOPTIONS>-DLOG_COMPATMODE=Off</JVMOPTIONS>"
  insert_line $file "java.security.auth.login.config" "<JVMOPTIONS>-Djava.protocol.handler.pkgs=com.iplanet.services.comm</JVMOPTIONS>"
  insert_line $file "java.security.auth.login.config" "<JVMOPTIONS>-Djava.endorsed.dirs=${PKGDIR}/lib/endorsed</JVMOPTIONS>"
  
  if [ "$NEW_INSTANCE" = "true" ];then
    insert_line $file "java.security.auth.login.config" "<JVMOPTIONS>-Dserver.name=$WS61_INSTANCE_HOST</JVMOPTIONS>"
    insert_line $file "java.security.auth.login.config" "<JVMOPTIONS>-Dcom.iplanet.am.serverMode=true</JVMOPTIONS>"
  fi
}

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

configureServerPolicy()
{
  # modifying server.policy
  file="$WS61_CONFIG_BASE/server.policy"
  add_to_end "$file" "// IS 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" "};"
  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
}

# would like to get rid of the notion of a new instance and treat
# all instances the same. Only issue at this point is AMConfig and
# the ports. Perhaps pass them in through VM params.

configNewInstance()
{
  cd $CONFIG_DIR
  NORMALIZED_INSTANCE_HOST=`echo $WS61_INSTANCE_HOST | 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 | egrep -e "^com.iplanet.am.server.port" | /usr/bin/awk ' BEGIN { FS = "=" } { print $2 }'`
  OLDHOST=`cat $CONFIG_DIR/AMConfig.properties | egrep -e "^com.iplanet.am.server.host" | /usr/bin/awk ' BEGIN { FS = "=" } { print $2 }'`
  OLDPROTOCOL=`cat $CONFIG_DIR/AMConfig.properties | egrep -e "^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.server.host=$OLDHOST" "com.iplanet.am.server.host=$SERVER_HOST"
  replace_line "$file" "^com.iplanet.am.console.host=$OLDHOST" "com.iplanet.am.console.host=$CONSOLE_HOST"
  replace_line "$file" "^com.iplanet.am.profile.host=$OLDHOST" "com.iplanet.am.profile.host=$SERVER_HOST"
  replace_line "$file" "^com.iplanet.am.localserver.host=$OLDHOST" "com.iplanet.am.localserver.host=$SERVER_HOST"

  replace_line "$file" "^com.iplanet.am.server.protocol=$OLDPROTOCOL" "com.iplanet.am.server.protocol=$SERVER_PROTOCOL"
  replace_line "$file" "^com.iplanet.am.console.protocol=$OLDPROTOCOL" "com.iplanet.am.console.protocol=$CONSOLE_PROTOCOL"
  replace_line "$file" "^com.iplanet.am.profile.protocol=$OLDPROTOCOL" "com.iplanet.am.profile.protocol=$SERVER_PROTOCOL"
  replace_line "$file" "^com.iplanet.am.localserver.protocol=$OLDPROTOCOL" "com.iplanet.am.localserver.protocol=$SERVER_PROTOCOL"

  replace_line "$file" "^com.iplanet.am.naming.url=$OLDPROTOCOL:\/\/$OLDHOST:$OLDPORT\/amserver\/namingservice" "com.iplanet.am.naming.url=$SERVER_PROTOCOL:\/\/$SERVER_HOST:$SERVER_PORT\/amserver\/namingservice"
  replace_line "$file" "^com.iplanet.am.notification.url=$OLDPROTOCOL:\/\/$OLDHOST:$OLDPORT\/amserver\/notificationservice" "com.iplanet.am.notification.url=$SERVER_PROTOCOL:\/\/$SERVER_HOST:$SERVER_PORT\/amserver\/notificationservice"

  replace_line "$file" "^com.sun.identity.liberty.interaction.wspRedirectHandler=$OLDPROTOCOL:\/\/$OLDHOST:$OLDPORT\/amserver\/WSPRedirectHandler" "com.sun.identity.liberty.interaction.wspRedirectHandler=$SERVER_PROTOCOL:\/\/$SERVER_HOST:$SERVER_PORT\/amserver\/WSPRedirectHandler"
  rm -f $CONFIG_DIR/AMConfig-$NORMALIZED_INSTANCE_HOST.properties-orig*
  addServerEntry $WS61_HOST
}


# configure s1ws
configureWS61()
{
  echo "Checking if Web Server is already configed with IS "
  check_server_xml $WS61_HOME/$WS61_INSTANCE/config/server.xml xml ws61
  if [ $? -ne 1 ];then  # not configed yet
  echo Configuring Web Server
  backupConfig
  setJavaOptions
  configureServerPolicy
  #configureJavaSecurity
  configureEndorsedDirs
  setClassPath

  # Begin PORTALMA
  #Add mime types for WML
  addMimeTypes
  # End PORTALMA

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

  if [ "$NEW_INSTANCE" = "true" ];then
    # create new AMConfig-instance.properties
    # update the platform server list
    configNewInstance
  elif [ "$DIRECTORY_MODE" = "4" ]; then
    addServerEntry
  fi
}


  # Begin PORTALMA
  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/sax.jar:$LIB_DIR/dom.jar:$LIB_DIR/dom4j.jar:$LIB_DIR/jakarta-log4j-1.2.6.jar:$LIB_DIR/saaj-api.jar:$LIB_DIR/jaxrpc-api.jar:$LIB_DIR/jaxrpc-impl.jar:$LIB_DIR/jaxrpc-spi.jar:$LIB_DIR/saaj-impl.jar:$CONFIG_DIR:$LIB_DIR:$PKGDIR/locale:$JSS_JAR_FILE:$LIB_DIR/am_sdk.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/commons-logging.jar:$LIB_DIR/jaas.jar:$LIB_DIR/jax-qname.jar:$LIB_DIR/jaxm-api.jar:$LIB_DIR/jaxm-runtime.jar:$LIB_DIR/jce1_2_1.jar:$LIB_DIR/jdk_logging.jar:$LIB_DIR/servlet.jar:$LIB_DIR/xsltc.jar:$LIB_DIR/namespace.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"

setClassPath()
{

  cd ${WS61_CONFIG_BASE}

  #step1: grep for classpath suffix in server.xml
  file="$WS61_CONFIG_BASE/server.xml"
  classpath=`grep classpathsuffix $file`

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

  #step3: Add our classpath to the existing Classpathsuffix in server.xml
  count=1
  newline=""
  while [ $count -le $var ]
  do
      currentToken=`echo $classpath | cut -f$count -d " "`
      classpathToken=`echo $currentToken | cut -f$count -d " " | grep "classpathsuffix"`
      if [ "$classpathToken" != "" ]; then
          classpathToken=`echo $classpathToken | nawk ' BEGIN { FS="=" } { print $2 } ' | cut -f2 -d "\""`
          classpathAdd $classpathToken $JVM_CLASSPATH_CLASSES
          classpathsuffix="classpathsuffix=\"$classpathadded\""
          newline="$newline $classpathsuffix"
      else
          newline="$newline $currentToken"
      fi
      count=`expr $count + 1`
  done

  replace_line "$file" "classpathsuffix" "$newline"

}

# Begin PORTALMA
addMimeTypes() {

  # Do not proceed if SUNWamma / sun-identity-mobileaccess is not installed
  is_pkg_installed $MA_PKGNAME
  if [ $? -ne 0 ]; then
  	return
  fi

  MIME_TYPES_FILE=$WS61_CONFIG_BASE/mime.types

  MIME_TYPES="type=text/vnd.wap.wml type=image/vnd.wap.wbmp"

  MIME_TYPE_EXTS_1="exts=wml"
  MIME_TYPE_EXTS_2="exts=wbmp"

  i=1
  for MIME_TYPE in ${MIME_TYPES};
  do
    # Check if mime type already exists
    grep ${MIME_TYPE} $MIME_TYPES_FILE > /dev/null 2>&1

    if [ $? -ne 0 ]; then
	eval MIME_EXT=\$MIME_TYPE_EXTS_$i
	echo "Adding '$MIME_TYPE    $MIME_EXT' in ${MIME_TYPES_FILE}"
	echo "$MIME_TYPE    $MIME_EXT" >> ${MIME_TYPES_FILE}
    else
      echo "Mime type: '${MIME_TYPE}' already exists: Skipping ...."
    fi
    i=`expr $i + 1`
  done

}
# End PORTALMA

doUndeploy()
{

  ADMIN_SERVER_URI="$WS61_PROTOCOL://$WS61_HOSTNAME:$WS61_PORT"
  echo "undeploying $CURRENT_DEPLOY_URI from $ADMIN_SERVER_URI"
  echo "wdeploy delete -u ${CURRENT_DEPLOY_URI} -i ${WS61_INSTANCE} -v ${WS61_INSTANCE} -n hard"
  wdeploy delete -u ${CURRENT_DEPLOY_URI} -i ${WS61_INSTANCE} -v ${WS61_INSTANCE} -n hard
  if [ $? -eq 0 ];then
    echo "Successfully done undeploying $CURRENT_DEPLOY_URI ..."
  else
    echo "Failed undeploying $CURRENT_DEPLOY_URI ..."
  fi

}


doDeploy()
{
  echo "Deploying from $DEPLOY_SRC ($PKGDIR/$warfile) to $DEPLOY_DIR for $CURRENT_DEPLOY_URI"

  echo "wdeploy deploy -u $CURRENT_DEPLOY_URI -i $WS61_INSTANCE -v $WS61_INSTANCE -d $DEPLOY_DIR $PKGDIR/$warfile"
        wdeploy deploy -u $CURRENT_DEPLOY_URI -i $WS61_INSTANCE -v $WS61_INSTANCE -d $DEPLOY_DIR $PKGDIR/$warfile

  if [ $? -eq 0 ];then
    echo "Successfully deployed $CURRENT_DEPLOY_URI"
  else
    echo "Failed deploying $CURRENT_DEPLOY_URI"
  fi

}

tagSwap() 
{

 EDIT_FILES="
${CONFIG_DIR}/AMConfig.properties 
${PKGDIR}/bin/amserver
${PKGDIR}/share/bin/amserver.instance_template 
${COMMON_DIR}/WEB-INF/classes/FSIntroConfig.properties
${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#WS61_INSTANCE#${WS61_INSTANCE}#g" \
      -e "s#WS61_HOME#${WS61_HOME}#g" \
      -e "s#COOKIE_ENCODE#false#g" \
      -e "s#COOKIE_DOMAIN#${COOKIE_DOMAIN_LIST}#g" \
      -e "s#JSSHOME#${JSS_ROOTDIR}#g" \
      -e "s#CONTAINER_CERTDB_DIR#${WS61_HOME}/alias#g" \
      -e "s#CONTAINER_CERTDB_PREFIX#https-${WS61_HOST}-${WS61_HOSTNAME}-#g" \
      -e "s#BASEDIR/PRODUCT_DIR/config#${CONFIG_DIR}#g" \
      -e "s#NSSHOME#${NSS_ROOTDIR}#g" \
      -e "s#NSPRHOME#${NSPR_ROOTDIR}#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

}

# deploy IS to webcontainer
deploy_it()
{
  # Begin PORTALMA
  ma_auth_files=""
  # End PORTALMA
  idx=${1:-0}
  case $idx in
   0)
	CURRENT_DEPLOY_URI=${uri1:-/amconsole}	# /amconsole default
	warfile=console.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_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 [ ! -d $DEPLOY_SRC ]; then
    mkdir -p $DEPLOY_SRC
    cd $DEPLOY_SRC 
    jar xf $PKGDIR/$warfile

    # Begin PORTALMA
    #Add the ma auth files to the services web application
    if [ -n "$ma_auth_files" ]; then
	is_pkg_installed $MA_PKGNAME
	if [ $? -eq 0 ]; then
		jar xf $PKGDIR/$ma_auth_files
		rm $PKGDIR/$ma_auth_files
	fi
    fi
    # Begin PORTALMA

  fi
  rm $PKGDIR/$warfile

  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 $idx

  # post-deploy works
  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

}

unconfigureWS61()
{
  echo Unconfiguring Web Server
  # restore the ws and IS 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 iws61 and remove all IS related config
 cd ${WS61_HOME}/${WS61_INSTANCE}/config
 file=server.xml
 delete_line "$file" "LOG_COMPATMODE=Off"
 delete_line "$file" "java.protocol.handler.pkgs=com.iplanet.services.comm"
 delete_line "$file" "java.endorsed.dirs="
 delete_line "$file" "java.util.logging.config.class=com.sun.identity.log.s1is.LogConfigReader"
 delete_line "$file" "com.iplanet.am.serverMode=true"

 # check if this is an instance by looking for the -instance name in AMConfig
 NORMALIZED_INSTANCE_HOST=`echo $WS61_INSTANCE_HOST | sed -e "s/\./_/g"`
 rm -f $CONFIG_DIR/AMConfig-$NORMALIZED_INSTANCE_HOST.properites

 rm -f $WS61_HOME/docs/online_help

 cp=`grep classpathsuffix $file`

 #step 2
 var=`echo $cp | nawk ' { print NF } '` # this is to print the number of tokens

 #step 3
 #add our stuff to classpath
 count=1
 newline=""
 while [ $count -le $var ]
 do
      currentToken=`echo $cp | cut -f$count -d " "`
      classpathToken=`echo $currentToken | cut -f$count -d " " | grep "classpathsuffix"`
      if [ "$classpathToken" != "" ]; then
          classpathToken=`echo $classpathToken | nawk ' BEGIN { FS="=" } { print $2 } ' | cut -f2 -d "\""`
          classpathRemove $classpathToken $JVM_CLASSPATH_CLASSES
          newclasspathsuffix="classpathsuffix=\"$classpathremoved\""
          newline="$newline $newclasspathsuffix"
       else
          newline="$newline $currentToken"
       fi
       count=`expr $count + 1`
 done
 replace_line "$file" "classpathsuffix" "$newline"

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

 # Begin PORTALMA
 # Remove mime types added by MA
 MIME_TYPES_FILE=$WS61_CONFIG_BASE/mime.types
 MIME_TYPES="vnd.wap.wml vnd.wap.wbmp"
 for MIME_TYPE in ${MIME_TYPES};
 do
   delete_line "$MIME_TYPES_FILE" "$MIME_TYPE"
 done
 # End PORTALMA

}

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

# invoke doUndeploy and that function decide if to undeploy based on env
doUndeploy $idx

}

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

# undeploy_all func
undeploy_all()
{
  undeploy_it 3
  undeploy_it 2
  undeploy_it 1
  undeploy_it 0
}

# start webserver
start_ws61()
{
  if [ -x $WS61_HOME/$WS61_INSTANCE/start ];then
   if [ "$WS61_IS_SECURE" != "false" ];then       # SSL enabled
    $WS61_HOME/$WS61_INSTANCE/start <<EOF
$SSL_PASSWORD
EOF
   else
    $WS61_HOME/$WS61_INSTANCE/start 
   fi
  else
    echo "webserver 6.1 image ($WS61_HOME) has problem"
    exit 0
  fi
  echo "Webserver 6.1 started."
}

# stop webserver 
stop_ws61()
{
  if [ -x $WS61_HOME/$WS61_INSTANCE/stop ];then
	$WS61_HOME/$WS61_INSTANCE/stop 
  else
    echo "webserver 6.1 image ($WS61_HOME) has problem"
    exit 0
  fi
  echo "Webserver 6.1 stopped."
}

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

}

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

PWD=`pwd`
# check system env. 
check_env


# DEPLOY_LEVEL level range from 10 ~ 99 of following meaning
case $DEPLOY_LEVEL in
	1)	# full install
		deploy_all
                configureWS61
		;;
	2)	# console only
		deploy_it 0
		deploy_it 2
                configureWS61
		;;
	4)	# sdk only container config
                configureWS61
		;;
	5)	# federation only
		deploy_it 3
                configureWS61
		;;
	6)	# server only
		deploy_it 1
		deploy_it 3
                configureWS61
		;;
	11)	# full uninstall
		undeploy_all
                unconfigureWS61
		;;
	12)	# uninstall amconsole only
		undeploy_it 0
		undeploy_it 2
                unconfigureWS61
		;;
	14)	# uninstall sdk only with container config
                unconfigureWS61
		;;
	15)	# undeploy ampassword only
		undeploy_it 3
                unconfigureWS61
		;;
	16)	# undeploy server only
		undeploy_it 3
		undeploy_it 1
                unconfigureWS61
		;;
	21*)	# redeploy all
		undeploy_all
		deploy_all
		;;
	22*)	# redeploy console
		undeploy_it 0
		deploy_it 0 "yes"
		;;
	23*)	# redeploy services
		undeploy_it 1
		deploy_it 1 "yes"
		;;
	24*)	# redeploy password
		undeploy_it 2
		deploy_it 2
		;;
	25*)	# redeploy common
		undeploy_it 3
		deploy_it 3
		;;
	26*)	# redeploy server only
                undeploy_it 3
                undeploy_it 1
                deploy_it 3
                deploy_it 1
		;;
	27*)	# undeploy console
		undeploy_it 0
		;;
	28*)	# undeploy password
		undeploy_it 2
		;;
	29*)	# undeploy services
		undeploy_it 1
		;;
	30*)	# undeploy common
		undeploy_it 3
		;;
	31*)	# redeploy sdk only
		;;
	32* | 33*)	# redeploy console/console-sdk only
		undeploy_it 2
		undeploy_it 0
		deploy_it 2
		deploy_it 0
		;;
	35*)	# redeploy federation only
		undeploy_it 3
		deploy_it 3
		;;
	*)	echo "Unsupported DEPLOY_LEVEL value" 
		exit 0 ;;
esac



