#!/bin/sh

# Copyright © 2004 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, the Sun logo, Java and Sun[tm] ONE are trademarks or
# registered trademarks of Sun Microsystems, Inc. in the U.S. and other
# countries. 
# 
# Copyright © 2004 Sun Microsystems, Inc. Tous droits réservés. Sun
# Microsystems, Inc. détient les droits de propriété intellectuels relatifs
# à la technologie incorporée dans le produit qui est décrit dans ce document.
# En particulier, et ce sans limitation, ces droits de propriété
# intellectuelle peuvent inclure un ou plus des brevets américains listés
# à l'adresse http://www.sun.com/patents et un ou les brevets supplémentaires
# 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 développés par des
# tierces parties.
# 
# Sun, Sun Microsystems, le logo Sun, Java et Sun[tm] ONE sont des marques
# de fabrique ou des marques déposées de Sun Microsystems, Inc. aux
# Etats-Unis et dans d'autres pays.


###########################################################
# Finds amutils and sources it. This function is identical
# in all scripts. Any changes made here need to made in
# other scripts too.
source_amutils()
{
	# Try to guess the location of amutils
	if [ "$BASEDIR" != "" -a "$PRODUCT_DIR" != "" -a -f $BASEDIR/$PRODUCT_DIR/bin/amutils ]; then
		AMUTILS=$BASEDIR/$PRODUCT_DIR/bin/amutils
	elif [ "$BASEDIR" != "" -a "$PRODUCT_DIR" != "" -a -f $BASEDIR/$PRODUCT_DIR/share/bin/amutils ]; then
		AMUTILS=$BASEDIR/$PRODUCT_DIR/share/bin/amutils
	elif [ -f ./amutils ]; then
		AMUTILS=./amutils
	elif [ -f `dirname $0`/amutils ]; then
		AMUTILS=`dirname $0`/amutils
	elif [ -f /opt/SUNWam/bin/amutils ]; then
		AMUTILS=/opt/SUNWam/bin/amutils
	elif [ -f /opt/SUNWam/share/bin/amutils ]; then
		AMUTILS=/opt/SUNWam/share/bin/amutils ]
	elif [ -f /opt/sun/identity/bin/amutils ]; then
		AMUTILS=/opt/sun/identity/bin/amutils
	elif [ -f /opt/sun/identity/share/bin/amutils ]; then
		AMUTILS=/opt/sun/identity/share/bin/amutils ]
	else
		echo "$0: FATAL: Could not find amutils. Exiting."
		exit 1
	fi

	# Source it!
	echo "$0: Sourcing $AMUTILS"
	. $AMUTILS
}

if [ ${#} -eq 0 ]; then
	INSTALL_FILE_NOT_REQUIRED=true
	source_amutils
	do_interactive
	set -- -s $IS_SILENT_INSTALL_FILE
	INSTALL_FILE_NOT_REQUIRED=false
elif [ $1 = "-s" ]; then 
    if [ ! -f $2 ]; then 
        echo Silent file not found: $2 
        exit 
    fi 
    IS_SILENT_INSTALL_FILE=$2 
    export IS_SILENT_INSTALL_FILE 
else 
    echo "Usage: amdsconfig [ -s <silent> ]" 
    exit 
fi

source_amutils

# script specific variables

LDIF_LOCATION=${CONFIG_DIR}/ldif
DIT_LDIF=${LDIF_LOCATION}/install.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

#############################################################
###  Description - This script loads the Identity Server 
###  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 Identity Server 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 Identity Server schema into the Directory succeeded'`"
    else
        eval $ECHO "`$gettext 'ERROR : Loading of Identity Server schema into the Directory failed'`"
    fi
}

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

    NormalizeDNandReplaceCommaWith_ "$ROOT_SUFFIX"
    People_NM_ROOT_SUFFIX=People_${NMDN}
    
    NormalizeDNandReplaceCommaWith_ "$ORG_ROOT_SUFFIX"
    People_NM_ORG_ROOT_SUFFIX=People_${NMDN}
    
    RS_RDN=`$ECHO $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'`"
        return
    fi
    
    ENCLDAPUSERPASSWD=`${JAVA_HOME}/bin/java -classpath ${CLASSPATH} com.iplanet.services.util.internal.TextCrypt -f ${FILE_AMLDAPUSERPASSWD}`
    
      eval $ECHO "`$gettext 'Starting the tag swapping of the install.ldif and installExisting.ldif'`"
      
      eval $ECHO "`$gettext 'ROOT_SUFFIX is ${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}'`"
    
      escape_string_all $AMLDAPUSERPASSWD
      ESCAPED_AMLDAPUSERPASSWD=$x3
      escape_string_all $ADMINPASSWD
      ESCAPED_ADMINPASSWD=$x3
    
    EDIT_FILES="${EXISTING_DIT_LDIF} ${DIT_LDIF} ${CLIENT_DATA_LDIF}"
    for file in $EDIT_FILES; do
        $CP $file $file+
        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#${ORG_ROOT_SUFFIX}#g" \
            -e "s#\ROOT_SUFFIX#${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#${ESCAPED_ADMINPASSWD}#g" \
            -e "s#\AMLDAPUSERPASSWD#${ESCAPED_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+ > $file
        rm -f $file+
    done
}

##############################################################
#
# Function - Checks whether the IS 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'`"
        exit
    fi
    ISUSER=`${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 `
    if [ "$ISUSER" != "" ]; then
        $ECHO "Directory Server is already loaded with IS DIT. IS DIT will not be loaded."
        IS_DIT_LOADED=true
    fi
    export IS_DIT_LOADED
}

##############################################################
#
# Function - Add Identity Server 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 Identity Server 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 Identity Server 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 Identity Server DIT Schema from the Directory Server succeed'`"
    else
        eval $ECHO "`$gettext 'ERROR : Removal of Identity Server 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() {
    escape_string_all $AMLDAPUSERPASSWD
    ESCAPED_AMLDAPUSERPASSWD=$x3
    escape_string_all $ADMINPASSWD
    ESCAPED_ADMINPASSWD=$x3

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


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

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

create_password_files

check_mobile_packages

#check what this script will do. 
OPTION="loadall"
useroption=$1
if [ "$useroption" != "" ]; then
    if [ "$useroption" = "--silent" ] || [ "$useroption" = "-s" ];then
      useroption=$3
    fi
fi

if [ "$useroption" != "" ]; then
    if [ "$useroption" = "loadschema" ] || [ "$useroption" = "removeschema" ] || [ "$useroption" = "loaddit" ] || [ "$useroption" = "removedit" ] || [ "$useroption" = "configplugins" ] || [ "$useroption" = "loadall" ] || [ "$useroption" = "removeall" ] || [ "$useroption" = "-s" ] || [ "$useroption" = "--silent" ]; then
        OPTION=$useroption
    else
        $ECHO "`$gettext 'usage is - amdsconfig [loadschema|removeschema|loaddit|removedit|configplugin|loadall|removeall] '`"
        exit
    fi
fi  


# Set required path for this script         
set_path_for_config	
is_dit_loaded
# check option
if [ "$OPTION" = "loadschema" ]; then 
    # Load schema
    ds_config_dit_schema
    
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
    # Load schema
    ds_config_dit_schema

    # do tag swapping in the default DIT
    config_tag_swap
    # Load DIT
    ds_config_dit

    # Configure plugins and add Indexes
    ds_config_plugin_indexes
    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"
    
fi
delete_password_files

