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


if [ ${#} -eq 0 ]; then
    echo "Please use amconfig to configure Access Manager." 
    exit 1
elif [ ${#} -ge 2 -a $1 = "-s" ]; then 
    if [ ! -f $2 ]; then 
        echo Silent file not found: $2 
        exit 2
    fi 
    IS_SILENT_INSTALL_FILE=$2 
    export IS_SILENT_INSTALL_FILE 
else 
    echo "Please use amconfig to configure Access Manager." 
    exit 1
fi

. $AMUTILS

DIT_COMPLIANCE=false
DCTREE_SUFFIX=false
UM_ENABLED=true


#############################################################
###  Description - This script loads all the Access Manager 
###  Services Schema into the Directory Server.
#############################################################

get_edit_files() {
    chmod 400 ${CONFIG_DIR}/serverconfig.xml.template
    if [ "$DEPLOY_LEVEL" != "31" ]; then
       if [ "$NEW_INSTANCE" = "false" ]; then
          if [ -d ${PKGDIR}/upgrade ]; then
             UPGRADE_FILE=`/bin/ls -1 $PKGDIR/upgrade/scripts/*.xml \
                $PKGDIR/upgrade/services/*/*/*/*.*`
	     DELEGATION_FILE="${PKGDIR}/upgrade/services/99_sunAMDelegationService/s_10/premigrate.sh"
	     cp $DELEGATION_FILE $DELEGATION_FILE+
	     sed -e "s#XML_ENCODING#$XML_ENCODING#g" $DELEGATION_FILE+ > $DELEGATION_FILE
	     rm -f $DELEGATION_FILE+
 
	     AUTHCONFIG_FILE="${PKGDIR}/upgrade/services/50_iPlanetAMAuthService/20_30/postmigrate.sh"
	     cp $AUTHCONFIG_FILE $AUTHCONFIG_FILE+
	     sed -e "s#ORG_NAMING_ATTR#$ORG_NAMING_ATTR#g" $AUTHCONFIG_FILE+ > $AUTHCONFIG_FILE
	     rm -f $AUTHCONFIG_FILE+

	     AUTHCONFIG_FILE="${PKGDIR}/upgrade/services/50_iPlanetAMAuthService/20_30/process.awk"
	     cp $AUTHCONFIG_FILE $AUTHCONFIG_FILE+
	     sed -e "s#ORG_NAMING_ATTR#$ORG_NAMING_ATTR#g" $AUTHCONFIG_FILE+ > $AUTHCONFIG_FILE
	     rm -f $AUTHCONFIG_FILE+
          fi

 	 if [ -d ${PKGDIR}/migration ]; then
		ORG_FILE="${PKGDIR}/migration/update-o.pl"
	        cp $ORG_FILE $ORG_FILE+
		sed -e "s#ORG_OBJECT_CLASS#$ORG_OBJECT_CLASS#g" $ORG_FILE+ > $ORG_FILE
		rm -rf $ORG_FILE+

		USER_FILE="${PKGDIR}/migration/update-users.pl"
	        cp $USER_FILE $USER_FILE+
		sed -e "s#USER_OBJECT_CLASS#$USER_OBJECT_CLASS#g" $USER_FILE+ > $USER_FILE
		rm -rf $USER_FILE+
	 fi

          $CP ${PKGDIR}/bin/amadmin.template ${PKGDIR}/bin/amadmin
          $CP ${CONFIG_DIR}/ums/amserveradmin.template ${CONFIG_DIR}/ums/amserveradmin
          $CP ${CONFIG_DIR}/serverconfig.xml.template ${CONFIG_DIR}/serverconfig.xml
          $CP ${PKGDIR}/bin/ampassword.template ${PKGDIR}/bin/ampassword
          $CP ${CONFIG_DIR}/xml/template/*.xml ${CONFIG_DIR}/xml
          $CP ${CONFIG_DIR}/ums/ums.xml.template ${CONFIG_DIR}/ums/ums.xml
          $CP ${CONFIG_DIR}/ums/umsExisting.xml.template ${CONFIG_DIR}/ums/umsExisting.xml
          $CP ${PKGDIR}/bin/amserver.template ${PKGDIR}/bin/amserver
          $CP ${PKGDIR}/bin/am2bak.template ${PKGDIR}/bin/am2bak
          $CP ${PKGDIR}/bin/bak2am.template ${PKGDIR}/bin/bak2am
          $CP ${PKGDIR}/bin/amverifyarchive.template ${PKGDIR}/bin/amverifyarchive

          XML_FILES=`/bin/ls -1 ${CONFIG_DIR}/xml/template | $GREP -v amAuthConfig.xml`
          XML_FILES="amAuthConfig.xml $XML_FILES"
          EDIT_FILES="${PKGDIR}/bin/amadmin ${CONFIG_DIR}/ums/amserveradmin ${CONFIG_DIR}/AMConfig.properties ${CONFIG_DIR}/serverconfig.xml ${PKGDIR}/bin/ampassword $XML_FILES $ABS_REQUEST_FILES ${CONFIG_DIR}/ums/ums.xml ${CONFIG_DIR}/ums/umsExisting.xml ${PKGDIR}/bin/amserver  ${PKGDIR}/bin/am2bak ${PKGDIR}/bin/bak2am ${PKGDIR}/bin/amverifyarchive ${PKGDIR}/migration/61to62/install_61to62_upgrade.ldif ${PKGDIR}/migration/61to62/ds_remote_schema_61to62upgrade.ldif ${UPGRADE61to62_XML_FILES} $UPGRADE_FILE ${PKGDIR}/bin/ambulkfed"
        AMCONFIG="AMConfig"
      else
          INSTANCE_DIR="/$INSTANCE"
          sed -e "s#AMCFIG#AMConfig-$INSTANCE#g" ${PKGDIR}/bin/amadmin.template > ${PKGDIR}/bin/amadmin.$INSTANCE
          chmod 755 ${PKGDIR}/bin/amadmin.$INSTANCE
          $CP ${CONFIG_DIR}/ums/amserveradmin.template ${CONFIG_DIR}/ums/amserveradmin.$INSTANCE
          mkdir ${CONFIG_DIR}/$INSTANCE
          $CP ${CONFIG_DIR}/serverconfig.xml.template  ${CONFIG_DIR}/$INSTANCE/serverconfig.xml
          $CP ${PKGDIR}/bin/ampassword.template ${PKGDIR}/bin/ampassword.$INSTANCE
          mkdir ${CONFIG_DIR}/xml/$INSTANCE
          $CP ${CONFIG_DIR}/xml/template/*.xml ${CONFIG_DIR}/xml/$INSTANCE
          $CP ${CONFIG_DIR}/ums/ums.xml.template ${CONFIG_DIR}/ums/ums_$INSTANCE.xml
          $CP ${CONFIG_DIR}/ums/umsExisting.xml.template ${CONFIG_DIR}/ums/umsExisting_$INSTANCE.xml
          $CP ${PKGDIR}/bin/amserver.template ${PKGDIR}/bin/amserver.$INSTANCE
          $CP ${PKGDIR}/bin/am2bak.template ${PKGDIR}/bin/am2bak.$INSTANCE
          $CP ${PKGDIR}/bin/bak2am.template ${PKGDIR}/bin/bak2am.$INSTANCE
          $CP ${PKGDIR}/bin/amverifyarchive.template ${PKGDIR}/bin/amverifyarchive.$INSTANCE
          XML_FILES=`/bin/ls -1 ${CONFIG_DIR}/xml/template | $GREP -v amAuthConfig.xml`
          XML_FILES="amAuthConfig.xml $XML_FILES"
          EDIT_FILES="${PKGDIR}/bin/amadmin.$INSTANCE ${CONFIG_DIR}/ums/amserveradmin.$INSTANCE ${CONFIG_DIR}/AMConfig-$INSTANCE.properties ${CONFIG_DIR}/$INSTANCE/serverconfig.xml ${PKGDIR}/bin/ampassword.$INSTANCE $XML_FILES $ABS_REQUEST_FILES ${CONFIG_DIR}/ums/ums_$INSTANCE.xml ${CONFIG_DIR}/ums/umsExisting_$INSTANCE.xml ${PKGDIR}/bin/amserver.$INSTANCE ${PKGDIR}/bin/am2bak.$INSTANCE ${PKGDIR}/bin/am2bak.$INSTANCE ${PKGDIR}/bin/bak2am.$INSTANCE ${PKGDIR}/bin/amverifyarchive.$INSTANCE"
          AMCONFIG="AMConfig-$INSTANCE"
      fi
    else
       if [ "$NEW_INSTANCE" = "false" ]; then
          $CP ${PKGDIR}/bin/ampassword.template ${PKGDIR}/bin/ampassword$INSTANCE
          $CP ${CONFIG_DIR}/serverconfig.xml.template ${CONFIG_DIR}/serverconfig.xml$INSTANCE
          EDIT_FILES="${CONFIG_DIR}/AMConfig.properties ${PKGDIR}/bin/ampassword ${CONFIG_DIR}/serverconfig.xml"
          AMCONFIG="AMConfig"
       else
          $CP ${CONFIG_DIR}/AMConfig.properties.template ${CONFIG_DIR}/AMConfig-$INSTANCE.properties
          $CP ${PKGDIR}/bin/ampassword.template ${PKGDIR}/bin/ampassword.$INSTANCE
          $CP ${CONFIG_DIR}/serverconfig.xml.template ${CONFIG_DIR}/$INSTANCE/serverconfig.xml
          EDIT_FILES="${CONFIG_DIR}/AMConfig-$INSTANCE.properties ${PKGDIR}/bin/ampassword.$INSTANCE ${CONFIG_DIR}/$INSTANCE/serverconfig.xml"
          AMCONFIG="AMConfig-$INSTANCE"
       fi
    fi

}


##############################################################
#
# Tag swap of all the service Schema XML files and also the 
# AMConfig.properties file
#
config_tag_swap() {
    #
    # determine fc urls necessary.  if port is default port, then add another 
    # rule that does not include the port
    #
    FCURLS="<Val>$SERVER_PROTOCOL://$SERVER_HOST:$SERVER_PORT</Val>"
    if [ "$SERVER_PORT" = "80" ] && [ "$SERVER_PROTOCOL" = "http" ]; then
    	FCURLS="$FCURLS<Val>$SERVER_PROTOCOL://$SERVER_HOST</Val>"
    elif [ "$SERVER_PORT" = "443" ] && [ "$SERVER_PROTOCOL" = "https" ]; then
    	FCURLS="$FCURLS<Val>$SERVER_PROTOCOL://$SERVER_HOST</Val>"
    fi
    
    GROUP_TYPE="dynamic"
    # CHECK - For existence of ${JAVA_HOME}/bin/java 
    if [ ! -f ${JAVA_HOME}/bin/java ]; then
        eval $ECHO "`$gettext 'Java not found at ${JAVA_HOME}/bin/java'`"
        cleanup 2
    fi
    ORG_BASE=$ORG_ROOT_SUFFIX
    SERV_LIST=$SERVER_PROTOCOL://$SERVER_HOST:$SERVER_PORT
    server_url=$SERVER_PROTOCOL://$SERVER_HOST:$SERVER_PORT
    WSVR_INSTANCE="https-${SERVER_HOST}"
    PROFILE_HOST=$SERVER_HOST
    PROFILE_PORT=$SERVER_PORT
    session_url=%protocol://%host:%port
    profileservice_url=$SERVER_PROTOCOL://$PROFILE_HOST:$PROFILE_PORT
    loggingservice_url=$SERVER_PROTOCOL://$PROFILE_HOST:$PROFILE_PORT
    serverservice_url=$SERVER_PROTOCOL://$SERVER_HOST:$SERVER_PORT
    notification_url=$SERVER_PROTOCOL://$SERVER_HOST:$SERVER_PORT$SERVER_DEPLOY_URI/notificationservice
    SAMLSITEID=`${JAVA_HOME}/bin/java -classpath ${CLASSPATH}:${PKGDIR}/lib/xercesImpl.jar:${PKGDIR}/lib/sax.jar:${PKGDIR}/lib/dom.jar com.sun.identity.saml.common.SAMLSiteID ${SERV_LIST}`
    HASHADMINPASSWD=`${JAVA_HOME}/bin/java -classpath ${CLASSPATH} com.iplanet.services.util.Hash -f ${FILE_ADMINPASSWD}`
    HASHLDAPUSERPASSWD=`${JAVA_HOME}/bin/java -classpath ${CLASSPATH} com.iplanet.services.util.Hash -f ${FILE_AMLDAPUSERPASSWD}`

    if [ "x$PAM_SERVICE_NAME" = "x" ]; then
      if [ "$OSTYPE" = "Linux" ]; then
        PAM_SERVICE_NAME="password"
      else
        PAM_SERVICE_NAME="other"
      fi
    fi
# Begin PORTALMA. This is a generic change which allows request files to be put 
#  in CONFIG_DIR/request directory. These data files will be imported using 
#  amadmin --data. 
    REQUEST_DIR=${CONFIG_DIR}/request
    if [ -d $REQUEST_DIR ]; then
	    $CP $REQUEST_DIR/defaultDelegationPolicies.xml.template $REQUEST_DIR/defaultDelegationPolicies.xml
	    $CP $REQUEST_DIR/idRepoDefaults.xml.template $REQUEST_DIR/idRepoDefaults.xml
	    REQUEST_FILES=`/bin/ls -1 ${REQUEST_DIR}/*.xml`
	    for file in $REQUEST_FILES; do
		ABS_REQUEST_FILES="$ABS_REQUEST_FILES $file"
	    done
    else
    	    REQUEST_FILES=""
	    ABS_REQUEST_FILES=""
    fi

# End PORTALMA

    UPGRADE61to62_XML_FILES=`/bin/ls -1 ${UPGRADE61to62_XML_DIR}/*.xml`
    
    if [ "$NEW_INSTANCE" = "false" ]; then
      ENCADMINPASSWD=`${JAVA_HOME}/bin/java -classpath ${CLASSPATH} com.iplanet.services.util.internal.TextCrypt -f ${FILE_ADMINPASSWD}`
      ENCLDAPUSERPASSWD=`${JAVA_HOME}/bin/java -classpath ${CLASSPATH} com.iplanet.services.util.internal.TextCrypt -f ${FILE_AMLDAPUSERPASSWD}`

      if [ "$DIRECTORY_MODE" = "1" ]; then
          UMS_XML=${CONFIG_DIR}/ums/ums.xml
      else
          UMS_XML=${CONFIG_DIR}/ums/umsExisting.xml
      fi
    else
      ENCADMINPASSWD=`${JAVA_HOME}/bin/java -classpath ${CLASSPATH} -D"amconfig=AMConfig-$INSTANCE"  com.iplanet.services.util.internal.TextCrypt -f ${FILE_ADMINPASSWD}`
      ENCLDAPUSERPASSWD=`${JAVA_HOME}/bin/java -classpath ${CLASSPATH} -D"server.name=$INSTANCE" com.iplanet.services.util.internal.TextCrypt -f ${FILE_AMLDAPUSERPASSWD}`
      if [ "$DIRECTORY_MODE" = "1" ]; then
          UMS_XML=${CONFIG_DIR}/ums/ums_$INSTANCE.xml
      else
          UMS_XML=${CONFIG_DIR}/ums/umsExisting_$INSTANCE.xml
      fi
    fi

    DEFAULTORG=$ORG_ROOT_SUFFIX
    NormalizeDNandReplaceComma "$ROOT_SUFFIX" "^"
if [ "$OSTYPE" = "Linux" ]; then
    replaceCharacter "$NMDN" "&" "\\\&amp;"
else
    replaceCharacter "$NMDN" "&" "\&amp;"
fi
    ROOT_SUFFIX_HAT=$NEWSTR

    NormalizeDNandReplaceComma "$ROOT_SUFFIX" "_"
    NM_ROOT_SUFFIX="$NMDN"
    NormalizeDNandReplaceComma "$DEFAULTORG" "_"
    NM_INST_ORGANIZATION="$NMDN"
    NM_ORG_ROOT_SUFFIX="$NMDN"
    VERSION="7 2005Q4 patch1 (Wed Dec 21 15:47:43 2005) SunOS"
#    NORMALIZED_RS=`echo $ROOT_SUFFIX | sed -e "s#\&#\\&amp;#g" -e "s#'#\&apos;#g" -e "s#\"#\&quot;#g" -e "s#<#\&lt;#g" -e "s#>#\&gt;#g"`

if [ "$OSTYPE" = "Linux" ]; then
    replaceCharacter "$ROOT_SUFFIX" "&" "\\\&amp;"
    replaceCharacter "$NEWSTR" "'" "\\\&apos;"
    replaceCharacter "$NEWSTR" '"' "\\\&quot;"
    replaceCharacter "$NEWSTR" "<" "\\\&lt;"
    replaceCharacter "$NEWSTR" ">" "\\\&gt;"
else
    replaceCharacter "$ROOT_SUFFIX" "&" "\&amp;"
    replaceCharacter "$NEWSTR" "'" "\&apos;"
    replaceCharacter "$NEWSTR" '"' "\&quot;"
    replaceCharacter "$NEWSTR" "<" "\&lt;"
    replaceCharacter "$NEWSTR" ">" "\&gt;"
fi
    NORMALIZED_RS=$NEWSTR

#  NORMALIZED_DEFAULTORG=`echo $DEFAULTORG | sed -e "s#\&#\\&amp;#g" -e "s#'#\&apos;#g" -e "s#\"#\&quot;#g" -e "s#<#\&lt;#g" -e "s#>#\&gt;#g"`
if [ "$OSTYPE" = "Linux" ]; then
    replaceCharacter "$DEFAULTORG" "&" "\\\&amp;"
    replaceCharacter "$NEWSTR" "'" "\\\&apos;"
    replaceCharacter "$NEWSTR" '"' "\\\&quot;"
    replaceCharacter "$NEWSTR" "<" "\\\&lt;"
    replaceCharacter "$NEWSTR" ">" "\\\&gt;"
else
    replaceCharacter "$DEFAULTORG" "&" "\&amp;"
    replaceCharacter "$NEWSTR" "'" "\&apos;"
    replaceCharacter "$NEWSTR" '"' "\&quot;"
    replaceCharacter "$NEWSTR" "<" "\&lt;"
    replaceCharacter "$NEWSTR" ">" "\&gt;"
fi
    NORMALIZED_DEFAULTORG=$NEWSTR

if [ "$OSTYPE" = "Linux" ]; then
    replaceCharacter "$DEFAULTORG" "&" "\\\&"
else
    replaceCharacter "$DEFAULTORG" "&" "\&"
fi
    NORMAL_ORG=$NEWSTR

    RS_RDN=`echo $ORG_ROOT_SUFFIX | awk 'BEGIN { FS="=" } { print $2 }' | awk 'BEGIN { FS="," } { print $1 }' `
if [ "$OSTYPE" = "Linux" ]; then
    replaceCharacter "$RS_RDN" "&" "\\\&amp;"
    replaceCharacter "$NEWSTR" "'" "\\\&apos;"
    replaceCharacter "$NEWSTR" '"' "\\\&quot;"
    replaceCharacter "$NEWSTR" "<" "\\\&lt;"
    replaceCharacter "$NEWSTR" ">" "\\\&gt;"
else
    replaceCharacter "$RS_RDN" "&" "\&amp;"
    replaceCharacter "$NEWSTR" "'" "\&apos;"
    replaceCharacter "$NEWSTR" '"' "\&quot;"
    replaceCharacter "$NEWSTR" "<" "\&lt;"
    replaceCharacter "$NEWSTR" ">" "\&gt;"
fi
    RS_RDN=$NEWSTR

    if [ -z "$XML_ENCODING"  ];then 
    	TANS=`${JDK_BASE_DIR}/bin/java -classpath ${CLASSPATH} com.iplanet.am.util.getEncoding -http | awk ' { print $4 }' `
    	if [ "$TANS" != "" ]; then
    		XML_ENCODING=$TANS
    	else
    		XML_ENCODING="UTF-8"
    	fi
    	eval $ECHO "`$gettext 'XML Encoding is not set.found automatically to $XML_ENCODING'`"
    fi
    
    get_edit_files

    if [ "$NEW_INSTANCE" = "false" ]; then
        cd ${CONFIG_DIR}/xml
	LOG_DIR=logs
	DEBUG_SUBDIR=debug
    else
        cd ${CONFIG_DIR}/xml/$INSTANCE
	LOG_DIR=logs/$INSTANCE
	DEBUG_SUBDIR=debug/$INSTANCE
    fi
    if [ "$AM_REALM" = "enabled" ]; then
        REALM_MODE=true
        COEXIST_MODE=false
        AMSDK_I18N_KEY=a101
    else
        REALM_MODE=false
        COEXIST_MODE=true
	XML_COMMENT_START="<!--"
	XML_COMMENT_END="-->"
    fi
   
    # Seding start 
    for file in $EDIT_FILES; do
      $CP $file $file+
      sed -e "s#PLATDIR#$BASEDIR#g" \
       -e "s#\${DPRO_BASEDIR}#${BASEDIR}#g" \
       -e "s#\${BASE_DIR}#${BASEDIR}#g" \
       -e "s#\${JDK_BASE_DIR}#${JAVA_HOME}#g" \
       -e "s#\${PRODUCT_DIR}#${PRODUCT_DIR}#g" \
       -e "s#NORMALIZED_RS#$NORMALIZED_RS#g" \
       -e "s#NORMALIZED_ORGBASE#$NORMALIZED_DEFAULTORG#g" \
       -e "s#PKGDIR#${PKGDIR}#g" \
       -e "s#TEMP_DIR_PREFIX#${TEMP_DIR_PREFIX}#g" \
       -e "s#DEBUG_DIR_PREFIX#${DEBUG_DIR_PREFIX}#g" \
       -e "s#CONFIG_DIR#${CONFIG_DIR}#g" \
       -e "s#JDK_PATH#${JAVA_HOME}#g" \
       -e "s#WEBSERVER_HOST#$WEBSERVER_HOST#g" \
       -e "s#SERVER_URL#$server_url#g" \
       -e "s#SERVER_HOST#$SERVER_HOST#g" \
       -e "s#SERVER_PORT#$SERVER_PORT#g" \
       -e "s#CONSOLE_HOST#$CONSOLE_HOST#g" \
       -e "s#CONSOLE_PORT#$CONSOLE_PORT#g" \
       -e "s#SERVER_PROTO#$SERVER_PROTOCOL#g" \
       -e "s#CONSOLE_PROTO#$CONSOLE_PROTOCOL#g" \
       -e "s#SERVER_DEPLOY_URI#$SERVER_DEPLOY_URI#g" \
       -e "s#CONSOLE_DEPLOY_URI#$CONSOLE_DEPLOY_URI#g" \
       -e "s#OLDCON_DEPLOY_URI#\/console#g" \
       -e "s#PASSWORD_DEPLOY_URI#$PASSWORD_DEPLOY_URI#g" \
       -e "s#COMMON_DEPLOY_URI#$COMMON_DEPLOY_URI#g" \
       -e "s#CONSOLE_REMOTE#$CONSOLE_REMOTE#g" \
       -e "s#BASEDIR#$BASEDIR#g" \
       -e "s#HOST_NAME#$HOST_NAME#g" \
       -e "s#FULLHOSTNAME#$SERVER_HOST#g" \
       -e "s#PRODUCT_DIR#$PRODUCT_DIR#g" \
       -e "s#AM_REALM#$REALM_MODE#g" \
       -e "s#AM_COEXIST#$COEXIST_MODE#g" \
       -e "s#AMSDK_I18N_KEY#$AMSDK_I18N_KEY#g" \
       -e "s#XML_COMMENT_START#$XML_COMMENT_START#g" \
       -e "s#XML_COMMENT_END#$XML_COMMENT_END#g" \
       -e "s#DIT_COMPLIANCE#$DIT_COMPLIANCE#g" \
       -e "s#ROOT_SUFFIX_HAT#$ROOT_SUFFIX_HAT#g" \
       -e "s#NM_ROOT_SUFFIX#$NM_ROOT_SUFFIX#g" \
       -e "s#NM_ORG_ROOT_SUFFIX#$NM_ORG_ROOT_SUFFIX#g" \
       -e "s#ORG_ROOT_SUFFIX#$NORMALIZED_DEFAULTORG#g" \
       -e "s#ROOT_SUFFIX#$NORMALIZED_RS#g" \
       -e "s#RS_RDN#$RS_RDN#g" \
       -e "s#ORG_BASE#$NORMAL_ORG#g" \
       -e "s#DCTREE_SUFFIX#$DCTREE_SUFFIX#g" \
       -e "s#GROUP_TYPE#$GROUP_TYPE#g" \
       -e "s#NM_INST_ORGANIZATION#$NM_INST_ORGANIZATION#g" \
       -e "s#INST_ORGANIZATION#$NORMAL_ORG#g" \
       -e "s#\${DIRECTORY_PORT}#${DS_PORT}#g" \
       -e "s#\${DIRECTORY_SERVER}#${DS_HOST}#g" \
       -e "s#DIRECTORY_PORT#${DS_PORT}#g" \
       -e "s#DIRECTORY_SERVER#${DS_HOST}#g" \
       -e "s#SIMPLE_HOST#$DS_HOST#g" \
       -e "s#ENCLDAPUSERPASSWD#$ENCLDAPUSERPASSWD#g" \
       -e "s#HASHLDAPUSERPASSWD#$HASHLDAPUSERPASSWD#g" \
       -e "s#AMLDAPUSERPASSWD#$AMLDAPUSERPASSWD#g" \
       -e "s#ENCADMINPASSWD#$ENCADMINPASSWD#g" \
       -e "s#HASHADMINPASSWD#$HASHADMINPASSWD#g" \
       -e "s#ADMINPASSWD#$ADMINPASSWD#g" \
       -e "s#PROXUUSERPASSWORD#$ADMINPASSWD#g" \
       -e "s#INST_SERV_LIST#$SERV_LIST#g" \
       -e "s#INST_COOKIE_DOMAIN_LIST#$COOKIE_DOMAIN_LIST#g" \
       -e "s#SAML_SITEID#$SAMLSITEID#g" \
       -e "s#SERVER_URL#$serverservice_url#g" \
       -e "s#PROFILE_URL#$profileservice_url#g" \
       -e "s#SESSION_URL#$session_url#g" \
       -e "s#LOGGING_URL#$loggingservice_url#g" \
       -e "s#NOTIFICATION_URL#$notification_url#g" \
       -e "s#PROFILE_HOST#$SERVER_HOST#g" \
       -e "s#PROFILE_PORT#$SERVER_PORT#g" \
       -e "s#DPRO_VERSION#$VERSION#g" \
       -e "s#CURRENT_PLATFORM_LOCALE#$PLATFORM_LOCALE#g" \
       -e "s#AVAILABLE_LOCALES#$AVAILABLE_LOCALES#g" \
       -e "s#XML_ENCODING#$XML_ENCODING#g" \
       -e "s#PLATFORM_LOCALE#$PLATFORM_LOCALE#g" \
       -e "s#UM_ENABLED#$UM_ENABLED#g" \
       -e "s#ORG_OBJECT_CLASS#$ORG_OBJECT_CLASS#g" \
       -e "s#ORG_NAMING_ATTR#$ORG_NAMING_ATTR#g" \
       -e "s#USER_NAMING_ATTR#$USER_NAMING_ATTR#g" \
       -e "s#USER_OBJECT_CLASS#$USER_OBJECT_CLASS#g" \
       -e "s#PRIMARY_NAMING_URL#$profileservice_url$SERVER_DEPLOY_URI/namingservice#g" \
       -e "s#PRIMARY_LOGIN_URL#$profileservice_url$SERVER_DEPLOY_URI/UI/Login#g" \
       -e "s#SHARED_SECRET#$ENCLDAPUSERPASSWD#g" \
       -e "s#FAILOVER_NAMING_URL##g" \
       -e "s#FAILOVER_LOGIN_URL##g" \
       -e "s#WEB_CONTAINER_TAG#$WEB_CONTAINER#g" \
       -e "s#NEW_OWNER#$NEW_OWNER#g" \
       -e "s#NEW_GROUP#$NEW_GROUP#g" \
       -e "s#JSSHOME#$JSSHOME#g" \
       -e "s#NSSHOME#$NSSHOME#g" \
       -e "s#WS_BASE_DIR#$WS61_HOME#g" \
       -e "s#WEBSVR_INSTANCE#$WS61_HOME#g" \
       -e "s#WSVR_INSTANCE#$WSVR_INSTANCE#g" \
       -e "s#NSPRHOME#$NSPRHOME#g" \
       -e "s#JAXPHOME#$JAXP_JAR_PATH#g" \
       -e "s#JAXP_LIB_DIR#$JAXP_JAR_PATH#g" \
       -e "s#JAVA_COMPONENT_PACKAGES#$JAVA_COMPONENT_PACKAGES#g" \
       -e "s#PAM_SERVICE_NAME#$PAM_SERVICE_NAME#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_PATH}#g" \
       -e "s#TAG_JSS_JAR_PATH#${JSS_JAR_PATH}#g" \
       -e "s#TAG_NSS_SO_PATH#${NSS_PATH}#g" \
       -e "s#TAG_NSPR_SO_PATH#${NSPR_PATH}#g" \
       -e "s#AMCONFIG#$AMCONFIG#g" \
       -e "s#LOG_DIR#$LOG_DIR#g" \
       -e "s#DEBUG_SUBDIR#$DEBUG_SUBDIR#g" \
       $file+ > $file
      rm -f $file+
    done

    if [ "$ORG_NAMING_ATTR" != "o" ];then
      replace_line "$PKGDIR/locale/amEntrySpecific.properties" "o=Name" "$ORG_NAMING_ATTR=Name"
    fi
}

##############################################################
#
# Function - Checks whether the Access Manager Service schemas are loaded or not.
# Accordingly sets the value for the local variable IS_SERVICE_LOADED
#
is_service_loaded() {
    IS_SERVICE_LOADED=false
    if [ ! -f ${PKGDIR}/bin/ldapsearch ]; then
        eval $ECHO "`$gettext 'ldapsearch tool not found at ${PKGDIR}/bin/ldapsearch'`"
        eval $ECHO "`$gettext 'Exiting the install script'`"
        cleanup 2
    fi
    # First call verifies that we can connect or gives error code
    ${PKGDIR}/bin/ldapsearch -b "$ORG_ROOT_SUFFIX" -D "$DS_DIRMGRDN" -j "$FILE_DS_DIRMGRPASSWD" -h "$DS_HOST" -p "$DS_PORT" "$ORG_ROOT_SUFFIX" 1>/dev/null 2>&1
    LDAP_EXIT=$?
    if [ "$LDAP_EXIT" = "32" ]; then
      eval $ECHO "`$gettext 'Unable to connect to Directory Server at $ORG_ROOT_SUFFIX'`"
      eval $ECHO "`$gettext 'Exiting the install script'`"
      cleanup $LDAP_EXIT
    fi

    # Then check if DIT is loaded
    ${PKGDIR}/bin/ldapsearch -b "$ORG_ROOT_SUFFIX" -D "$DS_DIRMGRDN" -j "$FILE_DS_DIRMGRPASSWD" -h "$DS_HOST" -p "$DS_PORT" ou=DAI 1>/dev/null 2>&1
    LDAP_EXIT=$?
    if [ "$LDAP_EXIT" = "0" ]; then
      # DIT was loaded so now we grab the data
      DAI_SERVICE=`${PKGDIR}/bin/ldapsearch -b "$ORG_ROOT_SUFFIX" -D "$DS_DIRMGRDN" -j "$FILE_DS_DIRMGRPASSWD" -h "$DS_HOST" -p "$DS_PORT" ou=DAI `
    else
      # ldap connect failed, exit and return exit code
      eval $ECHO "`$gettext 'ldapsearch failed with error: $LDAP_EXIT'`"
      eval $ECHO "`$gettext 'Exiting the install script'`"
      cleanup $LDAP_EXIT
    fi

    if [ "$DAI_SERVICE" != "" ]; then
        $ECHO "Directory Server is already loaded with Access Manager Service Schema."
        IS_SERVICE_LOADED=true
    fi
    export IS_SERVICE_LOADED
}


##############################################################
#
# Load schema. Import services. Replace ${AMLDAPUSERPASSWD} with blank
#
load_schema() {

    if [ "$IS_SERVICE_LOADED" = "true" ]; then
        return
    fi
    
    eval $ECHO "`$gettext 'Loading service schema XML files ...'`"

    for file in $XML_FILES; do
	if [ "$DIT_COMPLIANCE" = "true" ]; then
	    if [ "$file" != "amEntrySpecific.xml" ] && [ "$file" != "amAdminConsole.xml" ]; then
                SXML_FILES="$SXML_FILES ${CONFIG_DIR}/xml/$INSTANCE_DIR/$file"
	    fi
	else
	    if [ "$file" != "amEntrySpecificCompliant.xml" ] && [ "$file" != "amAdminConsoleCompliant.xml" ]; then
                SXML_FILES="$SXML_FILES ${CONFIG_DIR}/xml/$INSTANCE_DIR/$file"
	    fi
	fi
    done

    OPTIONS='-Dcom.sun.identity.sm.enableDataStoreNotification=true -DinstallTime=true' \
    $ADMIN_CLI --runasdn "$USER_NAMING_ATTR=amAdmin,ou=People,$ORG_BASE" -f "$FILE_ADMINPASSWD" -v --nolog --schema ${UMS_XML}
    
    if [ $? -ne 0 ]; then
        eval $ECHO "`$gettext 'Error occured while loading: ${UMS_XML}'`"
       	cleanup 1
    else
       	eval $ECHO "`$gettext 'Successfully loaded: ${UMS_XML}'`"
    fi
    
    OPTIONS='-Dcom.sun.identity.sm.enableDataStoreNotification=true -DinstallTime=true' \
    $ADMIN_CLI --runasdn "$USER_NAMING_ATTR=amAdmin,ou=People,$ORG_BASE" -f "$FILE_ADMINPASSWD" -v --nolog --schema $SXML_FILES
        
    if [ $? -ne 0 ]; then
        eval $ECHO "`$gettext 'Error occured while loading: $file'`"
       	cleanup 1
    else
       	eval $ECHO "`$gettext 'Successfully loaded: $file'`"
    fi

    for file in $SXML_FILES; do
	$CP $file $file+
	sed -e "s#$AMLDAPUSERPASSWD##g" \
            -e "s#$ADMINPASSWD##g" \
            -e "s#$HASHADMINPASSWD##g" \
            -e "s#$HASHLDAPUSERPASSWD##g" \
           $file+ > $file
        rm $file+
    done

    eval $ECHO "`$gettext 'Done loading service schema XML files.'`"
}


##############################################################
#
# Load schema. Import services
#
remove_schema() {

    SERVICE_NAMES="iPlanetAMAdminConsoleService \
            iPlanetAMAgentService \
            iPlanetAMAuthService \
            iPlanetAMAuthAnonymousService \
            iPlanetAMAuthCertService \
            iPlanetAMAuthConfiguration \
            iPlanetAMAuthHTTPBasicService \
            iPlanetAMAuthLDAPService \
            iPlanetAMAuthMembershipService \
            iPlanetAMAuthNTService \
            iPlanetAMAuthRadiusService \
            iPlanetAMAuthSafeWordService \
            iPlanetAMAuthSecurIDService \
            iPlanetAMAuthUnixService \
            iPlanetAMAuthWindowsDesktopSSOService \
            iPlanetAMAuthenticationDomainConfigService \
            SunAMClientData \
            sunIdentityServerDiscoveryService \
            iPlanetAMClientDetection \
            iPlanetAMEntrySpecificService \
            iPlanetG11NSettings \
            sunIdentityServerLibertyPPService \
            iPlanetAMLoggingService \
            iPlanetAMNamingService \
            iPlanetAMPasswordResetService \
            iPlanetAMPlatformService \
            iPlanetAMPolicyService \
            iPlanetAMPolicyConfigService \
            iPlanetAMProviderConfigService \
            iPlanetAMSAMLService \
            sunIdentityServerSOAPBinding \
            iPlanetAMSessionService \
            iPlanetAMUserService \
            iPlanetAMWebAgentService \
            sunIdentityLocaleService \
            DAI"
    
    ORG_BASE=$ORG_ROOT_SUFFIX
    
    ans="n" 
    for service_name in $SERVICE_NAMES; do
        $ECHO
        eval $ECHO "`$gettext '**********Going to remove the service :- $service_name **********'`"
        OPTIONS='-DinstallTime=true' \
        $ADMIN_CLI --runasdn "$USER_NAMING_ATTR=amAdmin,ou=People,$ORG_BASE" --password "$ADMINPASSWD" -v --nolog -r $service_name
	if [ $? -ne 0 ]; then
                eval $ECHO "`$gettext 'Error occured while removing the service:- $service_name'`"
                if [ "$ans" != y ]; then
                    $ECHO
                    $ECHO "`$gettext 'Do you want to continue trying to remove services y/[n] ?'`"
                    read ans
                    if [ "$ans" != "y" ]; then
                        cleanup 1
                    fi
                fi
	else
		eval $ECHO "`$gettext '**********Successfully removed the service :- $service_name **********'`"
                
	fi
    done
}

# Begin PORTALMA. This is a generic change which allows request files to be put 
#  in CONFIG_DIR/request directory. These data files will be imported using 
#  amadmin --data. 

##############################################################
#
# Modify services. 
#
modify_services(){
        
        if [ "$IS_SERVICE_LOADED" = "true" ]; then
            return
        fi

	if [ "$ABS_REQUEST_FILES" != "" ]; then
		eval $ECHO "`$gettext 'Modifying services using request XML files ...'`"

		OPTIONS='-Dcom.sun.identity.sm.enableDataStoreNotification=true -DinstallTime=true' \
		$ADMIN_CLI --runasdn "$USER_NAMING_ATTR=amAdmin,ou=People,$ORG_BASE" -f "$FILE_ADMINPASSWD" -v --nolog --data ${ABS_REQUEST_FILES}
	
		if [ $? -ne 0 ]; then
			eval $ECHO "`$gettext 'Error occured while loading: $ABS_REQUEST_FILES'`"
			cleanup 1
		else
			eval $ECHO "`$gettext 'Successfully loaded: $ABS_REQUEST_FILES'`"
		fi
		eval $ECHO "`$gettext 'Done modifying services using request XML files.'`"
	fi
	eval $ECHO "`$gettext 'No request XML files found.'`"

}

# End PORTALMA

##############################################################
#
# Function - Cleanup before exiting script
#
cleanup() {
  delete_password_files
  exit $1
}

##############################################################
#
#           MAIN - STARTING MAIN ROUTINE
#

# check that user is root
# This function is defined in common.lib library
check_root_user

create_password_files

# Set required path for this script
set_path_for_config

OPTION=$3
if [ "$OPTION" = "" ]; then
    if [ "$DIRECTORY_MODE" = "1" ] || [ "$DIRECTORY_MODE" = "2" ]; then
	OPTION="load"
    else
	OPTION="tagswap"
    fi
fi

if [ "$OPTION" = "remove" ]; then
    remove_schema
elif [ "$OPTION" = "load" ]; then
    config_tag_swap
    # Load services irrespective of the DIRECTORY_MODE
    is_service_loaded
    load_schema

    # Begin PORTALMA. This is a generic change which allows request files to be put
    #  in CONFIG_DIR/request directory. These data files will be imported using
    #  amadmin --data.
    # Modify Services
    modify_services
    # End PORTALMA
elif [ "$OPTION" = "tagswap" ]; then
    config_tag_swap
fi

cleanup 0
