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

# source the silent install file. The assumption is that this file
# has been created prior to each script sourcing this utils script


# Initialization

OSTYPE=`/bin/uname -s`

CP=/bin/cp
SED=/bin/sed
awk=/bin/awk
LS=/bin/ls
RM=/bin/rm
NETSTAT=/bin/netstat
PATH=/bin:/usr/bin:/sbin:/usr/sbin
CAT=/usr/bin/cat
CP="/bin/cp -p"
gettext=/bin/gettext
OPEN='('
CLOSE=')'
OMIT='\c'
MKDIR=/bin/mkdir
#umask ${DEF_UMASK}
GREP=/bin/grep
EGREP=/bin/egrep

if [ "$OSTYPE" = "Linux" ]
then
	# nawk = awk on Linux
	alias nawk=/bin/awk
	ECHO="/bin/echo -e"
	GETENT=/usr/bin/getent
	PING="/bin/ping -c 1"
	MA_PKGNAME=sun-identity-mobileaccess
else
	alias nawk=/bin/nawk
	ECHO=/bin/echo
	GETENT=/bin/getent
	PING=/usr/sbin/ping
	MA_PKGNAME=SUNWamma

fi

# Source the silent file and then create all common variables needed by other 
# scripts
if [ ! "$IS_SILENT_INSTALL_FILE" = "" ]; then
    if [ `echo "$IS_SILENT_INSTALL_FILE" | cut -b1` != "/" ]; then
	IS_SILENT_INSTALL_FILE=`pwd`/$IS_SILENT_INSTALL_FILE
	export IS_SILENT_INSTALL_FILE
    fi
    if [ -f $IS_SILENT_INSTALL_FILE ]; then
	# only need to print warning the first time through
	if [ X$1 = X ]; then
	  $ECHO "Reading silent install file: $IS_SILENT_INSTALL_FILE"

	fi
        . $IS_SILENT_INSTALL_FILE

        if [ $DEPLOY_LEVEL -lt 10 -a $DEPLOY_LEVEL -ne 7 ]; then
          # verify that customer has removed the temporary settings
          if [ "X$SERVER_HOST" = "X" ] || [ "X$SERVER_PORT" = "X" ] || [ "X$DS_HOST" = "X" ] || [ "X$ADMINPASSWD" = "X" ] || [ "X$NEW_OWNER" = "X" ] || [ "X$NEW_GROUP" = "X" ] || [ "X$COOKIE_DOMAIN" = "X" ] || [ "X$ROOT_SUFFIX" = "X" ]; then
            $ECHO "Warning: Undefined variables exist in your silent file."
            $ECHO "Please verify these values have been set:" 
            $ECHO "   SERVER_NAME=$SERVER_NAME"
            $ECHO "   SERVER_HOST=$SERVER_HOST"
            $ECHO "   SERVER_PORT=$SERVER_PORT"
            $ECHO "   ADMIN_PORT=$ADMIN_PORT"
            $ECHO "   DS_HOST=$DS_HOST"
            $ECHO "   DS_DIRMGRPASSWD=<hidden>"
            $ECHO "   ROOT_SUFFIX=$ROOT_SUFFIX"
            $ECHO "   ADMINPASSWD=<hidden>"
            $ECHO "   AMLDAPUSERPASSWD=<hidden>"
            $ECHO "   COOKIE_DOMAIN=$COOKIE_DOMAIN"
            $ECHO "   AM_ENC_PWD=$AM_ENC_PWD"
            $ECHO "   NEW_OWNER=$NEW_OWNER"
            $ECHO "   NEW_GROUP=$NEW_GROUP"
            $ECHO "   WEB_CONTAINER=$WEB_CONTAINER"
            $ECHO "   SSL_PASSWORD=<hidden>"
          fi
        fi
    else
     	eval $ECHO "`$gettext 'amutils error: Silent file not found!'`"
        exit 1
    fi
else
    # Someone other than the installer might be calling this script.
    if [ "$INSTALL_FILE_NOT_REQUIRED" != "true" ]; then
     	eval $ECHO "`$gettext 'amutils error: Silent file not found!'`"
	exit 1
    fi
fi
##############################################################
#
# line manipulation routines
#


replace_line() {
  file=$1
  match=$2
  new=$3

  if [ ! -f $file-orig-$$ ]; then
     if [ -f $file ]; then
        $CP $file $file-orig-$$
     fi
  fi

  sed -e "
/$match/ {
c\\
$new
}" $file > $file-tmp
cp $file-tmp $file
rm -f $file-tmp
}

replace_line_by_number() {
  file=$1
  line=$2
  new=$3

  if [ ! -f $file-orig-$$ ]; then 
     if [ -f $file ]; then
        $CP $file $file-orig-$$
     fi
  fi

  sed -e "
$line {
c\\
$new
}" $file > $file-tmp
cp $file-tmp $file
rm -f $file-tmp
}

cat_line() {
  file=$1
  new=$2

  if [ ! -f $file-orig-$$ ]; then
      if [ -f $file ]; then
        $CP $file $file-orig-$$
      fi
  fi

  $ECHO "$new" >> $file
}

insert_line() {
  file=$1
  match=$2
  new=$3

  if [ ! -f $file-orig-$$ ]; then
     if [ -f $file ]; then
        $CP $file $file-orig-$$
     fi
  fi

  sed -e "
/$match/ {
i\\
$new
}" $file > $file-tmp
cp $file-tmp $file
rm -f $file-tmp
}

insert_line_by_number() {
  file=$1
  line=$2
  new=$3

  if [ ! -f $file-orig-$$ ]; then
     if [ -f $file ]; then
        $CP $file $file-orig-$$
     fi
  fi

  sed -e "
$line {
i\\
$new
}" $file > $file-tmp
cp $file-tmp $file
rm -f $file-tmp
}

delete_line() {
  file=$1
  match=$2

  if [ ! -f $file-orig-$$ ]; then
     if [ -f $file ]; then
        $CP $file $file-orig-$$
     fi
  fi

  sed -e "
/$match/ {
d
}" $file > $file-tmp
cp $file-tmp $file
rm -f $file-tmp
}

append_line() {
  file=$1
  match=$2
  new=$3

  if [ ! -f $file-orig-$$ ]; then
     if [ -f $file ]; then
        $CP $file $file-orig-$$
     fi
  fi

  sed -e "
/$match/ {
a\\
$new
}" $file > $file-tmp
cp $file-tmp $file
rm -f $file-tmp
}

append_line_by_number() {
  file=$1
  line=$2
  new=$3

  if [ ! -f $file-orig-$$ ]; then
     if [ -f $file ]; then
        $CP $file $file-orig-$$
     fi
  fi

  sed -e "
$line {
a\\
$new
}" $file > $file-tmp
cp $file-tmp $file
rm -f $file-tmp
}

add_to_end() {
  file=$1
  new=$2

  if [ ! -f $file-orig-$$ ]; then
     if [ -f $file ]; then
        $CP $file $file-orig-$$
     else 
        touch $file
    fi
  fi

length=`cat $file | wc -l`
if [ $length -eq 0 ] ; then
    $ECHO $new > $file
else 
  sed -e "
$ {
a\\
$new
}" $file > $file-tmp

  cp $file-tmp $file
  rm -f $file-tmp
fi

}

lastlineinblock() {
  file=$1
  match1=$2
  match2=$3
  pattern=$4

#  if [ ! -f $file-orig-$$ ]; then
#     if [ -f $file ]; then
#        $CP $file $file-orig-$$
#     fi
#  fi

  sed -e "
/$match1/,/$match2/ {
/$pattern/c\\
xxx$pattern
}" $file > $file-tmp
LAST_LINE_NO=`grep -n "xxx$pattern" $file-tmp | tail -1 | awk ' BEGIN { FS=":" } {
	print $1
}'`
  rm -f $file-tmp
}


find_enabled_disabled() {
  file=$1
  match1=$2
  match2=$3
  pattern=$4

#  if [ ! -f $file-orig-$$ ]; then
#     if [ -f $file ]; then
#        $CP $file $file-orig-$$
#     fi
#  fi

  sed -e "
/$match1/,/$match2/ {
/$pattern/c\\
xxx$pattern
}" $file > $file-tmp
isenabled=`grep "xxx$pattern" $file-tmp | awk ' {
    print $2
}'`
  LINE_EXISTS="false"
  if [ "$isenabled" != "" ]; then
    # required entry exists.
    LINE_EXISTS="true"
  fi
  rm -f $file-tmp
}


##############################################################
#
# find directory where java is installed - NOT USED CURRENTLY
#

get_java_dir()
{
basedir=`pkginfo -i -l SUNWj3dev 2>/dev/null | awk '/BASEDIR/ { print $2 }'`
if [ "$basedir" = "" ]; then
   basedir="unknown"
fi

if [ "$basedir" = "unknown" ]; then
   if [ "$JDK_BASE_DIR" = "" ]; then
        $ECHO "`$gettext 'Web server Java runtime will be used.'`"
        JAVA_HOME="$WS61_HOME/bin/https/jdk"
   else
        JAVA_HOME=$JDK_BASE_DIR
   fi
else
   if [ -d $basedir/j2se -a -x $basedir/j2se/jre/bin/java ];then
   	JAVA_HOME=$basedir/j2se
   else
   	JAVA_HOME=$basedir/java
   fi
fi
}

##############################################################
#
# Replace character with a specified new character (or string)
#    This will replace the character everywhere it appears
#    in the string.
#    (useful for cleaning up strings before calling SED)
# $1 = original string
# $2 = character to replace
# $3 = new character or string
#
replaceCharacter() {
    NEWSTR=`echo "$1" | awk -F"$2" '{
        result = ""
        for (i = 1; i < NF; i=i+1) { result = result $i newch }
        result =  result $NF
        print result
    }' newch=$3`
}

##############################################################
#
# Remove space and tab, and replace comma with char passed in
# $1 = dn
# $2 = new char
#

NormalizeDNandReplaceComma() {

    NMDN=`echo "$1" | awk '{

        dn = $0
        result = ""
        size = split(dn, rdns, ",")
        for(i=1; i<size+1; i++) {
            if (i>1) result = result newch
            rdn = rdns[i]
            size2 = split(rdn, attrs, "=")
            for(j=1; j<size2+1; j++) {
                if (j>1) result = result  "="
                str = attrs[j]
                strlen = length(str)
                start = 1
                end = strlen
                for (k=1; k<strlen+1; k++) {
                    ch = substr(str, k, 1);
                    if (ch != " " && ch != "\t") {
                        start = k
                        break
                    }
                }
                for(l=strlen; l>0; l--) {
                    ch = substr(str, l, 1);
                    if (ch != " " && ch != "\t") {
                        end = l
                        break
                    }
                }
                result = result substr(str, start, end-start+1)
            }
        }
        print result

    }' newch=$2`

export NMDN
}

#
# remove all clear test passwords from the package's pkginfo
#
delete_cleartext_password() {

 pkginfo $PKG_NAME > /dev/null 2>&1
 if [ $? -eq 0 ]; then
    # has $PKG_NAME installed
    PKGINFO=/var/sadm/pkg/$PKG_NAME/pkginfo

    if [ -f "$PKGINFO" ]; then
       sed -e "s/\(ADMINPASSWD.*\)=..*$/\1=/" \
           -e "s/\(DIRMGRPASSWD.*\)=..*$/\1=/" \
       $PKGINFO > $PKGINFO+
       if [ $? = 0 ]
       then
          mv $PKGINFO+ $PKGINFO
       fi
    fi
 fi

}
install_user_permissions () {
    if [ -f $PKGDIR/console.war ]; then
        chown $NEW_OWNER:$NEW_GROUP $PKGDIR/console.war > /dev/null 2>&1
        chmod 400 $PKGDIR/console.war > /dev/null 2>&1
    fi
}

###############################################
# check local box environment
#
check_env()
{
 box_type=`/bin/uname -p`
 os_ver=`/bin/uname -r | $SED -e "s#5.##" | $SED -e "s#.[1-9]##"`
 os_type=`/bin/uname -s`
if [ $os_type = "SunOS" ];then
 if [ $box_type = "sparc" -o $box_type = "i?86" ];then
  if [ $os_ver -gt 7 ];then
        continue
  else
        $ECHO "`$gettext 'Unsupported Solaris version'`"
        exit 1
  fi
 fi
elif [ $os_type = "Linux" ];then
 continue
else
 $ECHO "`$gettext 'Unsupported OS'`"
 exit 1
fi
}

###############################################
#
# we run on 5.8 and later, up to 5.10 for now
#

check_os()
{
    os=`/bin/uname -s`
    release=`/bin/uname -r`

    old_ifs=$IFS
    IFS=.
    set $release
    IFS=$old_ifs

    major=$1
    minor=$2
    patch=$3

    if [ "$os" = "SunOS" ]
    then
       if [ $major -ne 5 -o $minor -lt 8 ]
       then
          $ECHO "`$gettext 'Sorry, you need to be running SunOS 5.8 or better.'`"
          exit 2
       fi
    elif [ "$os" = "Linux" ]
    then
       if [ $major -ne 2 -o $minor -lt 4 ]
       then
          $ECHO "`$gettext 'Sorry, you need to be running Linux kernel 2.4 or better.'`"
          exit 2
       fi
    else
       $ECHO "`$gettext 'Sorry, you need to be running at least SunOS 5.8 or Linux kernel 2.4'`"
       exit 2
    fi
 
}

###############################################
#
# test for root user
#

check_root_user() {
  if test `id | /usr/bin/awk '{print $1}'` != "uid=0(root)"
  then
    eval $ECHO "`$gettext 'You must be root user to run $0.'`"
    exit 1
  fi
  create_safeword_config_dir
}


###################################################################
#  Function - Set Path of
#  JSS, NSS, NSPR, JSS_JAR, JAVA_DIR, JAXP_JAR and LD_LIBRARY_PATH
#
set_path_for_config() {
	REQ_FILES="SUNWjss SUNWtls SUNWpr SUNWjaxp"

	if [ "$OSTYPE" = "Linux" ]
	then
		# These RPMs are not made relocatable on Linux.
		SUNWjaxp_BASE_DIR=/
		JSSHOME=/
		NSSHOME=/
		NSPRHOME=/
		REL_JSS_PATH=opt/sun/private/lib
		REL_JSS_JAR_PATH=opt/sun/private/share/lib
		REL_NSS_PATH=opt/sun/private/lib
		REL_NSPR_PATH=opt/sun/private/lib
	elif [ "$OSTYPE" = "SunOS" ]; then
		NO_FILE=0
		for file in $REQ_FILES; do
			is_pkg_installed $file
			if [ $? -eq 1 ]; then
				$ECHO "Required package not found: $file !"
				NO_FILE=1
			fi
	        done
		if [ $NO_FILE = 1 ]; then
			exit 1
		fi

		JSSHOME=`pkginfo -i -l SUNWjss 2>&1 | awk '/BASEDIR/ { print $2 }'`
		NSSHOME=`pkginfo -i -l SUNWtls 2>&1 | awk '/BASEDIR/ { print $2 }'`
		NSPRHOME=`pkginfo -i -l SUNWpr 2>&1 | awk '/BASEDIR/ { print $2 }'`
		SUNWjaxp_BASE_DIR=`pkginfo -i -l SUNWjaxp 2>&1 | awk '/BASEDIR/ { print $2 }'`
		REL_JSS_PATH=usr/lib/mps/secv1
		REL_JSS_JAR_PATH=usr/share/lib/mps/secv1
		REL_NSS_PATH=usr/lib/mps/secv1
		REL_NSPR_PATH=usr/lib/mps/secv1
	fi

    if [ "$JSSHOME" = "/" ]; then
        JSS_PATH=/${REL_JSS_PATH}
        JSS_JAR_PATH=/${REL_JSS_JAR_PATH}
    else
        JSS_PATH=${JSSHOME}/${REL_JSS_PATH}
        JSS_JAR_PATH=${JSSHOME}/${REL_JSS_JAR_PATH}
    fi
    
    if [ "$NSSHOME" = "/" ]; then
        NSS_PATH=/${REL_NSS_PATH}
    else
        NSS_PATH=${NSSHOME}/${REL_NSS_PATH}
    fi
    
    if [ "$NSPRHOME" = "/" ]; then
        NSPR_PATH=/${REL_NSPR_PATH}
    else
        NSPR_PATH=${NSPRHOME}/${REL_NSPR_PATH}
    fi
    
    if [ "$SUNWjaxp_BASE_DIR" = "/" ]; then
		JAXP_JAR_PATH="/usr/share/lib"
    else
		JAXP_JAR_PATH="${SUNWjaxp_BASE_DIR}/usr/share/lib"
    fi
    
	# LD_LIBRARY_PATH
	if [ "$OSTYPE" = "Linux" ]
	then
		# Why is the native_threads dir needed in LD_LIBRARY_PATH on Linux? No idea. Seems like a JDK bug on Linux.
		LD_LIBRARY_PATH=$JSS_PATH:$NSS_PATH:$NSPR_PATH:${PKGDIR}/lib:${PKGDIR}/ldaplib/ldapsdk:$JAVA_HOME/jre/lib/i386/native_threads
	else
		LD_LIBRARY_PATH=$JSS_PATH:$NSS_PATH:$NSPR_PATH:${PKGDIR}/lib:${PKGDIR}/ldaplib/ldapsdk
	fi
        export LD_LIBRARY_PATH
	#echo "LD_LIBRARY_PATH is --- $LD_LIBRARY_PATH"
    
	# CLASSPATH
	CLASSPATH=${LOCALE_DIR}:${CONFIG_DIR}:${PKGDIR}/lib:${PKGDIR}/lib/am_services.jar:${PKGDIR}/lib/ldapjdk.jar:$JSS_JAR_FILE:${PKGDIR}/lib/am_sdk.jar
	echo "CLASSPATH is --- $CLASSPATH"
	echo " "
	
    # check if AMConfig.properties has been configured already, if so
    # just SED it, otherwise copy it from AMConfig.properties.template
    #
    if [ "$NEW_INSTANCE" = "false" ]; then
        if [ ! -f ${CONFIG_DIR}/AMConfig.properties ]; then
            chown $NEW_OWNER:$NEW_GROUP ${CONFIG_DIR}/AMConfig.properties.template
            chmod go-rwx ${CONFIG_DIR}/AMConfig.properties.template
            $CP ${CONFIG_DIR}/AMConfig.properties.template ${CONFIG_DIR}/AMConfig.properties
            chmod 400 ${CONFIG_DIR}/AMConfig.properties 
        fi
        file=${CONFIG_DIR}/AMConfig.properties
        NEW_CONFIG_DIR=$CONFIG_DIR
	DEBUG_SUBDIR=debug
    else
        if [ ! -f ${CONFIG_DIR}/AMConfig-$INSTANCE.properties ]; then
            $CP ${CONFIG_DIR}/AMConfig.properties.template ${CONFIG_DIR}/AMConfig-$INSTANCE.properties
            chmod 400 ${CONFIG_DIR}/AMConfig-$INSTANCE.properties
        fi
        file=${CONFIG_DIR}/AMConfig-$INSTANCE.properties
        NEW_CONFIG_DIR=$CONFIG_DIR/$INSTANCE
	DEBUG_SUBDIR=debug/$INSTANCE
    fi

    
    if [ "$AM_ENC_PWD" = "" ]; then
        AM_ENC_PWD=`${JAVA_HOME}/bin/java -classpath ${CLASSPATH} com.iplanet.services.util.internal.RandomString`
    fi
    #This has to be done before encrypting any password.
    $CP $file $file+
    sed -e "s#AM_ENC_PWD#$AM_ENC_PWD#g" \
    	-e "s#IS_INSTALL_VARDIR#$IS_INSTALL_VARDIR#g" \
    	-e "s#IS_INSTALL_ETCDIR#$IS_INSTALL_ETCDIR#g" \
        -e "s#CONFIG_DIR#$NEW_CONFIG_DIR#g" \
    	-e "s#IS_PRODNAME#$PRODUCT_DIR#g" \
	-e "s#DEBUG_SUBDIR#$DEBUG_SUBDIR#g" \
    $file+ > $file
    rm -f $file+

    #These are HADB config files required for the Session Failover scripts 
    if [ -f ${CONFIG_DIR}/amProfile.conf -a -f $BASEDIR/$PRODUCT_DIR/bin/amhasetup -a -f  $BASEDIR/$PRODUCT_DIR/share/HARepo/amsessionconfig -a -f $BASEDIR/$PRODUCT_DIR/bin/amsfoconfig ]; then
        SFO_FILES="${CONFIG_DIR}/amProfile.conf $BASEDIR/$PRODUCT_DIR/bin/amhasetup  $BASEDIR/$PRODUCT_DIR/share/HARepo/amsessionconfig $BASEDIR/$PRODUCT_DIR/bin/amsfoconfig"
        for file in $SFO_FILES; do
            $CP -p $file $file+
            sed -e "s#IS_PRODNAME#$PRODUCT_DIR#g" \
                -e "s#IS_INSTALL_BASEDIR#${BASEDIR}#g" \
    	        -e "s#IS_INSTALL_ETCDIR#$IS_INSTALL_ETCDIR#g" \
                -e "s#JAVADIR#${JAVA_HOME}#g" \
            $file+ > $file
            rm -f $file+
        done
    fi
}

########################################################
#
# check if the Debug and Log directory exists and create 
# if it's missing.
#
create_debug_log_directory() {
    debugdir=$VAR_SUBDIR/debug
    logdir=$VAR_SUBDIR/logs
    if [ ! -d  $debugdir ]
    then
        $MKDIR -p $debugdir > /dev/null 2>&1
    fi
    if [ ! -d  $logdir ]
    then
        $MKDIR -p $logdir > /dev/null 2>&1
    fi
    chmod 777 $debugdir > /dev/null 2>&1
    chmod 0700 $logdir > /dev/null 2>&1
}

####################################
create_safeword_config_dir() {
    safeworddir=$VAR_SUBDIR/auth/safeword
    if [ ! -d $safeworddir ]
    then
	$MKDIR -p $safeworddir > /dev/null 2>&1
    fi
    chmod 700 $safeworddir
}

####################################
link_amconfig()
{
if [ -f $CONFIG_DIR/AMConfig.properties ] && [ ! -f ${PKGDIR}/lib/AMConfig.properties ]; then
    ln -s $CONFIG_DIR/AMConfig.properties ${PKGDIR}/lib/AMConfig.properties
fi
}


####################################
unjar_docs()
{
if [ -f ${PKGDIR}/docs/am_public_javadocs.jar ]; then
    TEMPWD=`pwd`
    cd ${PKGDIR}/docs
    ${JAVA_HOME}/bin/jar xf am_public_javadocs.jar
    cd $TEMPWD
fi
}

####################################
# Tag Swaps the Samples
tag_swap_samples()
{   
    SAMPLEDIR=${PKGDIR}/samples
    SHARELIB=${PKGDIR}/lib
    EDIT_FILES="${SAMPLEDIR}/authentication/api/Cert/Makefile ${SAMPLEDIR}/authentication/api/LDAP/Makefile ${SAMPLEDIR}/authentication/api/jcdi/Makefile ${SAMPLEDIR}/authentication/spi/jcdi/Makefile ${SAMPLEDIR}/authentication/spi/postprocess/Makefile ${SAMPLEDIR}/authentication/spi/providers/Makefile ${SAMPLEDIR}/authentication/spi/purejaas/Makefile ${SAMPLEDIR}/sso/Makefile ${SAMPLEDIR}/sso/run ${SAMPLEDIR}/admin/cli/bulk-ops/schemaAddAttributeSchemaRequests.xml ${SAMPLEDIR}/admin/cli/bulk-ops/schemaAddSubSchemaRequests.xml ${SAMPLEDIR}/liberty/sample1/idp1/WEB-INF/web.xml ${SAMPLEDIR}/liberty/sample1/sp1/WEB-INF/web.xml ${SAMPLEDIR}/liberty/sample2/idp1/WEB-INF/web.xml ${SAMPLEDIR}/liberty/sample2/sp1/WEB-INF/web.xml ${SAMPLEDIR}/liberty/sample3/idp1/WEB-INF/web.xml ${SAMPLEDIR}/liberty/sample3/idp2/WEB-INF/web.xml ${SAMPLEDIR}/liberty/sample3/sp1/WEB-INF/web.xml ${SAMPLEDIR}/liberty/sample3/sp2/WEB-INF/web.xml ${SAMPLEDIR}/logging/RunSample ${SAMPLEDIR}/logging/RunLogReader ${SAMPLEDIR}/phase2/sis-ep/bin/install_dir.var ${SAMPLEDIR}/phase2/sis-ep/src/Makefile ${SAMPLEDIR}/phase2/sis-ep/xml/amLibertyEmployeeProfile.xml ${SAMPLEDIR}/policy/Makefile ${SAMPLEDIR}/saml/client/Makefile ${SAMPLEDIR}/saml/query/Makefile ${SAMPLEDIR}/saml/sso/Makefile ${SAMPLEDIR}/saml/xmlsig/Makefile ${SAMPLEDIR}/um/Makefile ${SAMPLEDIR}/um/RunSamples ${SAMPLEDIR}/authentication/spi/genuid/Makefile ${SAMPLEDIR}/phase2/authnsvc/Makefile"

if [ "$WEB_CONTAINER" = "WL8" ]; then
	JVM_HOME=$WL8_JDK_HOME
elif [ "$WEB_CONTAINER" = "WAS5" ]; then
	JVM_HOME=$WAS5_JDK_HOME
else
	JVM_HOME=$JAVA_HOME
fi

    for file in $EDIT_FILES; do
        cp -p $file $file+
        sed -e "s#JAVADIR#${JVM_HOME}#g" \
            -e "s#IS_INSTALL_BASEDIR#${BASEDIR}#g" \
            -e "s#BASEDIR#${BASEDIR}#g" \
            -e "s#SHARELIB#${SHARELIB}#g" \
            -e "s#JSSJARPATH#${JSS_JAR_PATH}#g" \
            -e "s#JSSPATH#${JSS_SO_PATH}#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" \
            -e "s#TAG_JSS_SO_PATH#${JSS_SO_PATH}#g" \
            -e "s#TAG_JSS_JAR_PATH#${JSS_JAR_PATH}#g" \
            -e "s#TAG_NSS_SO_PATH#${NSS_SO_PATH}#g" \
            -e "s#TAG_NSPR_SO_PATH#${NSPR_SO_PATH}#g" \
        $file+ > $file
        rm -f $file+
    done
}


###############################################
#
# confirm the user Input
#
confirm_user_input() {
    echo
    echo
    echo "Please confirm if these are the correct input for installation"
    echo "If this is not correct then re-enter the inputs or modify the "
    echo "silent input file..."
    echo "******************************************"
    echo "BASEDIR=$BASEDIR"
    echo "PRODUCT_DIR=${PRODUCT_DIR}"
    echo "SERVER_HOST=${SERVER_HOST}"
    echo "SERVER_PORT=${SERVER_PORT}"
    echo "SERVER_PROTOCOL=${SERVER_PROTOCOL}"
    echo "CONSOLE_HOST=${CONSOLE_HOST}"
    echo "CONSOLE_PORT=${CONSOLE_PORT}"
    echo "CONSOLE_PROTOCOL=${CONSOLE_PROTOCOL}"
    echo "CONSOLE_REMOTE=${CONSOLE_REMOTE}"
    echo "DS_HOST=${DS_HOST}"
    echo "DS_PORT=${DS_PORT}"
    echo "DS_DIRMGRDN=${DS_DIRMGRDN}"
    echo "ROOT_SUFFIX=${ROOT_SUFFIX}"
    echo "SERVER_DEPLOY_URI=${SERVER_DEPLOY_URI}"
    echo "CONSOLE_DEPLOY_URI=${CONSOLE_DEPLOY_URI}"
    echo "PASSWORD_DEPLOY_URI=${PASSWORD_DEPLOY_URI}"
    echo "COMMON_DEPLOY_URI=${COMMON_DEPLOY_URI}"
    echo "DIRECTORY_MODE=${DIRECTORY_MODE}"
    echo "JAVA_HOME=${JAVA_HOME}"
    echo "WEB_CONTAINER=${WEB_CONTAINER}"

    case $DEPLOY_LEVEL in
  1)
      echo Full Install
      ;; 
  1)
      echo Server Only Install
      ;; 
  11)
      echo Full Uninstall
      ;; 
  16)
      echo Server Only Uninstall
      ;; 
  3)
      echo SDK Only
      ;; 
  4)
      echo SDK Only Container Config
      ;; 
  2)
      echo Console Only
      ;; 
  5)
      echo Federation Only
      ;; 
  14)
      echo Uninstall SDK Unconfig Container
      ;;
  *) echo error no such config option
      exit 0
      ;;
  esac
    
    echo "******************************************"
    echo
    echo "Are these correct inputs ?[y]/n" 
    read ans
    if [ "$ans" = "no" ] || [ "$ans" = "n" ]; then
        echo "exiting..."
        exit
    fi      
}

###############################################
#
# Check for spaces
#
check_for_spaces() {

	str=`$ECHO "$1" | grep " "`
	if [ $? -eq 0 ]; then
		return 1
	else
		return 0
	fi
}


##############################################################################
#
#
delete_line_by_number() {
   file=$1
   line=$2
   if [ ! -f $file-orig-$$ ]; then
     if [ -f $file ]; then
        $CP $file $file-orig-$$
     fi
   fi

   sed -e "
$line {
d
}" $file > $file-tmp
cp $file-tmp $file
rm -f $file-tmp
}

##############################################################################
#
#
yesno() {
    ok="no"
	
    question=$1
    default=$2
	
    valids="ynYN"
    while [ "$ok" = "no" ]
    do
	if [ "$default" = "y" ] || [ "$default" = "Y" ]; then
	    $ECHO	
	    $ECHO "$question [y]/n: ${OMIT}"
	    default="y"
	elif [ "$default" = "n" ] || [ "$default" = "N" ]; then
	    $ECHO
	    $ECHO "$question y/[n]: ${OMIT}"
	    default="n"
	else 
	    $ECHO
	    $ECHO "$question y/n: ${OMIT}"
	    default=""
	fi
	read ans
	
	if [ "$ans" = "" ]; then
	    if [ "$default" != "" ]; then
		ans=$default
	    fi
	fi
	
	if [ "$ans" = "y" ] || [ "$ans" = "Y" ] || [ "$ans" = "N" ] || [ "$ans" = "n" ]; then
	    ok="yes"
	fi           
		
	if [ "$ok" = "no" ]; then
	    $ECHO
	    $ECHO "`$gettext 'Invalid response!'`"          
	    $ECHO
	fi
    done    
	
    # make sure we have a std response so client doesn't need to check
    if [ "$ans" = "`$gettext 'Y'`" ]; then
	ans="y"
    elif [ "$ans" = "`$gettext 'N'`" ]; then
	ans="n"
    fi
}


##############################################################################
#
#
check_file_for_write() {
    file=$1
    verbose=$2

    if [ "$verbose" = "" ]; then
        verbose=1
    fi
    if [ ! -f $file ]; then
        if [ "$verbose" = "1" ]; then 
            $ECHO "File not found: " $file
        fi
        return 100
    fi

    touch $file

    if [ $? -eq 1 ]; then
        return 100
    fi  
}

###########################################################################################
# substitute_token_in_line
# This function is useful in replacing tokens of the type token="value" in any line of a given file
# (especially useful in replacing values for certain tokens in XML files
# match     - matching pattern which identifies the line where the token is to be replaced
# token     - token name fully spelt
# newvalue  - new value to be used
# mode      - 0 is replace
#             1 is prepend
#             2 is append
# delimiter - delimiter to be used while appending or prepending b/w the old and new values
###########################################################################################
substitute_token_in_line(){
    file=$1
    match=$2
    token=$3
    newvalue=$4
    mode=$5
    delimiter=$6

    #step1: grep for classpath suffix in server.xml
    orig_line=`grep $match $file`

    #step2: Get the number of tokens in the line
    number_of_tokens=`echo $orig_line | nawk ' { print NF } '`

    #step3: Replace the value for the token
    count=1
    newline=""
    while [ $count -le $number_of_tokens ]
    do
        currentToken=`echo $orig_line | cut -f$count -d " "`
        desiredTokenStr=`echo $currentToken | cut -f$count -d " " | grep $token`
        if [ "$desiredTokenStr" != "" ]; then
            desiredTokenValue=`echo $desiredTokenStr | nawk ' BEGIN { FS="=" } { print $2 } ' | cut -f2 -d "\""`
            left_over_str=`echo $desiredTokenStr | nawk ' BEGIN { FS="=" } { print $2 } ' | cut -f3 -d "\""`

            if [ "$mode" -eq "0" ] || [ "`echo $desiredTokenValue | wc -m`" -eq "1" ]; then 
                desiredTokenValue="\"$newvalue\""
            elif [ "$mode" -eq "1" ]; then
                desiredTokenValue="\"$newvalue$delimiter$desiredTokenValue\""
            else
                desiredTokenValue="\"$desiredTokenValue$delimiter$newvalue\""
            fi

            new_token_str="$token=$desiredTokenValue$left_over_str"
            newline="$newline $new_token_str"
        else
            newline="$newline $currentToken"
       fi
       count=`expr $count + 1`
    done
    replace_line "$file" $match "$newline"
}


###############################################
# This function changes the ownership of all
# the installed files to the user and group
# indicated.
change_ownership()
{
  if [ -d $BASEDIR/$PRODUCT_DIR ]; then
    chown -R $NEW_OWNER:$NEW_GROUP $BASEDIR/$PRODUCT_DIR
  fi
  if [ -d $ETC_SUBDIR ]; then
    chown -R $NEW_OWNER:$NEW_GROUP $ETC_SUBDIR
  fi
  if [ -d $VAR_SUBDIR ]; then
    chown -R $NEW_OWNER:$NEW_GROUP $VAR_SUBDIR
  fi
}

###############################################
# This function creates temporary password files
#
create_password_files()
{
if [ "$DS_DIRMGRPASSWD" != "" ] && [ "$FILE_DS_DIRMGRPASSWD" != "" ]; then
    if [ -f $FILE_DS_DIRMGRPASSWD ]; then  
        $RM $FILE_DS_DIRMGRPASSWD
    fi
    $ECHO $DS_DIRMGRPASSWD > $FILE_DS_DIRMGRPASSWD
    chmod 700 $FILE_DS_DIRMGRPASSWD
fi

if [ "$ADMINPASSWD" != "" ] && [ "$FILE_ADMINPASSWD" != "" ]; then
    if [ -f $FILE_ADMINPASSWD ]; then  
        $RM $FILE_ADMINPASSWD
    fi
    $ECHO $ADMINPASSWD > $FILE_ADMINPASSWD
    chmod 700 $FILE_ADMINPASSWD
fi

if [ "$AMLDAPUSERPASSWD" != "" ] && [ "$FILE_AMLDAPUSERPASSWD" != "" ]; then
    if [ -f $FILE_AMLDAPUSERPASSWD ]; then  
        $RM $FILE_AMLDAPUSERPASSWD
    fi
    $ECHO $AMLDAPUSERPASSWD > $FILE_AMLDAPUSERPASSWD
    chmod 700 $FILE_AMLDAPUSERPASSWD
fi

if [ "$AS70_ADMINPASSWD" != "" ] && [ "$FILE_AS70_ADMINPASSWD" != "" ]; then    
    if [ -f $FILE_AS70_ADMINPASSWD ]; then  
        $RM $FILE_AS70_ADMINPASSWD
    fi
    
    $ECHO AS_ADMIN_PASSWORD=$AS70_ADMINPASSWD > $FILE_AS70_ADMINPASSWD
    chmod 700 $FILE_AS70_ADMINPASSWD
fi

if [ "$AS81_ADMINPASSWD" != "" ] && [ "$FILE_AS81_ADMINPASSWD" != "" ]; then    
    if [ -f $FILE_AS81_ADMINPASSWD ]; then  
        $RM $FILE_AS81_ADMINPASSWD
    fi
    
    $ECHO AS_ADMIN_PASSWORD=$AS81_ADMINPASSWD > $FILE_AS81_ADMINPASSWD
    chmod 700 $FILE_AS81_ADMINPASSWD
fi
}


###############################################
# This function delete temporary password files
#
delete_password_files()
{
if [ -f $FILE_DS_DIRMGRPASSWD ]; then  
    $RM $FILE_DS_DIRMGRPASSWD
fi

if [ -f $FILE_ADMINPASSWD ]; then  
    $RM $FILE_ADMINPASSWD
fi

if [ -f $FILE_AMLDAPUSERPASSWD ]; then  
    $RM $FILE_AMLDAPUSERPASSWD
fi

if [ -f $FILE_AS70_ADMINPASSWD ]; then  
    $RM $FILE_AS70_ADMINPASSWD
fi
if [ -f $FILE_AS81_ADMINPASSWD ]; then  
    $RM $FILE_AS81_ADMINPASSWD
fi
}


#############################################
#### Interactive script functions below. ####
#############################################

# Error Codes (Dummy Right now)
VALID=0
ERR_INVALID_DEPLOY_LEVEL=100
ERR_NEED_FULL_PATH=101
ERR_DIR_NOT_EXIST=102
ERR_INVALID_CONTAINER=103
ERR_NOT_FQDN=104
ERR_HOST_NOPING=105
ERR_INVALID_PORT=106
ERR_PORT_INUSE=107
ERR_PORT_NOTUSED=108
ERR_INVALID_PROTOCOL=109
ERR_PASSWD_IS_BLANK=110
ERR_PASSWD_WITH_SPACES=111
ERR_PASSWD_TOO_SHORT=112
ERR_INVALID_DS_MODE=113
ERR_DS_NOT_REACHABLE=114
ERR_PASSWD_CANTBE_SAME=115
ERR_URI_FIRST_CHAR=116
ERR_INVALID_COOKIE_DOMAIN=117
ERR_INVALID_JAVA_HOME=118
ERR_INVALID_USER=119
ERR_INVALID_GROUP=120


##################################################################
#
# This function sets the given variable in the silent install file
# Required: $1=Variable Name
# Optional: $2=New Value
# If $2 is provided it is used as the new value
# else the function assumes that the current value of the
# variable is to be used and sets it in the environment also.
setdeployvar()
{
	VARNAME=$1
	NEWVAL=$2

	# Fetch the new value from the variable itself
	if [ "$NEWVAL" = "" ]; then
		eval NEWVAL=$`echo $VARNAME`
	else
		# Set new value in the environment
		eval "$VARNAME"="$NEWVAL"
	fi

	# Need to insert quotes around values with whitespace or = signs
	$ECHO "$NEWVAL" | grep "[ 	=]" >/dev/null 2>&1
	if [ $? -eq 0 ]; then
		replace_line $IS_SILENT_INSTALL_FILE "^${VARNAME}=" "${VARNAME}=\"${NEWVAL}\""
	else
		replace_line $IS_SILENT_INSTALL_FILE "^${VARNAME}=" "${VARNAME}=${NEWVAL}"
	fi
}

####################################################################
#
# Validates the hostname to be a FQDN and the host to be accessible
validate_host()
{
	$ECHO $1 | grep "\." >/dev/null 2>&1
        [ $? -ne 0 ] && return $ERR_NOT_FQDN

	$PING $1 >/dev/null 2>&1
	[ $? -ne 0 ] && return $ERR_HOST_NOPING

	return $VALID
}

################################################################
#
# This function asks the user for a fully qualified domain name
# and validates it.
get_host() {
	msg=$1
	hostnamedefault=$2

	if [ "$hostnamedefault" = "" ]; then
	hostnamedefault=`hostname`.`domainname`
	fi
    	
	while true
	do
		$ECHO
		$ECHO "`$gettext 'What is the fully qualified domain name of the machine'`"
		$ECHO "$msg: [$hostnamedefault] ${OMIT}"
		read USERHOST

		if [ "$USERHOST" = "" ]; then
		    USERHOST=$hostnamedefault
		fi

		validate_host $USERHOST
		case $? in
		$ERR_NOT_FQDN)
			$ECHO "`$gettext 'Please specify a fully qualified domain name'`"
			continue
			;;
		$ERR_HOST_NOPING)
			$ECHO
			msg=`$gettext "WARNING: $USERHOST is invalid or not responding."`
			$ECHO "$msg"
			yesno "`$gettext 'Are you sure you still want to use this as the host name?'`" "`$gettext 'n'`"
			if [ "$ans" = "`$gettext 'y'`" ]; then
				break
			fi
			continue
			;;
		$VALID)
			ipaddr=`$GETENT hosts $USERHOST`
			if [ "$ipaddr" != "" ]; then
				set $ipaddr
				IPADDRESS=$1
			else
				IPADDRESS="unknown"
			fi
			break
			;;
		esac
    done
    RETURN_VALUE=$USERHOST
}

##########################
#
# Validates a port number
validate_port()
{
	MINPORT=1
	MAXPORT=65535
	$ECHO "$1" | grep '^[0-9]*$' >/dev/null 2>&1
	[ $? -ne 0 ] && return $ERR_INVALID_PORT
	[ "$1" -lt "$MINPORT" ] && return $ERR_INVALID_PORT
	[ "$1" -gt "$MAXPORT" ] && return $ERR_INVALID_PORT
	return $VALID
}

########################################
#
# Validates a port to be NOT in use
# Required: $1=host name $2=port number
validate_new_port()
{
	check_port $1 $2
	[ $? -ne 0 ] && return $ERR_PORT_INUSE
	return $VALID
}

########################################
#
# Validates a port to be IN use
# Required: $1=host name $2=port number
validate_existing_port()
{
        check_port $1 $2
        [ $? -eq 0 ] && return $ERR_PORT_NOTUSED
        return $VALID
}

################################################
#
# This function asks the user for a port number
get_port() {
	msg=$1
	defaultport=$2
	PORT=0

	while true
	do
		$ECHO
		$ECHO "`$gettext 'What is the port number'` $msg: [$defaultport] $OMIT"
		read PORT
		if [ "$PORT" = "" ]; then
			PORT="$defaultport"
		fi

		validate_port $PORT
		if [ $? -ne $VALID ]; then
			msg=`$gettext "Invalid Port!! Please enter a port number between $MINPORT and $MAXPORT"`
			$ECHO "$msg"
			PORT=0
			continue
		fi
		break
	done
	RETURN_VALUE=$PORT
}

###################################################################################
#
# This function checks if the port provided is in use or not on the host provided.
# Return value 0 = port NOT in use
#              not 0 = port Access Manager in use
check_port()
{
	host=$1
	port=$2

	output=`telnet $host $port 2>&1 <<EOF
quit
EOF
`
	$ECHO $output | $EGREP "Connection refused|Unknown host|Name or service not known" >/dev/null 2>&1
	return $?
}

##############################################
#
# Validates protocol name to be http or https
validate_protocol()
{
	[ "$1" != "http" -a "$1" != "https" ] && return $ERR_INVALID_PROTOCOL
	return $VALID
}

####################################################
#
# This function asks the protocol name (http/https)
get_protocol() {

    msg=$1
    defaultproto=$2
           
    while true
    do
	$ECHO
	$ECHO "`$gettext 'What is the protocol'` $msg (http/https): [$defaultproto] ${OMIT}"
	read USERPROTOCOL
	if [ "$USERPROTOCOL" = "" ]; then
		USERPROTOCOL=$defaultproto
	fi
		
	validate_protocol $USERPROTOCOL
	if [ $? -ne $VALID ]; then
	    errmsg=`$gettext "WARNING: Protocol $USERPROTOCOL is invalid."`
            $ECHO "$errmsg"
            continue
        fi
    	break
    done
    RETURN_VALUE=$USERPROTOCOL
}

###################################################################
#
# Validates an existing password to be nonblank and without spaces
validate_existing_passwd()
{
	[ "$1" = "" ] && return $ERR_PASSWD_IS_BLANK
	check_for_spaces "$1"
	[ $? -eq 1 ] && return $ERR_PASSWD_WITH_SPACES
	return $VALID
}

####################################################
#
# Validates a new password to be of minimum 8 chars
validate_new_passwd()
{
        [ "$1" = "" ] && return $ERR_PASSWD_IS_BLANK
        check_for_spaces "$1"
        [ $? -eq 1 ] && return $ERR_PASSWD_WITH_SPACES
	LEN=`$ECHO "$1" | wc -m`
	[ $LEN -lt 8 ] && return $ERR_PASSWD_TOO_SHORT
        return $VALID
}

###########################################################################
#
# Function - Get a password 
# $1 - Get the type of password. Possible values are "existing" and "new".
# $2 - Which password is being asked.
# PASS_WORD - Returns the password
#
get_passwd() {

	passwordtype=$1
	context=$2
	PASS_WORD=""
	PASS_WORD1=""
	  
	if [ "$passwordtype" = "new" ]; then
		while true
		do
			$ECHO
			eval $ECHO "`$gettext 'Please enter ${context} - Password ${OPEN} 8 chars minimum ${CLOSE}: ${OMIT}'`"
			stty -echo
			read PASS_WORD
			stty echo
			$ECHO
			PASS_WORD=`$ECHO "$PASS_WORD" | sed -e 's/ *$//'`
		
			validate_new_passwd "$PASS_WORD"
			case $? in
				$ERR_PASSWD_WITH_SPACES)
					$ECHO
					$ECHO "\a`$gettext 'Password cannot contain spaces!'`"
					$ECHO
					PASS_WORD=""
					continue
					;;
		
				$ERR_PASSWD_IS_BLANK)
					$ECHO
					$ECHO "\a`$gettext 'Password cannot be blank!'`"
					$ECHO
					PASS_WORD=""
					continue
					;;

				$ERR_PASSWD_TOO_SHORT)
					$ECHO	
					$ECHO "\a`$gettext 'Password must be at least 8 characters!'`"
					$ECHO
					PASS_WORD=""
					continue
					;;
				$VALID) ;;
			esac
		
			$ECHO
			eval $ECHO "`$gettext 'Confirm Password: ${OMIT}'`"
			stty -echo
			read PASS_WORD1
			PASS_WORD1=`$ECHO "$PASS_WORD1" | sed -e 's/ *$//'`
			stty echo
			$ECHO

			if [ "$PASS_WORD" = "$PASS_WORD1" ]; then
				RETURN_VALUE=$PASS_WORD
				return
			else
				$ECHO "\a`$gettext 'Password verification failed!'`"
			fi
		done
	elif  [ "$passwordtype" = "existing" ]; then
		while true
		do
			$ECHO
			eval $ECHO "`$gettext 'Please enter ${context} password: ${OMIT}'`"
			stty -echo
			read PASS_WORD
			stty echo
			$ECHO
			PASS_WORD=`$ECHO "$PASS_WORD" | sed -e 's/ *$//'`
		
			validate_existing_passwd "$PASS_WORD"
			case $? in
			$ERR_PASSWD_WITH_SPACES)
				$ECHO
				$ECHO
				$ECHO "\a`$gettext 'Password cannot contain spaces!'`"
				PASS_WORD=""
				continue
				;;
			$ERR_PASSWD_IS_BLANK)
				$ECHO
				$ECHO "\a`$gettext 'Password cannot be blank!'`"
				PASS_WORD=""
				continue
				;;
			$VALID)
				RETURN_VALUE=$PASS_WORD
				return 
				;;
			esac
		done
	fi
}

###########################################
#
# This function validates the deploy level
validate_deploy_level()
{
	case $1 in
		1|2|3|4|5|6) return $VALID;;
		11|12|13|14|15|16) return $VALID;;
		21|26|31|32|33|35) return $VALID;;
		*) return $ERR_INVALID_DEPLOY_LEVEL;;
	esac
}

#############################################################################
#
# This function presents the Configuration choices and gets user's selection
# Sets DEPLOY_LEVEL in the silent install file
ask_deploy_level()
{
	while true
	do
		$ECHO
		$ECHO
		$ECHO "`$gettext 'Please choose the type of configuration from the following choices:'`"
		$ECHO
		$ECHO "`$gettext 'Configuration options:'`"
		$ECHO "`$gettext '1. Full Configuration'`"
		$ECHO "`$gettext '2. Console only Configuration'`"
		$ECHO "`$gettext '3. SDK only Configuration'`"
		$ECHO "`$gettext '4. SDK only with Web Container Configuration'`"
		$ECHO "`$gettext '5. Federation only Configuration'`"
		$ECHO "`$gettext '6. Server only Configuration'`"
		$ECHO
		$ECHO "`$gettext 'Undo Configuration options:'`"
		$ECHO "`$gettext '11. Undo Full Configuration'`"
		$ECHO "`$gettext '12. Undo Console only Configuration'`"
		$ECHO "`$gettext '13. Undo SDK only Configuration'`"
		$ECHO "`$gettext '14. Undo SDK only with Web Container Configuration'`"
		$ECHO "`$gettext '15. Undo Federation only Configuration'`"
		$ECHO "`$gettext '16. Undo Server only Configuration'`"
		$ECHO
		################ Commented out for the time being ###################
#		$ECHO "`$gettext 'Redo Configuration options"'`"
#		$ECHO "`$gettext '21. Redo Full Configuration'`"
#		$ECHO "`$gettext '26. Redo Server Configuration'`"
#		$ECHO "`$gettext '31. Redo SDK Configuration'`"
#		$ECHO "`$gettext '32. Redo Console Configuration'`"
#		$ECHO "`$gettext '33. Redo Console SDK Configuration'`"
#		$ECHO "`$gettext '35. Redo Liberty Configuration'`"
#		$ECHO
		####################################################################
		$ECHO "`$gettext 'Please make your selection: [1]'` $OMIT"
		read ANS
		
		case $ANS in
			"" | 1) DEPLOY_LEVEL=1;;
			*) DEPLOY_LEVEL=$ANS;;
		esac

		validate_deploy_level $DEPLOY_LEVEL
		if [ $? -eq 0 ]; then
			break
		else
			$ECHO `$gettext 'Invalid Deploy Level specified'`
			continue
		fi
	done

	setdeployvar DEPLOY_LEVEL
}

######################################################
#
# This function validates the Base Directory provided
validate_basedir()
{
	[ `$ECHO $1 | cut -b1` != "/" ] && return $ERR_NEED_FULL_PATH
	[ ! -d $1 ] && return $ERR_DIR_NOT_EXIST
	return $VALID
}

##################################################################
#
# This function asks the user to provide the Access Manager Install Directory
# Sets BASEDIR in the silent install file
ask_basedir()
{
	BASEDIR=${BASEDIR:-/opt}

	if [ "$BASEDIR" = "PLATFORM_DEFAULT" ]; then
		if [ "$OSTYPE" = "Linux" ]; then
			BASEDIR=/opt/sun
		else
			BASEDIR=/opt
		fi
	fi

	tmp_BASEDIR=$BASEDIR
	while true
	do
		$ECHO
		if [ "$DEPLOY_LEVEL" -ge 11 -a "$DEPLOY_LEVEL" -le 16 ]; then
			$ECHO "`$gettext 'Where is the Access Manager installed'` [$tmp_BASEDIR]: ${OMIT}"
		else
			$ECHO "`$gettext 'Where do you want the Access Manager to be installed'` [$tmp_BASEDIR]: ${OMIT}"
		fi
		read ANS

		if [ "$ANS" != "" ]
		then
			tmp_BASEDIR=$ANS
		fi

		validate_basedir $tmp_BASEDIR
		case $? in
			$VALID) break;;
			$ERR_NEED_FULL_PATH)
				$ECHO "`$gettext 'Directory specified is not a full path. Please specify a full path.'`"
				continue
				;;
			$ERR_DIR_NOT_EXIST)
				if [ "$DEPLOY_LEVEL" -ge 11 -a "$DEPLOY_LEVEL" -le 16 ]; then
					$ECHO `$gettext "Directory $tmp_BASEDIR does not exist. Please specify the Access Manager base directory"`
					continue
				fi
				msg=`gettext "Directory $tmp_BASEDIR does not exist. Do you want to create it? "`
				yesno "$msg" "y"

				if [ "$ans" = "`$gettext 'y'`" ]; then
					$MKDIR -p $tmp_BASEDIR
					if [ $? != 0 ]; then
						$ECHO "`$gettext 'Could not create directory '` $tmp_BASEDIR"
						continue
					else
						break
					fi
				else
					continue
				fi
				;;
		esac
	done 

	setdeployvar BASEDIR $tmp_BASEDIR
}

#####################################################
#
# Validates web container to run the Access Manager
validate_container()
{
if [ $DEPLOY_LEVEL -eq 1 ]; then
	case $1 in
		"WS6"|"AS7"|"AS8") return $VALID;;
		*) return $ERR_INVALID_CONTAINER;;
	esac
else
	case $1 in
		"WS6"|"AS7"|"AS8"|"WL8"|"WAS5") return $VALID;;
		*) return $ERR_INVALID_CONTAINER;;
	esac
fi
}

#######################################################
#
# This function asks the user to specify the container
# Sets WEB_CONTAINER in the silent install file
ask_container()
{
	case $WEB_CONTAINER in
		"WS6") default=1;;
		"AS7") default=2;;
		"AS8") default=3;;
		"WL8") default=4;;
		"WAS5") default=5;;
		*) default=1;;
	esac

	while true
	do
		$ECHO
		if [ "$DEPLOY_LEVEL" -ge 11 -a "$DEPLOY_LEVEL" -le 16 ]; then
			$ECHO "`$gettext 'Which type of Web Container is Access Manager installed in?'`"
		else
			$ECHO "`$gettext 'Which type of Web Container will Access Manager run in?'`"
		fi
		$ECHO
		$ECHO "`$gettext '1. Sun Java System Web Server 6.1'`"
		$ECHO "`$gettext '2. Sun Java System Application Server 7.0'`"
		$ECHO "`$gettext '3. Sun Java System Application Server 8.1'`"
		if [ $DEPLOY_LEVEL -ne 1 ]; then
			$ECHO "`$gettext '4. BEA WebLogic 8'`"
			$ECHO "`$gettext '5. IBM WebSphere 5'`"
		fi
		$ECHO
		$ECHO "`$gettext 'Please make your selection:'`" "[$default] $OMIT"

		read ANS
		
		case $ANS in
			"" | 1) WEB_CONTAINER=WS6;;
			2) WEB_CONTAINER=AS7;;
			3) WEB_CONTAINER=AS8;;
			4) WEB_CONTAINER=WL8;;
			5) WEB_CONTAINER=WAS5;;
			*) continue;;
		esac
		validate_container $WEB_CONTAINER
		case $? in
			$ERR_INVALID_CONTAINER)
				$ECHO `$gettext "Invalid Web Container specified!"` ;;
			$VALID)
				break ;;
		esac
	done

	determine_container_variables
	setdeployvar WEB_CONTAINER
}

####################################
#
# Validates Web Container Directory
validate_container_basedir()
{
	[ ! -d $1 ] && return $ERR_DIR_NOT_EXIST
	return $VALID
}

###################################
# Sets names of various vars based
# on the container specified.
determine_container_variables()
{
        case $WEB_CONTAINER in
                "WS6")  INSTANCE=`echo $WS61_INSTANCE | sed -e "s#https-##" -e "s/\./_/g"`
                        ;;
                "AS7")  INSTANCE=`echo $AS70_INSTANCE | sed -e "s/\./_/g"`
                        ;;
                "AS8")  INSTANCE=`echo $AS81_INSTANCE | sed -e "s/\./_/g"`
                        ;;
                "WL8")  INSTANCE=`echo $WL8_SERVER | sed -e "s/\./_/g"`
                        ;;
                "WAS5") INSTANCE=`echo $WAS51_INSTANCE | sed -e "s/\./_/g"`
                        ;;
        esac
        if [ "$NEW_INSTANCE" = "false" ]; then
            INSTANCE_DIR=""
        else
            INSTANCE_DIR=$INSTANCE
        fi
}


#############################################################################
#
# This function asks the user to specify the container's base directory
# Sets appropriate variable to the container's basedir provided in
# the silent install file
ask_container_basedir()
{
	eval CONTAINER_BASE_DIR=$`echo $CONTAINER_BASE_DIR_VAR`
	while true
	do
		$ECHO
		msg=`$gettext "What is the base directory where $WCNAME is installed?"`
		$ECHO "$msg" "[$CONTAINER_BASE_DIR]: $OMIT"

		read ANS
		if [ "$ANS" != "" ]; then
			CONTAINER_BASE_DIR=$ANS
		fi

		validate_container_basedir $CONTAINER_BASE_DIR
		case $? in
			$ERR_DIR_NOT_EXIST)
				msg=`$gettext "Directory $CONTAINER_BASE_DIR does not exist!"`
				$ECHO $msg
				continue
				;;
			$VALID) break;;
		esac
	done

	setdeployvar $CONTAINER_BASE_DIR_VAR $CONTAINER_BASE_DIR
}

##############################################################################
#
# This function asks the user to specify the container's Admin ID
# Sets appropriate variable to the container's basedir provided in
# the silent install file
ask_container_adminid()
{
	eval CONTAINER_ADMINID=$`echo $CONTAINER_ADMINID_VAR`

	$ECHO
	msg=`$gettext "What is the Admin ID for the $WCNAME?"`
	$ECHO "$msg" "[$CONTAINER_ADMINID]: $OMIT"

	read ANS
	if [ "$ANS" != "" ]; then
		CONTAINER_ADMINID=$ANS
	fi

	setdeployvar $CONTAINER_ADMINID_VAR $CONTAINER_ADMINID
}

##############################################################################
#
# This function asks the user to specify the container's Admin ID password
# Sets appropriate variable to the container's basedir provided in 
# the silent install file
ask_container_adminpwd()
{
	if [ "$WEB_CONTAINER" != "WS6" -a "$WEB_CONTAINER" != "WAS5" ]; then
		get_passwd "existing" "Admin Password for the $WCNAME"
		setdeployvar $CONTAINER_ADMIN_PASSWD_VAR $RETURN_VALUE
	fi
}

#########################################################
#
# This function asks the container host for install
# Sets appropriate varibake in the silent install file
ask_container_host()
{
	msg=`$gettext "where the Container $WCNAME is installed"`
	get_host "$msg"
	setdeployvar $CONTAINER_HOST_VAR $RETURN_VALUE
}

##########################################################
#
# This function asks the container port for install
# Sets appropriate variable in the silent install file
ask_container_port()
{
	eval CONTAINER_PORT=$`echo $CONTAINER_PORT_VAR`
	eval CONTAINER_HOST=$`echo $CONTAINER_HOST_VAR`
	while true
	do
		msg=`$gettext "which will be used by the Container $WCNAME"`
		get_port "$msg" $CONTAINER_PORT
		validate_existing_port $CONTAINER_HOST $RETURN_VALUE
		if [ $? -eq $ERR_PORT_NOTUSED ]; then
			$ECHO "`$gettext 'Port is not in use. Please specify a different port'`"
			continue
		else
			break
		fi
	done
	setdeployvar $CONTAINER_PORT_VAR $RETURN_VALUE
}

##########################################################
#
# This function asks the container protocol for install
# Sets appropriate varibale in the silent install file
ask_container_protocol()
{
	eval CONTAINER_PROTO=$`echo $CONTAINER_PROTO_VAR`
	msg=`$gettext "which will be used by the Container $WCNAME"`
	get_protocol "$msg" $CONTAINER_PROTO
	setdeployvar $CONTAINER_PROTO_VAR $RETURN_VALUE
}

#############################################################################################
#
# This function asks the server name (FQDN) of the machine where Access Manager will be run
# Sets SERVER_HOST in the silent install file
ask_server_host()
{
	# Special case for full install
	if [ $DEPLOY_LEVEL -eq 1 -o $DEPLOY_LEVEL -eq 6 ]; then
		msg=`$gettext 'where the Access Manager will be installed'`
	else
		msg=`$gettext 'where the Access Manager is installed'`
	fi
	get_host "$msg"
	SERVER_HOST=$RETURN_VALUE
	setdeployvar SERVER_HOST
}

#########################################################
#
# This function asks the server port for Access Manager
# Sets SERVER_PORT in the silent install file
ask_server_port()
{
	while true
	do
		# Special case for full install
		if [ $DEPLOY_LEVEL -eq 1 -o $DEPLOY_LEVEL -eq 6 ]; then
			msg=`$gettext 'which will be used by Access Manager?'`
		else
			msg=`$gettext 'which is used by Access Manager?'`
		fi
		get_port "$msg" $SERVER_PORT
		validate_existing_port $SERVER_HOST $RETURN_VALUE
		if [ $? -eq $ERR_PORT_NOTUSED ]; then
			$ECHO "`$gettext 'Port is not in use. Is the Access Manager Container running?'`"
			continue
		else
			break
		fi
	done

	SERVER_PORT=$RETURN_VALUE
	setdeployvar SERVER_PORT
}

#############################################################
#
# This function asks the server protocol for Access Manager
# Sets SERVER_PROTOCOL in the silent install file
ask_server_protocol()
{
	# Special case for full install
	if [ $DEPLOY_LEVEL -eq 1 -o $DEPLOY_LEVEL -eq 6 ]; then
		msg=`$gettext 'which will be used by Access Manager?'`
	else
		msg=`$gettext 'which is used by Access Manager?'`
	fi
	get_protocol "$msg" $SERVER_PROTOCOL
	SERVER_PROTOCOL=$RETURN_VALUE
	setdeployvar SERVER_PROTOCOL
}

############################################################
#
# This function asks the user if the container is secure
# and asks the SSL password if it is.
# Sets SSL_PASSWORD in the silent install file
ask_ssl_password()
{
	msg=`$gettext "Is the Web container $WCNAME secure?"`
	yesno "$msg" "n"
	if [ "$ans" = "y" ]; then
		setdeployvar $CONTAINER_SECURE_VAR "true"
		get_passwd "new" `$gettext "SSL password for $WCNAME"`
		SSL_PASSWORD=$RETURN_VALUE
		setdeployvar SSL_PASSWORD
	else
		setdeployvar $CONTAINER_SECURE_VAR "false"
	fi

}

#####################################################################################################
#
# This function asks the server name (FQDN) of the machine where Access Manager Console will be run
# Sets CONSOLE_HOST in the silent install file
ask_console_host()
{
	if [ $DEPLOY_LEVEL -eq 6 ]; then
		msg=`$gettext 'where the Access Manager Console is installed'`
	else
		msg=`$gettext 'where the Access Manager Console will be installed'`
	fi
	get_host "$msg" $CONSOLE_HOST
	CONSOLE_HOST=$RETURN_VALUE
	setdeployvar CONSOLE_HOST
}

#################################################################
#
# This function asks the server port for Access Manager Console
# Sets CONSOLE_PORT in the silent install file
ask_console_port()
{
	while true
	do
		if [ $DEPLOY_LEVEL -ne 6 ]; then
			msg=`$gettext 'which will be used by Access Manager Console?'`
		else
			msg=`$gettext 'which is used by Access Manager Console?'`
		fi
		get_port "$msg" $CONSOLE_PORT
		validate_existing_port $CONSOLE_HOST $RETURN_VALUE
		if [ $? -eq $ERR_PORT_NOTUSED ]; then
			$ECHO "`$gettext 'Port is not in use. Is the Access Manager Console Container running?'`"
			continue
		else
			break
		fi
	done

	CONSOLE_PORT=$RETURN_VALUE
	setdeployvar CONSOLE_PORT
}

#############################################################
#
# This function determines if the Console will be run remote
# Sets CONSOLE_REMOTE in the silent install file
set_console_remote_status()
{
	CONSOLE_REMOTE=false

	# If Console Host is set to the same as server host or not.
	if [ "$CONSOLE_HOST" != "$SERVER_HOST" -a "$CONSOLE_HOST" != "\$SERVER_HOST"  ]; then
		CONSOLE_REMOTE=true
	fi

	# If Console Port is set to the same as server port or not.
	if [ "$CONSOLE_PORT" != "$SERVER_PORT" -a "$CONSOLE_PORT" != "\$SERVER_PORT"  ]; then
		CONSOLE_REMOTE=true
	fi

	setdeployvar CONSOLE_REMOTE
}

#####################################################################
#
# This function asks the server protocol for Access Manager Console
# Sets CONSOLE_PROTOCOL in the silent install file
ask_console_protocol()
{
	if [ $DEPLOY_LEVEL -eq 6 ]; then
		msg=`$gettext 'which is used by Access Manager Console?'`
	else
		msg=`$gettext 'which will be used by Access Manager Console?'`
	fi
	get_protocol "$msg" $SERVER_PROTOCOL
	CONSOLE_PROTOCOL=$RETURN_VALUE
	setdeployvar CONSOLE_PROTOCOL
}

###############################################################################################
#
# This function asks the server name (FQDN) of the machine where Directory Server is installed
# Sets DS_HOST in the silent install file
ask_ds_host()
{
	msg=`$gettext 'where the Directory Server is installed?'`
	get_host "$msg" $DS_HOST
	DS_HOST=$RETURN_VALUE
	setdeployvar DS_HOST
}

##########################################################
#
# This function asks the server port for Directory Server
# Sets DS_PORT in the silent install file
ask_ds_port()
{
	while true
	do
		msg=`$gettext 'where the Directory Server is installed?'`
		get_port "$msg" $DS_PORT
		DS_PORT=$RETURN_VALUE

		validate_existing_port $DS_HOST $DS_PORT
		if [ $? -eq $ERR_PORT_NOTUSED ]; then
			$ECHO "`$gettext 'Could not connect to Directory Server. Please check the port number used by Directory Server.'`"
			continue
		else
			break
		fi
	done

	setdeployvar DS_PORT
}

###########################################################
#
# This function asks the user for the directory manager dn
# Sets DS_DIRMGRDN in the silent install file
ask_ds_mgr_dn() {

	$ECHO
	$ECHO "`$gettext 'The Directory Server administrative user, or Directory Manager will be used to perform certain directory operations'`"
	$ECHO "`$gettext 'Directory Manager DN'` [$DS_DIRMGRDN]: ${OMIT}"
	read ANS
	if [ "$ANS" != "" ]; then
		DS_DIRMGRDN=$ANS
	fi
	setdeployvar DS_DIRMGRDN
}

######################################################
#
# This function asks the Directory Manager's password
# Sets DS_DIRMGRPASSWD in the silent install file
ask_ds_passwd()
{
	get_passwd "existing" "Directory Manager"
	DS_DIRMGRPASSWD=$RETURN_VALUE
	setdeployvar DS_DIRMGRPASSWD
}

##################################
#
# Validates Directory Server Mode
validate_ds_mode()
{
	[ "$1" -lt 1 ] && return $ERR_INVALID_DS_MODE
	[ "$1" -gt 5 ] && return $ERR_INVALID_DS_MODE
	return $VALID
}

#######################################################################
#
# This function asks the Directory Server mode (Fresh or Existing DIT)
# Sets DIRECTORY_MODE in the silent install file
ask_ds_mode()
{
	while true
	do
		$ECHO
		$ECHO `$gettext 'Please specify whether the Access Manager DIT exists on the Directory Server or not?'`
		$ECHO `$gettext 'Please choose one of the following options:'` $OMIT
		$ECHO
		$ECHO `$gettext '1. Fresh Directory Server (no existing Access Manager DIT)'`
		$ECHO `$gettext '2. Directory Server has an existing Access Manager DIT'`
		$ECHO `$gettext '3. Existing DIT with Manual procedure to load ldifs later'`
		$ECHO `$gettext '4. Existing Multiserver(only tag swapping)'`
		$ECHO `$gettext '5. Upgrade (only tag swapping)'`
		$ECHO
		$ECHO "`$gettext 'Please make your selection: [1]'` $OMIT"

		read ANS
		if [ "$ANS" = "" ]; then
			ANS=1
		fi
		DIRECTORY_MODE=$ANS
		validate_ds_mode $DIRECTORY_MODE
		case $? in
			$ERR_INVALID_DS_MODE)
				$ECHO
				$ECHO `$gettext "Please choose from 1-5 only."`
				continue
				;;
			$VALID) break;;
		esac
	done

	setdeployvar DIRECTORY_MODE
}

#################################################################################
#
# This function asks the DS Root Suffix where Access Manager will be configured
# Sets ROOT_SUFFIX in the silent install file
ask_root_suffix()
{
	$ECHO
	$ECHO "`$gettext 'Please provide the Directory Root Suffix where Access Manager will be configured'` [$ROOT_SUFFIX] $OMIT"
	read ANS
	if [ "$ANS" != "" ]; then
		ROOT_SUFFIX=$ANS
	fi

	setdeployvar ROOT_SUFFIX
}

############################################
# Connects to the DS server to verify
# that the DS specified is valid
validate_ds_connection()
{
	dirhost=$1
	dirport=$2
	dirmgrdn=$3
	dirmgrpwd=$4

	LDAPSEARCH=$BASEDIR/$PRODUCT_DIR/bin/ldapsearch
	if [ "$OSTYPE" = "Linux" ]; then
		LDAPLIBS=$BASEDIR/$PRODUCT_DIR/ldaplib/ldapsdk:/opt/sun/private/lib
	else
		LDAPLIBS=$BASEDIR/$PRODUCT_DIR/ldaplib/ldapsdk:/usr/lib/mps/secv1
	fi

	LD_LIBRARY_PATH=$LDAPLIBS $LDAPSEARCH -h $dirhost -p $dirport -b "cn=schema" -D "$dirmgrdn" -w $dirmgrpwd "(objectclass=*)" | grep -i groupofuniquenames > /dev/null 2>&1
	if [ $? -eq 0 ]; then
		$ECHO "`$gettext 'Success connecting to the DS server'`"
		return $VALID
	else
		$ECHO "`$gettext 'Failure connecting to the DS server!'`"
		return $ERR_DS_NOT_REACHABLE
	fi
}

##########################################
# Asks amadmin password
ask_amadmin_passwd()
{
	get_passwd "new" "Super Admin or amadmin user of the Access Manager"
	ADMINPASSWD=$RETURN_VALUE
	setdeployvar ADMINPASSWD
}

#########################################
# Validates amldapuser password to be
# different from amadmin password
validate_amldapuser_passwd()
{
	[ "$1" = "$ADMINPASSWD" ] && return $ERR_PASSWD_CANTBE_SAME
	return $VALID
}

#########################################
# Asks amldapuser password
ask_amldapuser_passwd()
{
	while true
	do
		get_passwd "new" "LDAP User or User to bind to the directory for the authentication process"
		validate_amldapuser_passwd $RETURN_VALUE
		if [ $? -eq $ERR_PASSWD_CANTBE_SAME ]; then
			$ECHO "`$gettext 'LDAP User password cannot be the same as the Admin User password'`"
			$ECHO "`$gettext 'Please enter a different password'`"
			continue
		else
			break
		fi
	done
	AMLDAPUSERPASSWD=$RETURN_VALUE
	setdeployvar AMLDAPUSERPASSWD
}

########################
# Validates a URI
validate_uri()
{
	fc=`$ECHO $1 | cut -c1`
	[ "$fc" != "/" ] && return $ERR_URI_FIRST_CHAR
	return $VALID
}

################################
# Prompts for a URI and
# validates it.
get_uri()
{
	msg=$1
	defaulturi=$2

	while true
	do
		$ECHO "`$gettext 'What is the deployment URI prefix for'` $msg: [$defaulturi] ${OMIT}"
		read URI

		if [ "$URI" = "" ]; then
			URI=$defaulturi
		fi

		# Get rid of the trailing / if any
		if [ "$URI" != "/" ]; then
			URI=`$ECHO $URI | sed -e 's/\/$//'`
		fi

		validate_uri $URI
		case $? in
			$ERR_URI_FIRST_CHAR)
				errmsg=`$gettext "$URI is an invalid URI. URIs should begin with a /. Please enter again."`
				$ECHO $errmsg
				continue
				;;
			$VALID) break;;
		esac
	done
	RETURN_VALUE=$URI
}

#############################
# Asks Server Deploy URI
ask_server_uri()
{
	msg="`$gettext 'the Access Manager Management and Policy Services?'`"
	get_uri "$msg" "$SERVER_DEPLOY_URI"
	SERVER_DEPLOY_URI=$RETURN_VALUE
	setdeployvar SERVER_DEPLOY_URI
}

#############################
# Asks Console Deploy URI
ask_console_uri()
{
	msg="`$gettext 'the Access Manager Administration Console?'`"
	get_uri "$msg" "$CONSOLE_DEPLOY_URI"
	CONSOLE_DEPLOY_URI=$RETURN_VALUE
	setdeployvar CONSOLE_DEPLOY_URI
}

#############################
# Asks Password Deploy URI
ask_password_uri()
{
	msg="`$gettext 'the PASSWORD module?'`"
	get_uri "$msg" "$PASSWORD_DEPLOY_URI"
	PASSWORD_DEPLOY_URI=$RETURN_VALUE
	setdeployvar PASSWORD_DEPLOY_URI
}

#############################
# Asks Common Deploy URI
ask_common_uri()
{
	msg="`$gettext 'the COMMON module?'`"
	get_uri "$msg" "$COMMON_DEPLOY_URI"
	COMMON_DEPLOY_URI=$RETURN_VALUE
	setdeployvar COMMON_DEPLOY_URI
}

##############################
# Wrapper for asking all URIs
ask_all_uris()
{
	ask_server_uri
	ask_console_uri
	ask_password_uri
	ask_common_uri
}

#############################
# Validates a cookie domain
validate_cookie_domain()
{
	fc=`$ECHO $1 | cut -c1`
	[ "$fc" != "." ] && return $ERR_INVALID_COOKIE_DOMAIN
	return $VALID
}

#############################
# Asks for the cookie domain
ask_cookie_domain()
{
	# Take the last 2 components of the domainname as the default cookie domain
	COOKIE_DOMAIN=`domainname | nawk -F. '{ print "." $(NF-1) "." $NF }'`

	while true
	do
		cookiedomain=$COOKIE_DOMAIN
		$ECHO "`$gettext 'What is the Cookie Domain?'` [$cookiedomain]: ${OMIT}"
		read ANS
		if [ "$ANS" != "" ]; then
			cookiedomain=$ANS
		fi

		validate_cookie_domain $cookiedomain

		case $? in
			$ERR_INVALID_COOKIE_DOMAIN)
				errmsg=`$gettext "$cookiedomain is an invalid cookie domain. Cookie domain must begin with a \'.\'. Please enter again."`
				$ECHO "$errmsg"
				continue;;
			$VALID) break;;
		esac
	done

	COOKIE_DOMAIN=$cookiedomain
	setdeployvar COOKIE_DOMAIN

}

############################
# Validates JAVA_HOME
validate_java_home()
{
	[ ! -d $1 ] && return $ERR_INVALID_JAVA_HOME
	[ ! -x $1/bin/java ] && return $ERR_INVALID_JAVA_HOME
	return $VALID
}

############################
# Asks for JAVA_HOME
ask_java_home()
{
	while true
	do
		javahome=$JAVA_HOME
		$ECHO "`$gettext 'Where is Java 2 installed?'` [$javahome]: ${OMIT}"
		read ANS
		if [ "$ANS" != "" ]; then
			javahome=$ANS
		fi

		validate_java_home $javahome

		case $? in
			$ERR_INVALID_JAVA_HOME)
				errmsg=`$gettext "Java is not installed in $javahome. Please enter again."`
				$ECHO "$errmsg"
				continue;;
			$VALID) break;;
		esac
	done

	JAVA_HOME=$javahome
	setdeployvar JAVA_HOME
}

#################################
# Validates a User name
validate_new_owner()
{
	$GETENT passwd $1 >/dev/null 2>&1
	[ $? -ne 0 ] && return $ERR_INVALID_USER
	return $VALID
}

#################################
# Asks for the Owner to run Access Manager as
ask_new_owner()
{
	while true
	do
		newowner=$NEW_OWNER
		$ECHO "`$gettext 'Which User will Access Manager run as?'` [$newowner]: ${OMIT}"
		read ANS
		if [ "$ANS" != "" ]; then
			newowner=$ANS
		fi

		validate_new_owner $newowner

		case $? in
			$ERR_INVALID_USER)
				errmsg=`$gettext "User $newowner does not exist. Please specify a different user"`
				$ECHO "$errmsg"
				continue;;
			$VALID) break;;
		esac
	done

	NEW_OWNER=$newowner
	setdeployvar NEW_OWNER
}

#################################
# Validates a Group name
validate_new_group()
{
	$GETENT group $1 >/dev/null 2>&1
	[ $? -ne 0 ] && return $ERR_INVALID_GROUP
	return $VALID
}

#################################
# Asks for the Group to run Access Manager as
ask_new_group()
{
	while true
	do
		newgroup=$NEW_GROUP
		$ECHO "`$gettext 'Which Group will Access Manager run as?'` [$newgroup]: ${OMIT}"
		read ANS
		if [ "$ANS" != "" ]; then
			newgroup=$ANS
		fi

		validate_new_group $newgroup

		case $? in
			$ERR_INVALID_GROUP)
				errmsg=`$gettext "Group $newgroup does not exist. Please specify a different group"`
				$ECHO "$errmsg"
				continue;;
			$VALID) break;;
		esac
	done

	NEW_GROUP=$newgroup
	setdeployvar NEW_GROUP
}

###############################
# Asks Default Organization
# Sets DEFAULT_ORGANIZATION
# in the silent install file
ask_default_org()
{
	while true
	do
		yesno "Do you want to specify a different Default Organization for installing Access Manager?" "n"
		if [ "$ans" = "y" ]; then
			$ECHO "`$gettext 'What is the Default Organization name?: '` ${OMIT}"
			read ANS
			if [ "$ANS" != "" ]; then
				DEFAULT_ORGANIZATION=$ANS
				break
			else
				continue
			fi
		else
			DEFAULT_ORGANIZATION=
			break
		fi
	done
	setdeployvar DEFAULT_ORGANIZATION

}

#######################################
# Asks the User Naming Attribute
# Sets USER_NAMING_ATTR in the
# silent install file
ask_user_naming_attr()
{
	$ECHO "`$gettext 'What is the User Naming Attribute?'` [$USER_NAMING_ATTR]: ${OMIT}"
	read ANS
	if [ "$ANS" != "" ]; then
		USER_NAMING_ATTR=$ANS
	fi
	setdeployvar USER_NAMING_ATTR
}

#######################################
# Asks the Organization Naming Attribute
# Sets ORG_NAMING_ATTR in the
# silent install file
ask_org_naming_attr()
{
	$ECHO "`$gettext 'What is the Organization Naming Attribute?'` [$ORG_NAMING_ATTR]: ${OMIT}"
	read ANS
	if [ "$ANS" != "" ]; then
		ORG_NAMING_ATTR=$ANS
	fi
	setdeployvar ORG_NAMING_ATTR
}

#######################################
# Asks the User Object Class
# Sets USER_OBJECT_CLASS in the
# silent install file
ask_user_object_class()
{
	$ECHO "`$gettext 'What is the User Object Class?'` [$USER_OBJECT_CLASS]: ${OMIT}"
	read ANS
	if [ "$ANS" != "" ]; then
		USER_OBJECT_CLASS=$ANS
	fi
	setdeployvar USER_OBJECT_CLASS
}

#######################################
# Asks the Organization Object Class
# Sets ORG_OBJECT_CLASS in the
# silent install file
ask_org_object_class()
{
	$ECHO "`$gettext 'What is the Organization Object Class?'` [$ORG_OBJECT_CLASS]: ${OMIT}"
	read ANS
	if [ "$ANS" != "" ]; then
		ORG_OBJECT_CLASS=$ANS
	fi
	setdeployvar ORG_OBJECT_CLASS
}

###############################
# Wrapper for all DS questions
ask_all_ds_details()
{
	ask_ds_host
	ask_ds_port
	ask_ds_mgr_dn
	ask_ds_passwd
	ask_ds_mode
	ask_root_suffix
	validate_ds_connection $DS_HOST $DS_PORT "$DS_DIRMGRDN" "$DS_DIRMGRPASSWD"
}

#############################
# Wrapper for all questions
# for full install
# DEPLOY_LEVEL=1
ask_all_questions()
{
	ask_basedir
	ask_container
	ask_container_basedir
	ask_container_adminid
	ask_container_adminpwd
	ask_server_host
	ask_server_port
	ask_server_protocol
	ask_ssl_password
	setdeployvar $CONTAINER_HOST_VAR '$SERVER_HOST'
	setdeployvar $CONTAINER_PORT_VAR '$SERVER_PORT'
	setdeployvar $CONTAINER_PROTO_VAR '$SERVER_PROTOCOL'
	setdeployvar CONSOLE_HOST '$SERVER_HOST'
	setdeployvar CONSOLE_PORT '$SERVER_PORT'
	setdeployvar CONSOLE_PROTOCOL '$SERVER_PROTOCOL'
	setdeployvar CONSOLE_REMOTE "false"
	ask_all_ds_details
	ask_amadmin_passwd
	ask_amldapuser_passwd
	ask_all_uris
	ask_cookie_domain
#	ask_default_org
	ask_user_naming_attr
	ask_org_naming_attr
	ask_user_object_class
	ask_org_object_class
	ask_java_home
	ask_new_owner
	ask_new_group
}

###########################
# Wrapper for CONSOLE only
# install questions
# DEPLOY_LEVEL=2
ask_console_questions()
{
	ask_basedir
	ask_container
	ask_container_basedir
	ask_container_adminid
	ask_container_adminpwd
	ask_console_host
	ask_console_port
	ask_console_protocol
	ask_ssl_password
	setdeployvar $CONTAINER_HOST_VAR '$CONSOLE_HOST'
	setdeployvar $CONTAINER_PORT_VAR '$CONSOLE_PORT'
	setdeployvar $CONTAINER_PROTO_VAR '$CONSOLE_PROTOCOL'
	ask_server_host
	ask_server_port
	ask_server_protocol
	setdeployvar CONSOLE_REMOTE "true"
	ask_ds_host
	ask_ds_port
	ask_root_suffix
	ask_amadmin_passwd
	ask_console_uri
	ask_password_uri
	ask_java_home
	ask_new_owner
	ask_new_group
}

###########################
# Wrapper for SDK only
# install questions
# DEPLOY_LEVEL=3
ask_sdk_questions()
{
	ask_basedir
	ask_server_host
	ask_server_port
	ask_server_protocol
	ask_ds_host
	ask_ds_port
	ask_root_suffix
	ask_amadmin_passwd
	ask_server_uri
	ask_java_home
	ask_new_owner
	ask_new_group
}


###########################
# Wrapper for SDK with
# Container Config questions
# DEPLOY_LEVEL=4
ask_sdk_container_config_questions()
{
	ask_basedir
	ask_container
	ask_container_basedir
	ask_container_adminid
	ask_container_adminpwd
	ask_container_host
	ask_container_port
	ask_container_protocol
	ask_ssl_password
	ask_server_host
	ask_server_port
	ask_server_protocol
	ask_ds_host
	ask_ds_port
	ask_root_suffix
	ask_amadmin_passwd
	ask_server_uri
	ask_java_home
	ask_new_owner
	ask_new_group
}

###########################
# Wrapper for Federation
# Config questions
# DEPLOY_LEVEL=5
ask_federation_questions()
{
	ask_basedir
	ask_container
	ask_container_basedir
	ask_container_adminid
	ask_container_adminpwd
	ask_container_host
	ask_container_port
	ask_container_protocol
	ask_ssl_password
	ask_server_host
	ask_server_port
	ask_server_protocol
	ask_ds_host
	ask_ds_port
	ask_root_suffix
	ask_amadmin_passwd
	ask_server_uri
	ask_common_uri
	ask_java_home
	ask_new_owner
	ask_new_group
}

#############################
# Wrapper for Server Only
# config questions
# DEPLOY_LEVEL=6
ask_server_only_questions()
{
	ask_basedir
	ask_container
	ask_container_basedir
	ask_container_adminid
	ask_container_adminpwd
	ask_server_host
	ask_server_port
	ask_server_protocol
	ask_ssl_password
	setdeployvar $CONTAINER_HOST_VAR '$SERVER_HOST'
	setdeployvar $CONTAINER_PORT_VAR '$SERVER_PORT'
	setdeployvar $CONTAINER_PROTO_VAR '$SERVER_PROTOCOL'
	ask_console_host
	ask_console_port
	ask_console_protocol
	setdeployvar CONSOLE_REMOTE "true"
	ask_all_ds_details
	ask_amadmin_passwd
	ask_amldapuser_passwd
	ask_server_uri
	ask_common_uri
	ask_cookie_domain
#	ask_default_org
	ask_user_naming_attr
	ask_org_naming_attr
	ask_user_object_class
	ask_org_object_class
	ask_java_home
	ask_new_owner
	ask_new_group
}

ask_undeploy_questions()
{
	ask_basedir
	ask_container
	ask_container_basedir
	ask_container_host
	ask_container_port
	ask_container_protocol
	case $DEPLOY_LEVEL in
		11) ask_all_uris;;
		12) ask_console_uri
		    ask_password_uri;;
		15) ask_common_uri;;
		16) ask_server_uri
		    ask_common_uri;;
	esac
	ask_java_home
}

#################################
# Calls deploy level specific
# functions to ask the questions
ask_questions()
{
	ask_deploy_level

	case $DEPLOY_LEVEL in

		1) ask_all_questions;;
		2) ask_console_questions;;
		3) ask_sdk_questions;;
		4) ask_sdk_container_config_questions;;
		5) ask_federation_questions;;
		6) ask_server_only_questions;;
		11|12|13|14|15|16) ask_undeploy_questions;;
	esac
}

####################################
# Interactive mode wrapper function
do_interactive()
{
	if [ "$IS_SILENT_INSTALL_FILE" != "" ]; then
		if [ -f $IS_SILENT_INSTALL_FILE ]; then
			. $IS_SILENT_INSTALL_FILE
		fi
	else
		# Try to guess the location of the sample install file
		if [ -f ./amsamplesilent ]; then
			SAMPLE_SILENT_FILE=./amsamplesilent
		elif [ -f `dirname $0`/amsamplesilent ]; then
			SAMPLE_SILENT_FILE=`dirname $0`/amsamplesilent
		elif [ -f /opt/SUNWam/bin/amsamplesilent ]; then
			SAMPLE_SILENT_FILE=/opt/SUNWam/bin/amsamplesilent
		elif [ -f /opt/sun/identity/bin/amsamplesilent ]; then
			SAMPLE_SILENT_FILE=/opt/sun/identity/bin/amsamplesilent
		elif [ -f /tmp/amsamplesilent ]; then
			SAMPLE_SILENT_FILE=/tmp/amsamplesilent
		fi

		if [ "$SAMPLE_SILENT_FILE" = "" ]; then
			echo "Could not find the sample silent installation file. Cannot proceed."
			exit 1
		fi

		IS_SILENT_INSTALL_FILE=/tmp/amsilent.inf
		export IS_SILENT_INSTALL_FILE

		if [ ! -f $IS_SILENT_INSTALL_FILE ]; then
			cp -p $SAMPLE_SILENT_FILE $IS_SILENT_INSTALL_FILE
			chmod 600 $IS_SILENT_INSTALL_FILE
		fi
	fi

	clear
	echo "The install parameters will be saved in $IS_SILENT_INSTALL_FILE"
	source_amutils
	ask_questions
}

######################################################################
#########
#Appends the jvmclasspath to the classpath
classpathAdd()
{
cp=$1
jvmclasspath=$2
if [ "$cp" != "null" ] && [ "$cp" != "" ]; then
  classpathadded="$cp:$jvmclasspath"
else
  classpathadded=$jvmclasspath
fi
export classpathadded
}

######################################################################
#########
#Removes the jvmclasspath from the classpath
classpathRemove()
{
newcp=$1
jvmclasspath=$2
SPACE=""
classpathremoved=`echo $newcp | sed -e "s#$jvmclasspath#$SPACE#g"`
    export classpathremoved
}

################################################
# This function determines if a given package
# is installed or not.
# Returns 0 if installed, 1 otherwise.
is_pkg_installed()
{
	PKG=$1
	if [ "$OSTYPE" = "Linux" ]; then
		rpm -q --quiet $PKG
	elif [ "$OSTYPE" = "SunOS" ]; then
		pkginfo -q $PKG
	else
		return 1
	fi

	if [ $? -ne 0 ]; then
		return 1
	else
		return 0
	fi
}

####################################################
# This function updates the server entry in platform
# service list and organization alias list in exisitng
# directory server.
#
addServerEntry()
{   
    CONTAINER_PROTOCOL=$SERVER_PROTOCOL
    CONTAINER_HOST=$SERVER_HOST
    CONTAINER_PORT=$SERVER_PORT
    
    if [ "$WEB_CONTAINER" = "WS6" ];then
        CONTAINER_PROTOCOL=$WS61_PROTOCOL
        CONTAINER_HOST=$WS61_HOST
        CONTAINER_PORT=$WS61_PORT
    elif [ "$WEB_CONTAINER" = "AS7" ];then
        CONTAINER_PROTOCOL=$AS70_PROTOCOL
        CONTAINER_HOST=$AS70_HOST
        CONTAINER_PORT=$AS70_PORT
    elif [ "$WEB_CONTAINER" = "AS8" ];then
        CONTAINER_PROTOCOL=$AS81_PROTOCOL
        CONTAINER_HOST=$AS81_HOST
        CONTAINER_PORT=$AS81_PORT
    fi
    
    SERVER_URI="$CONTAINER_PROTOCOL://$CONTAINER_HOST:$CONTAINER_PORT"
    
    if [ "$1" != "" ]; then
        SERVER_ARG="-Dserver.name=$1"
        AMCONFIG=$IS_INSTALL_ETCDIR/$PRODUCT_DIR/config/AMConfig-$1.properties
    else
        AMCONFIG=$IS_INSTALL_ETCDIR/$PRODUCT_DIR/config/AMConfig.properties
    fi
    
    AM_SERVER_PROTOCOL=`grep com.iplanet.am.server.protocol $AMCONFIG | sed -e "s#com.iplanet.am.server.protocol=##"`
    if [ "$AM_SERVER_PROTOCOL" = "https" -o "$AM_SERVER_PROTOCOL" = "HTTPS" ]; then
        SERVER_ARG="$SERVER_ARG -Djava.protocol.handler.pkgs=com.iplanet.services.comm"
    fi

    LIB_DIR=${PKGDIR}/lib
    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/servlet.jar:$LIB_DIR/jaxp-api.jar:$LIB_DIR/sax.jar:$LIB_DIR/xercesImpl.jar:$LIB_DIR/dom.jar:$LIB_DIR/xmlsec.jar:$LIB_DIR/xalan.jar:$CONFIG_DIR

   ${JAVA_HOME}/bin/java $SERVER_ARG -classpath $CLASSPATH com.iplanet.am.util.AMGenerateServerID create "$SERVER_URI" "cn=dsameuser,ou=DSAME Users,$ORG_ROOT_SUFFIX" "$ADMINPASSWD"

    # build a new ldif file for new global alias entry
    file=/tmp/ga-$$.ldif
cat << EOF > $file
dn:$ROOT_SUFFIX
changetype:modify
add:sunOrganizationAlias
sunOrganizationAlias:$CONTAINER_HOST
EOF

    if [ "$OSTYPE" = "Linux" ]; then
        # Why is the native_threads dir needed in LD_LIBRARY_PATH on Linux? No idea. Seems like a JDK bug on Linux.
	LD_LIBRARY_PATH=$JSS_SO_PATH:$NSS_SO_PATH:$NSPR_SO_PATH:${PKGDIR}/lib:${PKGDIR}/ldaplib/ldapsdk:$JAVA_HOME/jre/lib/i386/native_threads
    else
	LD_LIBRARY_PATH=$JSS_SO_PATH:$NSS_SO_PATH:$NSPR_SO_PATH:${PKGDIR}/lib:${PKGDIR}/ldaplib/ldapsdk
    fi
    
    # load it to DS
    $PKGDIR/bin/ldapmodify -h $DS_HOST -p $DS_PORT -D "cn=dsameuser,ou=DSAME Users,$ORG_ROOT_SUFFIX" -w "$ADMINPASSWD" -c -a -f $file
    rm -f $file
}

check_server_xml()
{
conf_file=${1:-server.xml}
file_type=${2:-xml}
container=${3:-ws61}

if [ "$container" = "ws61" ];then
 suffixstring="classpathsuffix"
elif [ "$container" = "as70" ];then
 suffixstring="classpath-suffix"
elif [ "$container" = "as81" ];then
 suffixstring="classpath-suffix"
elif [ "$container" = "was51" ];then
 suffixstring="classpath"
fi

  exist=0
  #step1: grep for classpath suffix in server.xml
  file=$conf_file
  classpath=`grep $suffixstring $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 "$suffixstring" |grep "am_sdk.jar"`
      if [ "$classpathToken" != "" ]; then
          exist=1
      fi
      count=`expr $count + 1`
  done

return $exist
}


# Link the shared componenet jars like JWSDP and LDAPJDK
link_shared_jars()
{
if [ "$OSTYPE" = "Linux" ]; then
	# It will always be install under this location.
	SHARED_JAR_LOC=/opt/sun/share/lib
	PRIVATE_SHARED_JAR_LOC=/opt/sun/private/share/lib
else
	SHARED_JAR_LOC=${MISC_JAR_PATH}
	PRIVATE_SHARED_JAR_LOC=${MISC_JAR_PATH}
fi

JAR_LIST="ldapjdk.jar \
	dom.jar \
        xalan.jar \
        xercesImpl.jar \
        jaxr-api.jar \
        jaxr-impl.jar \
        jaxrpc-api.jar \
        jaxrpc-impl.jar \
        jaxb-api.jar \
        jaxb-impl.jar \
        jaxb-xjc.jar \
        jaxb-libs.jar \
        saaj-api.jar \
        saaj-impl.jar \
        jax-qname.jar \
        namespace.jar \
	activation.jar \
	mail.jar"
PRIVATE_JAR_LIST="jaxrpc-spi.jar \
        relaxngDatatype.jar \
        xsdlib.jar"


for ja in ${JAR_LIST}
do
	if [ ! -f ${PKGDIR}/lib/${ja} ]; then
	  if [ -f ${SHARED_JAR_LOC}/${ja} ]; then
		ln -s ${SHARED_JAR_LOC}/${ja} ${PKGDIR}/lib/${ja}
          else
    		eval $ECHO "`$gettext 'WARNING: Shared JAR file not found: ${SHARED_JAR_LOC}/${ja}'`"
          fi
	fi
done

for ja in ${PRIVATE_JAR_LIST}
do
    if [ ! -f ${PKGDIR}/lib/${ja} ]; then
	if [ -f ${PRIVATE_SHARED_JAR_LOC}/${ja} ]; then
	   ln -s ${PRIVATE_SHARED_JAR_LOC}/${ja} ${PKGDIR}/lib/${ja}
        else
     	   eval $ECHO "`$gettext 'WARNING: Shared JAR file not found: ${PRIVATE_SHARED_JAR_LOC}/${ja}'`"
        fi
    fi
done

}

# add permission for SSL
configureJvmPolicy()
{
# modifying java.policy
   file=$JAVA_HOME/jre/lib/security/java.policy
   result=`grep "Access Manager RELATED ADDITIONS" $JAVA_HOME/jre/lib/security/java.policy`
   if [ "$result" = "" ]; then
      append_line $file 'grant {' ' '
      append_line $file 'grant {' '	permission java.util.PropertyPermission "java.protocol.handler.pkgs", "write";'
      append_line $file 'grant {' '	// Access Manager RELATED ADDITIONS'
   fi
}

####################################################
# This function searches a package to find a file. It matches regular file
# only.  A softlink will not be returned. It doesn't check if the package is
# installed or not. Call function is_pkg_installed() to check before calling
# this one.
#
# Param 1: package name
# Param 2: file name to look for (file name only)
# Result is in $FILE_PATH
# Return : 0 if found; 1 if not.
#
getFilePathFromPackage()
{
  pkgname=$1
  filename=$2
  FILE_PATH=
  if [ "$OSTYPE" = "Linux" ]; then
    filepaths="`rpm -ql $pkgname | $GREP $filename$`"
  elif [ "$OSTYPE" = "SunOS" ]; then
    filepaths="`/usr/sbin/pkgchk -v $pkgname 2>&1 | $GREP $filename$`"
  else
    return 1
  fi
  [ x"$filepaths" = x"" ] && return 1

  for fp in $filepaths
  do
    if [ -f $fp -a ! -h $fp ] ; then
      FILE_PATH=$fp
      return 0
    fi
  done

  return 1
}

cleanLogConfig(){
  if [ "$NEW_INSTANCE" = "false" ]; then
    rm ${PKGDIR}/bin/am2bak
    rm ${PKGDIR}/bin/ampassword
    rm ${PKGDIR}/bin/amverifyarchive
    rm ${PKGDIR}/bin/amadmin
    rm ${PKGDIR}/bin/amserver
    rm ${PKGDIR}/bin/bak2am
    rm $CONFIG_DIR/xml/*.xml
    rm $CONFIG_DIR/ums/amserveradmin
    rm $CONFIG_DIR/ums/*.xml
    rm $CONFIG_DIR/AMConfig.properties
    rm $CONFIG_DIR/serverconfig.xml
    rm $VAR_SUBDIR/logs/* > /dev/null
    rm $VAR_SUBDIR/debug/*
  else
    if [ "$INSTANCE" != "" ];then
       rm ${PKGDIR}/bin/*.$INSTANCE
       rm -rf $CONFIG_DIR/xml/$INSTANCE
       rm $CONFIG_DIR/ums/amserveradmin.$INSTANCE
       rm $CONFIG_DIR/ums/*_$INSTANCE.xml
       rm $CONFIG_DIR/AMConfig-$INSTANCE.properties
       rm -rf $CONFIG_DIR/$INSTANCE
       rm -rf $VAR_SUBDIR/logs/$INSTANCE
       rm -rf $VAR_SUBDIR/debug/$INSTANCE
    fi
  fi
}

# since third party Web container may not be able to use jss as protocol handler,
# has to switch to jce from jss
enable_jce()
{
 cd ${CONFIG_DIR}

 if [ "$NEW_INSTANCE" = "true" ]; then
   file=AMConfig-$INSTANCE.properties
   amadmin=amadmin.$INSTANCE
 else
   file=AMConfig.properties
   amadmin=amadmin
 fi

 cat $file | sed -e "s#com.sun.identity.jss.donotInstallAtHighestPriority=false#com.sun.identity.jss.donotInstallAtHighestPriority=true#g" \
        -e "s#com.iplanet.security.SecureRandomFactoryImpl=com.iplanet.am.util.JSSSecureRandomFactoryImpl#com.iplanet.security.SecureRandomFactoryImpl=com.iplanet.am.util.SecureRandomFactoryImpl#g" \
        -e "s#com.iplanet.security.SSLSocketFactoryImpl=com.iplanet.services.ldap.JSSSocketFactory#com.iplanet.security.SSLSocketFactoryImpl=netscape.ldap.factory.JSSESocketFactory#g" \
        -e "s#com.iplanet.security.encryptor=com.iplanet.services.util.JSSEncryption#com.iplanet.security.encryptor=com.iplanet.services.util.JCEEncryption#g" > $file.temp

 cp -f $file.temp $file
 rm -f $file.temp

 cd ${PKGDIR}/bin
 sed -e 's# -D"java.protocol.handler.pkgs=com.iplanet.services.comm"##' $amadmin > $amadmin.temp
 cp -f $amadmin.temp $amadmin
 rm -f $amadmin.temp
}

determine_container_variables
if [ "$NEW_INSTANCE" = "false" ]; then
        ADMIN_CLI="${PKGDIR}/bin/amadmin"
else
        ADMIN_CLI="${PKGDIR}/bin/amadmin.$INSTANCE"
fi
export ADMIN_CLI

if [ "$OSTYPE" = "Linux" ]; then
	if [ "$BASEDIR" = "PLATFORM_DEFAULT" ]; then
		BASEDIR=/opt/sun
	fi
	PRODUCT_DIR=identity
	IS_INSTALL_VARDIR=/var/opt/sun
	IS_INSTALL_ETCDIR=/etc/opt/sun
	TR_COMMAND=/usr/bin/tr
else
	if [ "$BASEDIR" = "PLATFORM_DEFAULT" ]; then
		BASEDIR=/opt
	fi
	PRODUCT_DIR=SUNWam
	IS_INSTALL_VARDIR=/var/opt
	IS_INSTALL_ETCDIR=/etc/opt
	TR_COMMAND=/usr/xpg4/bin/tr
fi

ETC_SUBDIR=$IS_INSTALL_ETCDIR/$PRODUCT_DIR
CONFIG_DIR=$ETC_SUBDIR/config
VAR_SUBDIR=$IS_INSTALL_VARDIR/$PRODUCT_DIR

PKGDIR=${BASEDIR}/${PRODUCT_DIR}
export PKGDIR
UPGRADE61to62_XML_DIR=${PKGDIR}/migration/61to62/61to62
export UPGRADE61to62_XML_DIR
LOCALE_DIR="${PKGDIR}/locale"
export LOCALE_DIR
COOKIE_DOMAIN_LIST=$COOKIE_DOMAIN
export COOKIE_DOMAIN_LIST
FILE_ADMINPASSWD=/tmp/sun_is62_adminpasswd
export FILE_ADMINPASSWD
FILE_AMLDAPUSERPASSWD=/tmp/sun_is62_amldapuserpasswd
export FILE_AMLDAPUSERPASSWD
FILE_DS_DIRMGRPASSWD=/tmp/sun_is62_dsdirmgrpasswd
export FILE_DS_DIRMGRPASSWD
FILE_WS61_ADMINPASSWD=/tmp/sun_is62_ws61adminpasswd
export FILE_WS61_ADMINPASSWD
FILE_AS70_ADMINPASSWD=/tmp/sun_is62_as70adminpasswd
export FILE_AS70_ADMINPASSWD
FILE_AS81_ADMINPASSWD=/tmp/sun_is62_as81adminpasswd
export FILE_AS81_ADMINPASSWD
AVAILABLE_LOCALES="<Value>en_US</Value>"
export AVAILABLE_LOCALES
PRODUCTNAME="Sun Java System Access Manager 2005Q4"
export PRODUCTNAME
JSS_ROOTDIR=/
export JSS_ROOTDIR
NSS_ROOTDIR=/
export NSS_ROOTDIR
NSPR_ROOTDIR=/
export NSPR_ROOTDIR

if [ "$OSTYPE" = "Linux" ]; then
	JSS_JAR_PATH=${JSS_ROOTDIR:-/}opt/sun/private/share/lib
	JSS_SO_PATH=${JSS_ROOTDIR:-/}opt/sun/private/lib
	NSS_SO_PATH=${NSS_ROOTDIR:-/}opt/sun/private/lib
	NSPR_SO_PATH=${NSPR_ROOTDIR:-/}opt/sun/private/lib
else
	JSS_JAR_PATH=${JSS_ROOTDIR:-/}usr/share/lib/mps/secv1
	JSS_SO_PATH=${JSS_ROOTDIR:-/}usr/lib/mps/secv1
	NSS_SO_PATH=${NSS_ROOTDIR:-/}usr/lib/mps/secv1
	NSPR_SO_PATH=${NSPR_ROOTDIR:-/}usr/lib/mps/secv1
fi
JSS_JAR_FILE=$JSS_JAR_PATH/jss4.jar

export JSS_JAR_FILE
export JSS_JAR_PATH
export JSS_SO_PATH
export NSS_SO_PATH
export NSPR_SO_PATH
MISC_JAR_PATH=${JSS_ROOTDIR:-/}usr/share/lib
export MISC_JAR_PATH
USR_DIR=/usr
export USR_DIR

NormalizeDNandReplaceComma "$ROOT_SUFFIX" ","
ROOT_SUFFIX="$NMDN"
export ROOT_SUFFIX

ORG_ROOT_SUFFIX=$ROOT_SUFFIX
if [ "X$DEFAULT_ORGANIZATION" != "X" ]; then
    ORG_ROOT_SUFFIX="$DEFAULT_ORGANIZATION,$ROOT_SUFFIX"
fi


# Convert Naming Attribute and Object Classes to the 
# lower case and export
USER_NAMING_ATTR=`echo $USER_NAMING_ATTR | $TR_COMMAND '[:upper:]' '[:lower:]'`
export USER_NAMING_ATTR
ORG_NAMING_ATTR=`echo $ORG_NAMING_ATTR | $TR_COMMAND '[:upper:]' '[:lower:]'`
export ORG_NAMING_ATTR
USER_OBJECT_CLASS=`echo $USER_OBJECT_CLASS | $TR_COMMAND '[:upper:]' '[:lower:]'`
export USER_OBJECT_CLASS
ORG_OBJECT_CLASS=`echo $ORG_OBJECT_CLASS | $TR_COMMAND '[:upper:]' '[:lower:]'`
export ORG_OBJECT_CLASS





