#!/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 
    PARAMS=${#}
    if [ $PARAMS -eq 3 ]; then
	useroption=$3
    fi

    IS_SILENT_INSTALL_FILE=$2 
    export IS_SILENT_INSTALL_FILE 
else 
    echo "Please use amconfig to configure Access Manager." 
    exit 1 
fi

# Load amutil scripts
. $AMUTILS

# script specific variables

LDIF_LOCATION=${CONFIG_DIR}/ldif
DIT_LDIF=${LDIF_LOCATION}/install.ldif
INDEX_LDIF=${LDIF_LOCATION}/index.ldif
EXISTING_DIT_LDIF=${LDIF_LOCATION}/installExisting.ldif
CONFIG_LDIF=${LDIF_LOCATION}/ds_remote_schema.ldif
SCHEMA2_CONFIG_LDIF=${LDIF_LOCATION}/sunone_schema2.ldif

LDIF_UNINSTALL_FILE=${LDIF_LOCATION}/ds_remote_schema_uninstall.ldif
CLIENT_SCHEMA_LDIF=${LDIF_LOCATION}/sunAMClient_schema.ldif
CLIENT_DATA_LDIF=${LDIF_LOCATION}/sunAMClient_data.ldif



##############################################################
#
# Function - Checks whether the Access Manager dit is loaded or not.
# Accordingly sets the value for the local variable IS_DIT_LOADED
#
is_dit_loaded() {
    IS_DIT_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
    if [ "$LDAP_EXIT" = "0" ]; then
      # second call check to see if DIT is already loaded
      ${PKGDIR}/bin/ldapsearch -b "ou=DSAME Users,$ORG_ROOT_SUFFIX" -D "$DS_DIRMGRDN" -j "$FILE_DS_DIRMGRPASSWD" -h "$DS_HOST" -p "$DS_PORT" cn=dsameuser 1>/dev/null 2>&1
      LDAP_EXIT=$?
      if [ "$LDAP_EXIT" = "0" ]; then
          $ECHO "Directory Server is already loaded with Access Manager DIT."
          IS_DIT_LOADED=true
      else
        # error code 32 - object not found
        if [ "$LDAP_EXIT" = "32" ]; then
          IS_DIT_LOADED=false
        else
          # any other error code - ldap down or authentication failure
          # ldap connect failed, exit and return exit code
          if [ "$LDAP_EXIT" = "91" ] || [ "$LDAP_EXIT" = "50" ] || [ "$LDAP_EXIT" = "81" ]; then
            eval $ECHO "`$gettext 'ldapsearch failed to connect: $LDAP_EXIT'`"
          else
            eval $ECHO "`$gettext 'ldapsearch failed with error: $LDAP_EXIT'`"
          fi
          eval $ECHO "`$gettext 'Exiting the install script'`"
          cleanup $LDAP_EXIT
        fi
      fi  
    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

    export IS_DIT_LOADED
}


#############################################################
###  Description - This script loads the Access Manager 
###  Schema and the basic DIT into the Directory Server.
#############################################################

##############################################################
#
# Function - Check if common packages of Mobile Access are installed.
#

check_mobile_packages() {

   is_pkg_installed $MA_PKGNAME
   if [ $? -ne 0 ]; then 
      #
      # unset the shell variables, so that the config_tag_swap does not fail
      #
      CLIENT_SCHEMA_LDIF=""
      CLIENT_DATA_LDIF=""

      eval $ECHO "`$gettext 'ERROR : Mobile Access Package not installed: '`" ${MA_PKG}

   fi 
}

##############################################################
#
# Function - Add Access Manager schema
#
ds_config_dit_schema() {
    
    if [ "$DIRECTORY_MODE" = "4" ] || [ "$DIRECTORY_MODE" = "5" ] || [ "$IS_DIT_LOADED" = "true" ]; then
        return
    fi
    
    # try multiple times
    i=2
    fail=0
    while [ $i != 6 ]
    do
        sleep $i
        # CHECK - for existence of the ldapmodify file(${PKGDIR}/bin/ldapmodify)
        if [ ! -f ${PKGDIR}/bin/ldapmodify ]; then
            $ECHO "`$gettext 'ldapmodify tool not found at ${PKGDIR}/bin/ldapmodify'`"
            return
        fi  
            
        ${PKGDIR}/bin/ldapmodify -D "$DS_DIRMGRDN" -j "$FILE_DS_DIRMGRPASSWD" -c -a -h "$DS_HOST" -p "$DS_PORT" -f "$SCHEMA2_CONFIG_LDIF"
        ${PKGDIR}/bin/ldapmodify -D "$DS_DIRMGRDN" -j "$FILE_DS_DIRMGRPASSWD" -c -a -h "$DS_HOST" -p "$DS_PORT" -f "$CONFIG_LDIF"    

        if [ -n "${CLIENT_SCHEMA_LDIF}" ]; then
            ${PKGDIR}/bin/ldapmodify -D "$DS_DIRMGRDN" -j "$FILE_DS_DIRMGRPASSWD" -c -a -h "$DS_HOST" -p "$DS_PORT" -f "$CLIENT_SCHEMA_LDIF"    
        fi

        fail=$?
        if [ $fail = 0 ]; then 
            break
        fi 
        i=`expr $i + 1`
        eval $ECHO "sleep $i"
    done
    if [ $fail = 0 ]; then
        eval $ECHO "`$gettext 'Loading of Access Manager schema into the Directory succeeded'`"
    else
        eval $ECHO "`$gettext 'ERROR : Loading of Access Manager schema into the Directory failed'`"
    fi
}

##############################################################
#
# Function - Do tag swapping of the ldif files.
#
config_tag_swap () {

    # Cleanup variables to remove excess space and fixup 'sed'
    # variables
    NormalizeDNandReplaceComma "$ROOT_SUFFIX" "_"
if [ "$OSTYPE" = "Linux" ]; then
    replaceCharacter "People_$NMDN" "&" "\\\&"
else
    replaceCharacter "People_$NMDN" "&" "\&"
fi
    People_NM_ROOT_SUFFIX=$NEWSTR

    NormalizeDNandReplaceComma "$ORG_ROOT_SUFFIX" "_"
if [ "$OSTYPE" = "Linux" ]; then
    replaceCharacter "People_$NMDN" "&" "\\\&"
else
    replaceCharacter "People_$NMDN" "&" "\&"
fi
    People_NM_ORG_ROOT_SUFFIX=$NEWSTR

if [ "$OSTYPE" = "Linux" ]; then
    replaceCharacter "$ORG_ROOT_SUFFIX" "&" "\\\&"
else
    replaceCharacter "$ORG_ROOT_SUFFIX" "&" "\&"
fi
    NEW_ORG_ROOT_SUFFIX=$NEWSTR
    
    RS_RDN=`$ECHO $NEW_ORG_ROOT_SUFFIX | awk ' BEGIN { FS="=" } { print $2 }' | awk ' BEGIN { FS="," } { print $1 }' `
    
    # CHECK - For existence of ${JAVA_HOME}/bin/java 
    if [ ! -f ${JAVA_HOME}/bin/java ]; then
        $ECHO "`$gettext 'Java not found at ${JAVA_HOME}/bin/java'`"
        cleanup 2
    fi
    
    if [ "$NEW_INSTANCE" = "false" ]; then
        ENCLDAPUSERPASSWD=`${JAVA_HOME}/bin/java -classpath ${CLASSPATH} com.iplanet.services.util.internal.TextCrypt -f ${FILE_AMLDAPUSERPASSWD}`
    else
        ENCLDAPUSERPASSWD=`${JAVA_HOME}/bin/java -classpath ${CLASSPATH} -D"server.name=$INSTANCE" com.iplanet.services.util.internal.TextCrypt -f ${FILE_AMLDAPUSERPASSWD}`
    fi
    
      eval $ECHO "`$gettext 'Starting the tag swapping of the install.ldif and installExisting.ldif'`"
      
      eval $ECHO "`$gettext 'ROOT_SUFFIX is ${NEW_ORG_ROOT_SUFFIX}'`"
      eval $ECHO "`$gettext 'People_NM_ROOT_SUFFIX is ${People_NM_ROOT_SUFFIX}'`"
      eval $ECHO "`$gettext 'SERVER_HOST ${SERVER_HOST}'`"
      eval $ECHO "`$gettext 'DIRECTORY_SERVER ${DS_HOST}'`"
      eval $ECHO "`$gettext 'DIRECTORY_PORT ${DS_PORT}'`"
      eval $ECHO "`$gettext 'USER_NAMING_ATTR ${USER_NAMING_ATTR}'`"
      eval $ECHO "`$gettext 'ORG_NAMING_ATTR ${ORG_NAMING_ATTR}'`"
      eval $ECHO "`$gettext 'CONSOLE_DEPLOY_URI ${CONSOLE_DEPLOY_URI}'`"
      eval $ECHO "`$gettext 'ORG_OBJECT_CLASS ${ORG_OBJECT_CLASS}'`"
      eval $ECHO "`$gettext 'RS_RDN ${RS_RDN}'`"
      eval $ECHO "`$gettext 'USER_OBJECT_CLASS ${USER_OBJECT_CLASS}'`"
    
    if [ ! -f ${CLIENT_DATA_LDIF}.template ]; then
        $CP ${CLIENT_DATA_LDIF} ${CLIENT_DATA_LDIF}.template
    fi
    
    EDIT_FILES="${EXISTING_DIT_LDIF} ${DIT_LDIF} ${CLIENT_DATA_LDIF} ${INDEX_LDIF}"
    for file in $EDIT_FILES; do
        sed -e "s#\BASE_DIR#${BASEDIR}#g" \
            -e "s#\People_NM_ROOT_SUFFIX#${People_NM_ROOT_SUFFIX}#g" \
            -e "s#\People_NM_ORG_ROOT_SUFFIX#${People_NM_ORG_ROOT_SUFFIX}#g" \
            -e "s#\ORG_ROOT_SUFFIX#${NEW_ORG_ROOT_SUFFIX}#g" \
            -e "s#\ROOT_SUFFIX#${NEW_ORG_ROOT_SUFFIX}#g" \
            -e "s#\SERVER_HOST#${SERVER_HOST}#g" \
            -e "s#\DIRECTORY_SERVER#${DS_HOST}#g" \
            -e "s#\DIRECTORY_PORT#${DS_PORT}#g" \
            -e "s#\ADMINPASSWD#${ADMINPASSWD}#g" \
            -e "s#\AMLDAPUSERPASSWD#${AMLDAPUSERPASSWD}#g" \
            -e "s#\ENCLDAPUSERPASSWD#${ENCLDAPUSERPASSWD}#g" \
            -e "s#\USER_NAMING_ATTR#${USER_NAMING_ATTR}#g" \
            -e "s#\ORG_NAMING_ATTR#${ORG_NAMING_ATTR}#g" \
            -e "s#\CONSOLE_DEPLOY_URI#${CONSOLE_DEPLOY_URI}#g" \
            -e "s#\ORG_OBJECT_CLASS#${ORG_OBJECT_CLASS}#g" \
            -e "s#\RS_RDN#${RS_RDN}#g" \
            -e "s#\USER_OBJECT_CLASS#${USER_OBJECT_CLASS}#g" \
        $file.template > $file
    done
}

##############################################################
#
# Function - Add Access Manager deafult DIT
#
ds_config_dit() {

    if [ "$DIRECTORY_MODE" != "1" ] && [ "$DIRECTORY_MODE" != "2" ] ; then
        return
    fi
    if [ "$IS_DIT_LOADED" = "true" ]; then
        return
    fi
    
    #
    # try multiple times
    i=2
    fail=0
    while [ $i != 3 ]
    do
        sleep $i
        # CHECK - for existence of the ldapmodify file(${PKGDIR}/bin/ldapmodify)
        if [ ! -f ${PKGDIR}/bin/ldapmodify ]; then
            eval $ECHO "`$gettext 'ldapmodify tool not found at ${PKGDIR}/bin/ldapmodify'`"
            return
        fi
    
        if [ "$DIRECTORY_MODE" = "1" ]; then
            ${PKGDIR}/bin/ldapmodify -D "$DS_DIRMGRDN" -j "$FILE_DS_DIRMGRPASSWD" -c -a -h "$DS_HOST" -p "$DS_PORT" -f "$DIT_LDIF"
        elif [ "$DIRECTORY_MODE" = "2" ]; then 
            ${PKGDIR}/bin/ldapmodify -D "$DS_DIRMGRDN" -j "$FILE_DS_DIRMGRPASSWD" -c -a -h "$DS_HOST" -p "$DS_PORT" -f "$EXISTING_DIT_LDIF"
        fi
        
        #
        # since we are adding to the ROOT_SUFFIX & we do not have any ORG specific
        # stuff, we dont need to be aware of existing or non-existing DIT
        #
        if [ -n "${CLIENT_DATA_LDIF}" ]; then
            ${PKGDIR}/bin/ldapmodify -D "$DS_DIRMGRDN" -j "$FILE_DS_DIRMGRPASSWD" -c -a -h "$DS_HOST" -p "$DS_PORT" -f "$CLIENT_DATA_LDIF"
        fi

        fail=$?
        if [ $fail = 0 ]; then
            break
        fi
        
        # i=`expr $i + 1`
        i=3
        eval $ECHO "sleep $i"
        i=3
    done
    if [ $fail = 0 ]; then
        eval $ECHO "`$gettext 'Configuring/Loading of the default DIT in the Directory Server succeed'`"
    else
        eval $ECHO "`$gettext 'ERROR : Configuring/Loading of the default DIT in the Directory Server failed'`"
    fi

}


##############################################################
#
# Function - Remove Access Manager deafult DIT
#
ds_unconfig_dit() {
    #
    # try multiple times
    i=2
    fail=0
    
    LDAP_DELETE="/usr/bin/ldapdelete"
    DELETE_FILE="/tmp/remove.ldif"
    
    while [ $i != 3 ]
    do  
        sleep $i
        if [ "$DIRECTORY_MODE" = "1" ] || [ "$DIRECTORY_MODE" = "2" ]; then
            ${LDAP_DELETE} -D "$DS_DIRMGRDN" -j "$FILE_DS_DIRMGRPASSWD" -c -h "$DS_HOST" -p "$DS_PORT" -f ${DELETE_FILE}
        fi
        
        fail=$?
        if [ $fail = 0 ]; then 
            break
        fi
        
        #i=`expr $i + 1`
        i=3
        eval $ECHO "sleep $i"
    done
    
    if [ $fail = 0 ]; then
        eval $ECHO "`$gettext 'Deleting of the default DIT in the Directory Server succeed'`"
    else
        eval $ECHO "`$gettext 'ERROR : Deleting of the default DIT in the Directory Server failed'`"
    fi
}

##############################################################
#
# Function - Remove Access Manager schema
#
ds_unconfig_dit_schema() {
    
    # try multiple times
    i=2
    fail=0
    
    while [ $i != 6 ]
    do
        sleep $i
        # CHECK - for existence of the ldapmodify file(${PKGDIR}/bin/ldapmodify)
        if [ ! -f ${PKGDIR}/bin/ldapmodify ]; then
            eval $ECHO "`$gettext 'ldapmodify tool not found at ${PKGDIR}/bin/ldapmodify'`"
            return
        fi

        ${PKGDIR}/bin/ldapmodify -D "$DS_DIRMGRDN" -j "$FILE_DS_DIRMGRPASSWD" -c -a -h "$DS_HOST" -p "$DS_PORT" -f "$LDIF_UNINSTALL_FILE"
        
        fail=$?
        if [ $fail = 0 ]; then 
            break
        fi 
        i=`expr $i + 1`
        eval $ECHO "sleep $i"
    done
    if [ $fail = 0 ]; then
        eval $ECHO "`$gettext 'Removal of Access Manager DIT Schema from the Directory Server succeed'`"
    else
        eval $ECHO "`$gettext 'ERROR : Removal of Access Manager DIT Schema from the Directory Server FAILED !!'`"
    fi
}


##############################################################
#
# Function - Turn on Referential Integrity plugin
#
ds_config_plugin_indexes() {

    
    if [ "$DIRECTORY_MODE" != "1" ] && [ "$DIRECTORY_MODE" != "2" ]; then
        return
    fi
    if [ "$IS_DIT_LOADED" = "true" ]; then
        return
    fi
    
    #
    PLUGIN_LDIF=$CONFIG_DIR/ldif/plugin.ldif
    INDEX_LDIF=$CONFIG_DIR/ldif/index.ldif
    if [ ! -f $PLUGIN_LDIF ] || [ ! -f $INDEX_LDIF ]; then
        $ECHO "`$gettext 'plugin or index file do not exist'`"
        return
    fi  
    # try multiple times
    i=2
    fail=0
    while [ $i != 3 ]
    do
        sleep $i
        # CHECK - for existence of the ldapmodify file(${PKGDIR}/bin/ldapmodify)
        if [ ! -f ${PKGDIR}/bin/ldapmodify ]; then
            eval $ECHO "`$gettext 'ldapmodify tool not found at ${PKGDIR}/bin/ldapmodify'`"
            return
        fi
    
        ${PKGDIR}/bin/ldapmodify -D "$DS_DIRMGRDN" -j "$FILE_DS_DIRMGRPASSWD" -c -a -h "$DS_HOST" -p "$DS_PORT" -f "$PLUGIN_LDIF"
        ${PKGDIR}/bin/ldapmodify -D "$DS_DIRMGRDN" -j "$FILE_DS_DIRMGRPASSWD" -c -a -h "$DS_HOST" -p "$DS_PORT" -f "$INDEX_LDIF"
        
        fail=$?
        if [ $fail = 0 ]; then
            break
        fi
        
        # i=`expr $i + 1`
        i=3
        eval $ECHO "sleep $i"
        i=3
    done
    if [ $fail = 0 ]; then
        eval $ECHO "`$gettext 'Configuring/Loading of the Plugins and Indexes in the Directory Server succeed'`"
    else
        eval $ECHO "`$gettext 'Warning : Plugins and Indexes already exist.'`"
    fi

}

##############################################################
#
# Function - Swap back the password in ldif files
#
swapback_password_in_ldif() {

    EDIT_FILES="${EXISTING_DIT_LDIF} ${DIT_LDIF} ${CLIENT_DATA_LDIF}"
    for file in $EDIT_FILES; do
        $CP $file $file+
        sed -e "s#userPassword: $ADMINPASSWD#userPassword: SAMPLEPASSWD#g" \
            -e "s#userPassword: $AMLDAPUSERPASSWD#userPassword: SAMPLEPASSWD#g" \
        $file+ > $file
        rm -f $file+
    done
}

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

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

create_password_files

# Set required path for this script         
set_path_for_config	

if [ $PARAMS -eq 3 ]; then
  if [ "$useroption" = "loadschema" ] || [ "$useroption" = "removeschema" ] || [ "$useroption" = "loaddit" ] || [ "$useroption" = "removedit" ] || [ "$useroption" = "configplugins" ] || [ "$useroption" = "loadall" ] || [ "$useroption" = "removeall" ] || [ "$useroption" = "tagswap" ]; then
  OPTION=$useroption
  fi
fi

    if [ "$OPTION" = "" ]; then
	OPTION="loadall"
	if [ "$DIRECTORY_MODE" = "1" ]; then
	    is_dit_loaded
	elif [ "$DIRECTORY_MODE" = "2" ]; then
	    OPTION="loadschema"
	    is_dit_loaded
	elif [ "$DIRECTORY_MODE" = "3" ]; then
	    OPTION="tagswap"
	elif [ "$DIRECTORY_MODE" = "4" ]; then
	    OPTION="tagswap"
	elif [ "$DIRECTORY_MODE" = "5" ]; then
	    OPTION="tagswap"
	fi
    fi

# check that user is root
# This function is defined in amutils library
check_root_user

check_mobile_packages

# check option
if [ "$OPTION" = "loadschema" ]; then 
    # Load schema
    config_tag_swap

    ds_config_dit_schema
    ds_config_plugin_indexes
    ds_config_dit

    swapback_password_in_ldif

elif [ "$OPTION" = "loaddit" ]; then
    # do tag swapping in the default DIT
    config_tag_swap
    # Load DIT
    ds_config_dit
    swapback_password_in_ldif
    
elif [ "$OPTION" = "configplugin" ]; then
    # Configure plugins and add Indexes
    ds_config_plugin_indexes
    swapback_password_in_ldif

elif [ "$OPTION" = "loadall" ]; then
    # do tag swapping in the default DIT
    config_tag_swap

    # Load schema
    ds_config_dit_schema

    # Configure plugins and add Indexes
    ds_config_plugin_indexes

    # Load DIT
    ds_config_dit

    swapback_password_in_ldif

elif [ "$OPTION" = "removeschema" ]; then 
    # Load schema
    ds_unconfig_dit_schema
    
elif [ "$OPTION" = "removedit" ]; then 
    $ECHO "ds_unconfig_dit not yet supported"
    
elif [ "$OPTION" = "removeall" ]; then
    
    ds_unconfig_dit_schema
    $ECHO "ds_unconfig_dit not yet supported"
    
elif [ "$OPTION" = "tagswap" ]; then
    config_tag_swap
    swapback_password_in_ldif
fi

#cleanup password files and exit script 
cleanup 0

