#!/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 webserver 6.1 and 
# make further necessary changes to Access Manager & webserver 6.1 site
#
# Variables imported into this script
# CONSOLE_DEPLOY_URI = 7.0 Console
# OLDCON_DEPLOY_URI = 6.3 Console
# SERVER_DEPLOY_URI
# PASSWORD_DEPLOY_URI
# COMMON_DEPLOY_URI
# WS61_HOST
# WS61_HOME
# WS61_INSTANCE

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"
notification_url=$SERVER_PROTOCOL://$SERVER_HOST:$SERVER_PORT$SERVER_DEPLOY_URI/notificationservice

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


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

if [ ! -f ${WS61_HOME}/bin/https/httpadmin/bin/wdeploy ]; then
	$ECHO "wdeploy command not found!"
	exit 1
fi

# add path for wdeploy
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/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
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
  for file in $WS61_CONFILES
  do
    if [ ! -f $BACKUP_DIR/$file ];then
      cp -f $file $BACKUP_DIR/
    fi
  done
}

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 Access Manager -->"
  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 Access Manager -->"
  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" "// 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 \"s1is.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
}

# 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 | grep "com.iplanet.am.server.port" | /usr/bin/awk ' BEGIN { FS = "=" } { print $2 }'`
  OLDHOST=`cat $CONFIG_DIR/AMConfig.properties | grep "com.iplanet.am.server.host" | /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.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\\$uri2\/namingservice" "com.iplanet.am.naming.url=$SERVER_PROTOCOL:\/\/$SERVER_HOST:$SERVER_PORT\\$uri2\/namingservice"
  replace_line "$file" "com.iplanet.am.notification.url=$OLDPROTOCOL:\/\/$OLDHOST:$OLDPORT\\$uri2\/notificationservice" "com.iplanet.am.notification.url=$SERVER_PROTOCOL:\/\/$SERVER_HOST:$SERVER_PORT\\$uri2\/notificationservice"

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


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

  # 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
  ln -s $PKGDIR/docs $WS61_HOME/docs/api 2>/dev/null
  fi

  # update the platform server list
  if [ "$NEW_INSTANCE" = "true" -a "$DIRECTORY_MODE" = "4" ];then
    addServerEntry
  elif [ "$DIRECTORY_MODE" = "2" ]; then
    addServerEntry
  fi
}


  # Begin PORTALMA
  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/xalan.jar:$LIB_DIR/xmlsec.jar:$LIB_DIR/xercesImpl.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/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/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/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"

}

configureJavaExtLib() {
  file="$WS61_CONFIG_BASE/server.xml"
  [ -f $file ] || return 1
  wsjavahome=`grep '<JAVA[ 	]*' $file | sed 's/^.*javahome="\([^"]*\)".*$/\1/g'`
  wsjavaext=$wsjavahome/jre/lib/ext
  if [ ! -d $wsjavaext ] ; then
    mkdir -p $wsjavaext
    chmod 775 $wsjavaext
  fi

  # javahelp
  jhdest=$wsjavaext/jhall.jar
  if [ -r $jhdest ] ; then
    echo "JavaHelp is already configured."
    return 0
  fi
  if [ "$OSTYPE" = "SunOS" ] ; then
    pkgname=SUNWjhrt
  elif [  "$OSTYPE" = "Linux" ] ; then
    pkgname=sun-javahelp
  else
    return 1
  fi
  is_pkg_installed $pkgname
  if [ $? -eq 1 ] ; then
    echo "Error: The dependent package $pkgname is missing!"
    return 1
  fi
  getFilePathFromPackage $pkgname jhall.jar
  if [ x"$FILE_PATH" = x"" ] ; then
    echo "Failed configuring JavaHelp.  Cannot find file jhall.jar!"
    return 1
  fi
  if [ ! -r $FILE_PATH ] ; then
    echo "Failed configuring JavaHelp. File $FILE_PATH not accessible!"
    return 1
  fi
  rm -rf $jhdest >/dev/null
  ln -s $FILE_PATH $jhdest
  return 0
}

# 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() 
{

$CP ${USR_DIR}/share/lib/identity/console-war/WEB-INF/web.xml.template ${USR_DIR}/share/lib/identity/console-war/WEB-INF/web.xml
$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
$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

if [ "$NEW_INSTANCE" = "false" -o "$NEW_INSTANCE" = "" ]; then
 EDIT_FILES="
${CONFIG_DIR}/AMConfig.properties 
${PKGDIR}/bin/amserver
${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"
else
 EDIT_FILES="
${CONFIG_DIR}/AMConfig-$INSTANCE.properties
${PKGDIR}/bin/amserver.$INSTANCE
${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"
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#OLDCON_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#NOTIFICATION_URL#$notification_url#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#${WS61_INSTANCE}-${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 Access Manager to webcontainer
deploy_it()
{
  # Begin PORTALMA
  ma_auth_files=""
  # End PORTALMA
  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_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
    # Begin 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 $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 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 iws61 and remove all Access Manager 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" "s1is.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 "Access Manager 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 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 func
undeploy_all()
{
  undeploy_it 3
  undeploy_it 2
  undeploy_it 1
  #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
  fi
}

# 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 start command not found at $WS61_HOME/$WS61_INSTANCE."
    exit 1
  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 stop command not found at $WS61_HOME/$WS61_INSTANCE."
    exit 1
  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
		tagSwap
                configureWS61
		;;
	5)	# federation only
		deploy_it 3
		;;
	6)	# server only
		deploy_it 1
		deploy_it 3
                configureWS61
		;;
	7)	# container config
		tagSwap
                configureWS61
		;;
	11)	# full uninstall
		undeploy_all
                unconfigureWS61
		cleanLogConfig
		;;
	12)	# uninstall amconsole only
		undeploy_it 0
		undeploy_it 2
                unconfigureWS61
		;;
	14)	# uninstall sdk only with container config
                unconfigureWS61
		;;
	15)	# undeploy federation
		undeploy_it 3
		;;
	16)	# undeploy server only
		undeploy_it 3
		undeploy_it 1
                unconfigureWS61
		;;
	17)	# uninstall container config
                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*)	# undeploy all
                undeploy_all
		;;
	27*)	# undeploy console
		undeploy_it 0
		;;
	28*)	# undeploy password
		undeploy_it 2
		;;
	29*)	# undeploy services
		undeploy_it 1
		;;
	30*)	# undeploy common
		undeploy_it 3
		;;
	*)	$ECHO "Unsupported DEPLOY_LEVEL value" 
		exit 0 ;;
esac



