#!/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 remotely on some box
# and this script is to deploy it locally to websphere server 5.1 and 
# any webapp on top of websphere will remotely talk to the Access Manager server
# through Access Manager SDK for SSO functionalities
#


if [ $# -eq 0 ]; then
    echo "Please use amconfig to configure Access Manager." 
    exit 
fi

if [ $# -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

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

WAS51_HOSTNAME=`echo $WAS51_HOST |nawk -F. '{print $1}'`
WAS51_CONFIG_BASE=$WAS51_HOME/config/cells/$WAS51_CELL/nodes/$WAS51_NODE/servers/$WAS51_INSTANCE
export WAS51_CONFIG_BASE
WAS51_CONFILES="$WAS51_CONFIG_BASE/server.xml "
export WAS51_CONFILES
BACKUP_DIR=$WAS51_CONFIG_BASE/.dsame
export BACKUP_DIR
WAS51_NEWLINE=""
export WAS51_NEWLINE
if [ $DEPLOY_LEVEL -eq 1 -o $DEPLOY_LEVEL -eq 6 -o $DEPLOY_LEVEL -eq 11 -o $DEPLOY_LEVEL -eq 16 -o $DEPLOY_LEVEL -eq 21 -o $DEPLOY_LEVEL -eq 26 ];then
 IS_OPTIONS="-Djava.util.logging.config.class=com.sun.identity.log.s1is.LogConfigReader -Djava.protocol.handler.pkgs=com.ibm.net.ssl.internal.www.protocol -Djava.util.logging.manager=com.sun.identity.log.LogManager -Dcom.iplanet.am.serverMode=true -DamCryptoDescriptor.provider=IBMJCE -DamKeyGenDescriptor.provider=IBMJCE"
 export IS_OPTIONS
else
 IS_OPTIONS="-Djava.util.logging.config.class=com.sun.identity.log.s1is.LogConfigReader -Djava.protocol.handler.pkgs=com.ibm.net.ssl.internal.www.protocol -Djava.util.logging.manager=com.sun.identity.log.LogManager -DamCryptoDescriptor.provider=IBMJCE -DamKeyGenDescriptor.provider=IBMJCE"
 export IS_OPTIONS
fi
LIB_DIR=${PKGDIR}/lib
export LIB_DIR

# Begin PORTALMA

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

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

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="$JSS_JAR_FILE:$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/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:$JAVA_HELPER:${MOBILE_ACCESS_JARS}"
export JVM_CLASSPATH_CLASSES

# add path for wdeploy
LIB_DIR=${PKGDIR}/lib
PATH=${WAS51_HOME}/bin:${JAVA_HOME}/bin:/bin:/usr/bin
export PATH
LD_LIBRARY_PATH=${JSS_SO_PATH}:${NSS_SO_PATH}:${NSPR_SO_PATH}:${WAS51_INSTANCE}/server/lib
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=$WAS51_DEPLOY_DIR/applications
PASSWORD_DEPLOY_DIR=$WAS51_DEPLOY_DIR/password
COMMON_DEPLOY_DIR=$WAS51_DEPLOY_DIR/common
SERVICES_DEPLOY_DIR=$WAS51_DEPLOY_DIR/services
notification_url=$SERVER_PROTOCOL://$SERVER_HOST:$SERVER_PORT$SERVER_DEPLOY_URI/notificationservice

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

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

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

cat <<EOF > $file
WSLogin {
        com.ibm.ws.security.common.auth.module.proxy.WSLoginModuleProxy required delegate=com.ibm.ws.security.common.auth.module.WSLoginModuleImpl;
EOF
}

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

configureServerPolicy()
{
  # modifying policy if any
  file="$WAS51_HOME/properties/server.policy"

  touch $file
  cp $file $file-bkup
  cat <<EOF >> $file 
// Access Manager RELATED ADDITIONS 
grant { 
permission java.lang.RuntimePermission "modifyThreadGroup"; 
permission java.lang.RuntimePermission "setFactory"; 
permission java.lang.RuntimePermission "accessClassInPackage.*"; 
permission java.lang.RuntimePermission "shutdownHooks";
permission java.util.logging.LoggingPermission "control";
permission java.util.PropertyPermission "java.util.logging.config.class", "write";
permission java.security.AllPermission;
permission java.io.FilePermission "<<ALL FILES>>", "execute,delete";
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.security.SecurityPermission "putProviderProperty.Mozilla-JSS";
permission java.security.SecurityPermission "insertProvider.Mozilla-JSS";
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.util.logging.config.class", "write";
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";
permission java.util.PropertyPermission "user.language", "write";
};
// END OF ADDITIONS FOR IS
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
  ln -s "${LIB_DIR}/xsltc.jar" "${LIB_DIR}/endorsed/xsltc.jar" 2>/dev/null
}

# configure websphere
configureWAS51()
{
  echo "Checking if WebSphere Server is configured with Access Manager"
  check_server_xml $WAS51_HOME/config/cells/$WAS51_CELL/nodes/$WAS51_NODE/servers/$WAS51_INSTANCE/server.xml xml was51
  if [ $? -ne 1 ];then  # not configured yet
  echo "Configuring WebSphere Server"
  backupConfig
  setJavaOptions
  configureServerPolicy
  configureJavaSecurity
  #configureEndorsedDirs
  setServerXml
  configStartServer

  enable_jce

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

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

}

configStartServer()
{
cd $WAS51_HOME/bin
file=startServer.sh
newfile=new$file-$$
rm -f $newfile;touch $newfile

case `uname -s` in
  SunOS)
	lno=`grep -n "SunOS)" $file|nawk -F: '{print $1}'`
	;;
  Linux)
	lno=`grep -n "Linux)" $file|nawk -F: '{print $1}'`
	;;
  *)
	lno=`grep -n "SunOS)" $file|nawk -F: '{print $1}'`
	;;
esac
lno=`expr $lno \+ 1`

line=`head -$lno $file |tail -1`
mod_line="${line}:$JSS_SO_PATH"
total_lines=`wc -l $file |awk '{print $1}'`
i=1
while [ $i -le $total_lines ];do
 if [ $i -ne $lno ];then
	thisline=`head -$i $file|tail -1`
	echo "$thisline" >> $newfile
 else
	echo "$mod_line" >> $newfile
 fi
 i=`expr $i \+ 1`
done
cp -f $newfile $file
rm -f $newfile
}

setServerXml()
{
# change server.xml of websphere
hvalue=0
vvalue=0        # 0=just jvmEntries, 1=with </jvmEntries> wrapper, 2=with <classpath>
file="server.xml"
newfile="new$file-$$"

  cd ${WAS51_CONFIG_BASE}

  rm -f $newfile; touch $newfile

 #LIB_DIR=${PKGDIR}/lib
for file in $WAS51_CONFILES 
do

# 1st: decide if </jvmEntries> is there for later use
if [ `grep "<classpath>" $file |wc -c` -ne 0 ];then     # has this entry
 # further check if classpath has all Access Manager stuff
 classpath_lno=`grep -n "<classpath>" $file |nawk -F: '{print $1}'`
 classpath_line=`head -$classpath_lno $file | tail -1`
 if [ `echo $classpath_line |grep $PRODUCT_DIR |wc -c` -ne 0 ];then	# all Access Manager stuff there
 	vvalue=3	
 else	# just empty classpath entry
	vvalue=2
 fi
elif [ `grep "</jvmEntries>" $file |wc -c` -ne 0 ];then # has this entry
 vvalue=1
fi
#echo "vvalue=$vvalue">vvalue.log
# 2nd: modify the <jvmEntries> line

jvmEntries_lno=`cat $file |grep -n "<jvmEntries"| nawk ' BEGIN { FS=":" } { print $1}'`
classpath_lno=`cat $file |grep -n "<classpath"| nawk ' BEGIN { FS=":" } { print $1}'`
#lno=`cat $file |grep -n "<jvmEntries"| nawk ' BEGIN { FS=":" } { print $1}'`
total_lines=`wc -l $file |awk '{print $1}'`
i=1

while [ $i -le $total_lines ];do
 if [ $i -eq $jvmEntries_lno ];then
        doThisline $jvmEntries_lno $file
        echo "    $WAS51_NEWLINE" >>$newfile
        if [ $vvalue -eq 0 ];then       # need add 2 entries
                echo "      <classpath>$JVM_CLASSPATH_CLASSES</classpath>" >>$newfile
                echo "    </jvmEntries>" >> $newfile
        elif [ $vvalue -eq 1 ];then     # just add classpath entry
                echo "      <classpath>$JVM_CLASSPATH_CLASSES</classpath>" >>$newfile
        elif [ $vvalue -eq 2 ];then     # just append Access Manager to exist classpath entry
		classpath_lno=`cat $file |grep -n "<classpath>"| nawk ' BEGIN { FS=":" } { print $1}'`
		classpath_line=`echo $classpath_line |sed -e 's#<classpath>##g' \
				-e 's#</classpath>##g'`
		if [ "X$classpath_line" = "X" ];then
                	classpath_line="      <classpath>$JVM_CLASSPATH_CLASSES</classpath>"
		else
                	classpath_line="      <classpath>$classpath_line:$JVM_CLASSPATH_CLASSES</classpath>" 
		fi
        fi
 elif [ $i -eq ${classpath_lno:-0} -a $vvalue -eq 2 ];then
	echo "$classpath_line" >> $newfile
 elif [ $i -eq ${classpath_lno:-0} ];then
                classpath_line=`echo $classpath_line |sed -e 's#<classpath>##g' \
                                -e 's#</classpath>##g'`
                if [ "X$classpath_line" = "X" ];then
                        classpath_line="      <classpath>$JVM_CLASSPATH_CLASSES</classpath>"
                else
                        classpath_line="      <classpath>$classpath_line:$JVM_CLASSPATH_CLASSES</classpath>"
                fi
	echo "$classpath_line" >> $newfile
 else
        head -$i $file|tail -1 >>$newfile
 fi
 i=`expr $i \+ 1`
done	# end of while 

done	# end of for

cp -f $newfile $file
rm -f $newfile

CryptoDescriptor=`grep "Property_1120370477732" $file`
if [ "$CryptoDescriptor" = "" ]; then
    insert_line $file '<components xmi:type="applicationserver.webcontainer:WebContainer"' \
            '<properties xmi:id="Property_1120370477732" name="amCryptoDescriptor.provider" value="IBMJCE" required="false"/>'
fi
KeyGenDescriptor=`grep "Property_1120370511939" $file`
if [ "$KeyGenDescriptor" = "" ]; then
    insert_line $file '<components xmi:type="applicationserver.webcontainer:WebContainer"' \
	    '<properties xmi:id="Property_1120370511939" name="amKeyGenDescriptor.provider" value="IBMJCE" required="false"/>'
fi

sync;sync;sync;sync;sync;sync;sync;sync;sync;sync;sync;sync;sync;sync;sync;sync
sleep 5		# wait long enough for the new change reflected
}

# change 1 line with new attributes
changeline()
{
lpattern=$1
ipattern=$2
token=$3
file=${4:-server.xml}
rm_genericjvmargs=${5:-0}	# if need to remove duplicate entry, default is no

line=`grep $lpattern $file`
firstToken=`echo $line |awk '{print $1}'`
if [ $firstToken != "" ];then
 if [ ${rm_genericjvmargs:-0} -eq 1 ];then
        line=`echo $line |nawk '{for(i=1;i<=NF;i++) if (index($i,"genericJvmArguments")==0) printf("%s ",$i); if (index($NF,"genericJvmArguments")!=0) printf (">"); }'`
 fi
        tmpline=`echo $line |nawk -v x="$ipattern" -v y="$token" '{for(i=1;i<=NF;i++) {if (index($i,x)==0) printf("%s ",$i);else printf(" %s %s ",$i,y);}}'`
        WAS51_NEWLINE=`echo $tmpline |nawk '{for(i=1;i<NF;i++) printf("%s ",$i); if((substr($NF,length($NF)-1,2))=="/>") printf ("%s>",substr($NF,1,length($NF)-2)); else printf ("%s",$NF);}'`
fi
}

# change jvm config line if necessary
doThisline()
{
lineno=$1
file=${2:-server.xml}

line=`head -$lineno $file |tail -1`
firstToken=`echo $line |awk '{print $1}'`

# 1st append entry after verboseModeJNI="false"  (horizontal)
if [ $firstToken != "" ];then
          newcp=`echo $line | awk ' BEGIN { FS=" "}
        {
             hvalue=0
             if (NF > 0) {
                 for (i = 1; i <= NF; i ++) {
                     if (index($i, "initialHeapSize") != 0) {
                         hvalue+=1
                     }
                     if (index($i, "maximumHeapSize") != 0) {
                         hvalue+=2
                     }
                     if (index($i, "genericJvmArguments") != 0) {
			if (index($i,"com.sun.identity.log.s1is.LogConfigReader") == 0) {
			 hvalue+=4 
			}
			else {
                         hvalue+=8
			}
		     }
                 }
             printf("%d",hvalue)
             }
         }'`

fi

case $newcp in
0)      # nothing
 changeline "<jvmEntries" "verboseModeJNI" "initialHeapSize=\"256\" maximumHeapSize=\"256\" genericJvmArguments=\"$IS_OPTIONS\"" $file 1
 ;;
1)      # only initialHeapSize there
 changeline "<jvmEntries" "initialHeapSize" "maximumHeapSize=\"256\" genericJvmArguments=\"$IS_OPTIONS\"" $file 1
 ;;
2)      # only maximumHeapSize there
 changeline "<jvmEntries" "verboseModeJNI" "initialHeapSize=\"256\"" $file 0
 changeline "<jvmEntries" "maximumHeapSize" "genericJvmArguments=\"$IS_OPTIONS\"" $file 1
 ;;
3)      # only initheapsize & maximumheapsize there
 changeline "<jvmEntries" "maximumHeapSize" "genericJvmArguments=\"$IS_OPTIONS\"" $file 1
 ;;
4)	# only genericjvmarguments there but no Access Manager stuff
 mod_genericJvmArgs "<jvmEntries" $file
 changeline "<jvmEntries" "verboseModeJNI" "initialHeapSize=\"256\" maximumHeapSize=\"256\" genericJvmArguments=\"$mod_line\"" $file 1
 ;;
5)	# both initheapsize & genericjvmarguments there with no Access Manager stuff
 mod_genericJvmArgs "<jvmEntries" $file
 changeline "<jvmEntries" "initialHeapSize" "maximumHeapSize=\"256\" genericJvmArguments=\"$mod_line\"" $file 1
 ;;
6)	# both maxheapsize & genericjvmarguments there with no Access Manager stuff
 mod_genericJvmArgs "<jvmEntries" $file
 changeline "<jvmEntries" "verboseModeJNI" "initialHeapSize=\"256\"" $file 0
 changeline "<jvmEntries" "maximumHeapSize" "genericJvmArguments=\"$mod_line\"" $file 1
 ;;
7)	# genericjvmarguments has no Access Manager stuff
 mod_genericJvmArgs "<jvmEntries" $file
 changeline "<jvmEntries" "maximumHeapSize" "genericJvmArguments=\"$mod_line\"" $file 1
 ;;
8)	# full Access Manager genericjvmarguments
 changeline "<jvmEntries" "verboseModeJNI" "initialHeapSize=\"256\" maximumHeapSize=\"256\"" $file 0
 ;;
9)
 changeline "<jvmEntries" "initialHeapSize" "maximumHeapSize=\"256\"" $file 0
 ;;
10)
 changeline "<jvmEntries" "verboseModeJNI" "initialHeapSize=\"256\"" $file 0
 ;;
11)	# all there
 WAS51_NEWLINE=`head -$lineno $file | tail -1 `
 ;;
esac

}

mod_genericJvmArgs()
{
pattern=$1
file=$2

#IS_pattern="-Djava.protocol.handler.pkgs=com.ibm.net.ssl.internal.www.protocol -Djava.util.logging.manager=com.sun.identity.log.LogManager -Djava.util.logging.config.class=com.sun.identity.log.s1is.LogConfigReader"

lineno=`grep -n "<jvmEntries" $file |nawk -F: '{print $1}'`
line=`head -$lineno $file |tail -1`

mod_line=`echo $line|awk '{for(i=1;i<=NF;i++)if(index($i,"genericJvmArguments")!=0) printf("%s",$i);}' |nawk -F= '{printf("%s",$NF);}' |sed -e 's#"##g' \
        -e 's#>##g' -e 's#[\/]$##' -e 's#^[ ]*##;s#[ ]*$##'`

if [ ${mod_line:-~} = "#" ];then
 mod_line="$IS_OPTIONS"
else if [ X${mod_line} = "X" ];then
 mod_line="$IS_OPTIONS"
else
 mod_line="$mod_line $IS_OPTIONS"
fi
fi
export mod_line
}

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

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

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

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

}

unconfigureWAS51()
{
  echo "Unconfiguring WebSphere 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 websphere and remove all Access Manager related config

 cd ${WAS51_CONFIG_BASE}

 #rm -f $WAS51_HOME/docs/online_help

 for file in $WAS51_CONFILES
 do
   tmpfile=$file-tmp-$$
   rm -f $tmpfile;touch $tmpfile
 
  # get line# and modified value for next use
  classpathlineno=`grep -n "<classpath>" $file | nawk -F: '{print $1}'`
  classpathline=`grep "<classpath>" $file | sed -e 's#<classpath>##g' \
		-e 's#</classpath>##g'`
  jvmentrieslineno=`grep -n "<jvmEntries" $file | nawk -F: '{print $1}'`
  jvmentriesline=`head -$jvmentrieslineno $file |tail -1`

  classpathRemove "$classpathline" "$JVM_CLASSPATH_CLASSES"
  classpathline=$classpathremoved

  for IS_OPTION in $IS_OPTIONS
  do
   classpathRemove "$jvmentriesline" "$IS_OPTION "
   classpathRemove "$jvmentriesline" "$IS_OPTION"
   jvmentriesline=$classpathremoved
  done
  jvmentriesline=`echo ${jvmentriesline} | sed -e "s#\" \"#\"\"#"`
  if [ X$classpathlineno != X ]; then
    i=1; total_lines=`wc -l $file |awk '{print $1}'`
    while [ $i -le $total_lines ];do
      if [ $i -eq $classpathlineno ]; then
        echo "      <classpath>${classpathline}</classpath>" >>$tmpfile
      elif [ $i -eq $jvmentrieslineno ];then
        echo "    $jvmentriesline" >>$tmpfile
      else
        head -$i $file |tail -1 >>$tmpfile
      fi
      i=`expr $i \+ 1`
    done        # end of while
    cp -f $tmpfile $file
    rm -f $tmpfile
  fi
  done  # end of for

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

 # restore server.policy
 cd $WAS51_HOME/properties
 lno=`grep -n "Access Manager RELATED ADDITIONS" server.policy |nawk -F: '{print $1}'`
 total=`wc -l server.policy |nawk '{print $1}'`
 if [ "x$lno" != "x" ];then
  for lines in $lno; do
    lines=`expr $lines \- 1`
    head -$lines server.policy >server.policy+
    lastline=`expr $lines \+ 31`
    if [ $lastline -lt $total ];then    # still somelines after AM config
        rest=`expr $total \- $lastline + 1`
        tail -$rest server.policy >> server.policy+
    fi
    continue
  done
  cp server.policy+ server.policy
  rm -f server.policy+
 fi
}

# start websphere server
start_was51()
{
  if [ -x $WAS51_HOME/bin/startServer.sh ];then
    echo "Starting WAS 5.1..."
   if [ "$WAS51_IS_SECURE" != "false" ];then
     sslfile=/tmp/sslfile-$$
     echo "$SSL_PASSWORD" > $sslfile
     $WAS51_HOME/bin/startServer.sh $WAS51_INSTANCE < $sslfile
     rm -f $sslfile
   else
    $WAS51_HOME/bin/startServer.sh $WAS51_INSTANCE
   fi
  else
    echo "WebSphere 5.1 image ($WAS51_HOME) has problem"
    exit 0
  fi
  echo "WebSphere 5.1 started."
}

# stop websphere 
stop_was51()
{
 echo "Stopping WAS 5.1 ..."
 $WAS51_HOME/bin/stopServer.sh $WAS51_INSTANCE
}

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#${AS70_CONFIG_BASE}#g" \
      -e "s#CONTAINER_CERTDB_PREFIX##g" \
      -e "s#WEB_CONTAINER#IBM5.1#g" \
      -e "s#BASEDIR/PRODUCT_DIR/config#${CONFIG_DIR}#g" \
      -e "s#SUNAPPSERVER_INSTANCE_DIR_TAG#${WAS51_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

}

doDeploy()
{

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

  echo "\$AdminApp install $PKGDIR/$warfile {-contextroot $CURRENT_DEPLOY_URI -usedefaultbindings -nopreCompileJSPs -distributeApp -nouseMetaDataFromBinary -node $WAS51_NODE -cell $WAS51_CELL -server $WAS51_INSTANCE -nodeployejb -appname $DEPLOY_WARPREFIX -createMBeansForResources -noreloadEnabled -reloadInterval 0 -nodeployws} " > /tmp/deploy.jacl
  echo "\$AdminConfig save" >> /tmp/deploy.jacl

  $WAS51_HOME/bin/wsadmin.sh -f /tmp/deploy.jacl

  if [ $? -eq 0 ];then
    echo "Successfully deployed $CURRENT_DEPLOY_URI"
  else
    echo "Failed deploying $CURRENT_DEPLOY_URI"
  fi
  rm -f /tmp/deploy.jacl
}

# 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

    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
}


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

# was 5.1 specific undeploy 
 deploy_tag=`echo $CURRENT_DEPLOY_URI |nawk -F/ '{print $NF}'`
 echo "\$AdminApp uninstall $deploy_tag {-node $WAS51_NODE -cell $WAS51_CELL -server $WAS51_INSTANCE}" > /tmp/undeploy.jacl
 echo "\$AdminConfig save" >> /tmp/undeploy.jacl

 $WAS51_HOME/bin/wsadmin.sh -f /tmp/undeploy.jacl
 rm -f /tmp/undeploy.jacl

}

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 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 with container config
		deploy_all
                configureWAS51
		;;
        2)      # console only
                deploy_it 0
                deploy_it 2
                configureWAS51
		;;
	4)	# sdk only with container config
                configureWAS51
		tagSwap
		;;
        5)      # federation only
                deploy_it 3
		;;
        6)      # server only
                deploy_it 1
                deploy_it 3
		;;
	7)	# sdk only with container config
                configureWAS51
		tagSwap
		;;
	11)	# unconfig FULL with container config
		undeploy_all
                unconfigureWAS51
		cleanLogConfig
		;;
        12)     # uninstall console only
                undeploy_it 0
                undeploy_it 2
		unconfigureWAS51
		;;
	14)	# unconfig sdk only with container config
                unconfigureWAS51
		;;
        15)     # uninstall federation
                undeploy_it 3
		;;
        16)     # uninstall server
                undeploy_it 3
                undeploy_it 1
		unconfigureWAS51
		;;
	17)	# unconfig container config
                unconfigureWAS51
		;;
	21*)	# reconfig Access Manager FULL with container config
		undeploy_all
		deploy_all
                unconfigureWAS51; sleep 5
                configureWAS51
		;;
        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"
                ;;
	31*)	# reconfig Access Manager SDK only with container config
                unconfigureWAS51; sleep 5
                configureWAS51
		;;
	*)	echo "Unsupported DEPLOY_LEVEL value" 
		exit 0 ;;
esac



