#!/bin/sh

#Copyright (c) 2013 NetIQ Corporation and its affiliates. All Rights Reserved.  

##########################################################################
# eDirectory cluster configuration script for Linux
##########################################################################

##########################################################################
# Script Initialization
##########################################################################
PATH=/usr/bin:/usr/sbin:/usr/local/bin:$PATH
this_file=$0
cmd_line="$@"
OS=`uname -s`
this_file_name=`basename $this_file`
VARBASEDIR="/var/opt/novell/eDirectory"
NICIBASEDIR="/var/opt/novell/nici"
LOGBASEDIR="$VARBASEDIR/log"
BINBASEDIR="/opt/novell/eDirectory/bin"
CONFBASEDIR="/etc/opt/novell/eDirectory/conf"
NDSCONFPATH=""

##########################################################################
#Variable used and changed by the functions#
##########################################################################
unattended=0
clusterpath=0
pkg_exists=0
clusterBaseLocn=""
rootinactiveinstances=0
rootactiveinstances=0
clusterSharedData=0
copySucessFlag=0
md5sumFlag=0
nicidir=""
dibdir=""
vardir=""
logdir=""
confdir=""
createDirFlag=0
linkSuccessFlag=0
normalizePath=""
subStringFlag=0
##########################################################################

##########################################################################
# Hardcoded paths of files  #
##########################################################################
log_file=$VARBASEDIR//$this_file_name".log"
TEXTDOMAINDIR="/opt/novell/eDirectory/share/locale"
export TEXTDOMAINDIR
##########################################################################

checkForSubString()
{
	vardir="$1"
	dibdir="$2"
	VARDIR_LEN=`expr length "$vardir"`
	var1=1
	var2=`expr "$VARDIR_LEN"`
	OUTPUT=`echo | awk '{ print substr("'"$dibdir"'","'"$var1"'","'"$var2"'") }'`
	if [ "$vardir" = "$OUTPUT" ]
	then
		subStringFlag=1
	fi
}

normalizePathName()
{
	normalizePath=""
        normalizePath=$1
        normalizePath=`echo "$normalizePath" | sed -e 's/\/\+/\//g'`
}

initializeForLog()
{
        dirn=`dirname $log_file`
        if [ ! -d "$dirn" -a "$dirn" != "$clusterBaseLocn" ]
        then
                mkdir -p $dirn 2>/dev/null
        fi
}

write_log()
{
	echo_sameline "`date '--rfc-3339=seconds'`: " >>$log_file
	echo $* >> $log_file
}

write_and_log()
{
        echo "%%%$*"
        write_log $*
}

echo_sameline()
{
	echo -n "%%% $1"
}

write_final_log()
{
        dirn=`dirname $log_file`
        if [ ! -d "$dirn"  -a "$dirn" != "$clusterBaseLocn" ]
        then
        	mkdir -p $dirn 2>/dev/null
        fi
        if [ -n "$log_file" ]
        then
                echo $* > $log_file
        fi
}

validateScriptExecution()
{
	id=`id | awk '{print $1}'|awk -F"=" '{print $2}'|awk -F"(" '{print $1}'`

	if [ $id -ne 0 ]
	then
		echo ""
		str1=`gettext nds "ERROR: You must have root permissions on the server for eDirectory cluster configuration."`
		echo "%%% ERROR: $failure_errcode $str1"
		exit 1
	fi
	initializeForLog
	write_log "Start of eDirectory cluster configuration"
	write_log "###############################################################"
	write_log "Inside validateScriptExecution"
	write_log "###############################################################"
	write_log "%%% User has permission to configure cluster"
	write_log "###############################################################"

}

ckyorn()
{
	shift
	ckyornstr="$@"
	ans=""
	while [ -z "$ans" ] || [ "$ans" = "ERRVAL" ]
	do
		write_log "$@"
		echo_sameline "$ckyornstr '[y/n/q] ? '"

		read ans
		ans=`echo $ans | tr "[:upper:]" "[:lower:]"`
		case $ans in
			y|yes) return 1 ;;
			n|no) return 0 ;;
			q|quit) exit 1 ;;
			*) str1=`gettext nds "Invalid option : "`
			echo "%%%$instr $str1$ans"
			ans="ERRVAL" ;;
		esac
	done
}

warningmsgPlatform()
{
	write_log "Inside warningmsgPlatform"
	write_log "###############################################################"

	echo $cmd_line | grep "\-u" > /dev/null
	unattendedFlag=$?

	str1=`gettext nds "Warning: The platform of the local computer is not supported for eDirectory cluster configuration. Please see the NetIQ eDirectory documentation for information on supported platforms."`
	echostr=`echo $str1`

	if [ $unattendedFlag -eq 1 ] ; then
		ckyornstr=`gettext nds "Do you want to Continue with eDirectory cluster configuration?"`
		ckyorn -p "$instr $echostr $ckyornstr"
		ans=`echo $ans | tr "[:upper:]" "[:lower:]"`
		case $ans in
			y|yes) return 0 ;;
			n|no) exit 1  ;;
			*) exit 1 ;;
		esac
	fi

	if [ $unattendedFlag -eq 0 ] ; then
		echo "%%%$instr $echostr"
		write_log "$instr Warning: The platform of the local computer is not supported for eDirectory cluster configuration. Please see the NetIQ eDirectory documentation for information on supported platforms."
		str1=`gettext nds "Aborting installation. The configuration utility will now exit."`
		echo "%%% $instr $str1"
		write_log "$instr Aborting installation. The configuration utility will now exit."
		write_final_log "$failure_errcode $echostr"
		exit 1
	fi
	write_log "###############################################################"
}

helpUsage()
{
        echo "  nds-cluster-config [-h] [-s] [-u]"
        str2=`gettext nds "The nds-cluster-config utility configures eDirectory to function in a Linux cluster environment."`

        str3=`gettext nds "                  Display help strings."`

        str4=`gettext nds "                  Specify the shared directory path for the cluster."`

        str5=`gettext nds "                  Perform eDirectory cluster configuration in unattended mode."`

        echo ""
        echo "  $str2"
        echo ""
        echo "          -h$str3"
        echo "          -s$str4"
        echo "          -u$str5"
}

validatePlatform()
{
	write_log "Inside validatePlatform"
	write_log "###############################################################"
	flag=0

	if [ $OS = "Linux" ] ; then
		if [ -f /etc/SuSE-release ] ; then

			rpm -q novell-oes-install >>$log_file 2>&1
			if [ $? = 0 ] ; then
				write_log "Detected Open Enterprise Server, aborting the installation"
				str1=`gettext nds "Detected Open Enterprise Server, aborting the installation"`
				write_final_log "$failure_errcode $str1"
				exit 1
			fi

			if cat /etc/SuSE-release | grep -i "suse linux enterprise server 11" >/dev/null
			then
				SLES11=$?
			fi

			if cat /etc/SuSE-release | grep -i "suse linux enterprise server 12" >/dev/null
			then
				SLES12=$?
			fi

			if [ "$SLES11" = "0" -o "$SLES12" = "0" ] ; then
				flag=0
			else
				flag=1
				warningmsgPlatform
			fi
		elif [ -f /etc/redhat-release ] ; then
			if cat /etc/redhat-release | grep -i "Red Hat Enterprise Linux Server release [67][\ \.]" >/dev/null
			then
				RHELES=$?
			fi
			if [ "$RHELES" = "0" ] ; then
				flag=0
			else
				flag=1
				warningmsgPlatform
			fi
		else
			warningmsgPlatform
		fi
	fi
	write_log "###############################################################"
}

printCurrentConfiguration()
{
	write_log "Inside printCurrentConfiguration"

	obtainDirPathToCopy
	write_and_log "###############################################################"
	str1=`gettext nds "Current eDirectory configuration"`
	echo "%%%$str1"
	write_log "Current eDirectory configuration"
	write_and_log "###############################################################"
	str1=`gettext nds "Directory"`
	if [ -d "$clusterBaseLocn/nici" ]
	then
		write_log "NICI Directory: $clusterBaseLocn/nici"
	else
		write_log "NICI Directory: $nicidir"
	fi
	echo "%%%Var  $str1 : $vardir"
	write_log "Var  Directory : $vardir"
	echo "%%%DIB  $str1 : $dibdir"
	write_log "DIB  Directory : $dibdir"
	echo "%%%Conf $str1 : $confdir"
	write_log "Conf Directory : $confdir"
	echo "%%%Log  $str1 : $logdir"
	write_log "Log  Directory : $logdir"
	str1=`gettext nds "is in"`
	echo "%%%nds.conf $str1   $confdir"
	write_log "nds.conf is in $confdir"
	write_and_log "###############################################################"
}

parseAndValidateCmdLine()
{
	write_log "Inside parseAndValidateCmdLine"
	write_log "###############################################################"

        while getopts us:h opt
        do
                case $opt in
                        u) unattended=1 ;;
                        s) clusterpath=1 
                           clusterBaseLocn=$OPTARG
			   normalizePathName "$clusterBaseLocn"
			   clusterBaseLocn="$normalizePath";;
                        h) helpUsage
                           exit 0 ;;
                        *) str1=`gettext nds "Invalid option :"`
                           echo "%%%$instr $str1 $OPTARG"
                           helpUsage
                           exit 1 ;;
                esac
        done

	checkAndCreateClusterPath

	#clear
	if [ -d "$clusterBaseLocn/nici" -o  -d "$clusterBaseLocn/data/" -o  -d "$clusterBaseLocn/data/dib" -o  -d "$clusterBaseLocn/log" -o  -d "$clusterBaseLocn/conf" ]
	then
		if [ -d "$clusterBaseLocn/nici" -a  -d "$clusterBaseLocn/data/dib" -a ! -d "$clusterBaseLocn/log" -a ! -d "$clusterBaseLocn/conf" ]
		then
			clusterSharedData=1
			str1=`gettext nds "The following directories exist on the shared drive"`
			str3=`gettext nds "Continuing with eDirectory cluster configuration"`
			str4=`gettext nds "and"`
			echo "%%%$str1: "$clusterBaseLocn/nici" $str4 "$clusterBaseLocn/data/dib". $str3."
			write_log "The following directories exist on the shared drive: "$clusterBaseLocn/nici" and "$clusterBaseLocn/data/dib". Continuing with eDirectory cluster configuration."
		elif [ -d "$clusterBaseLocn/nici" -a  -d "$clusterBaseLocn/data/dib" -a -d "$clusterBaseLocn/log" -a -d "$clusterBaseLocn/conf" ]
		then
			clusterSharedData=2
			str1=`gettext nds "All cluster shared directories exist on the shared drive."`
			echo "%%%$str1. $str3"
			write_log "All cluster shared directories exist on the shared drive. Continuing with eDirectory cluster configuration."
		else
			str1=`gettext nds "The required data for eDirectory cluster configuration does not exist on the shared drive. Ensure that the NICI and DIB data is located on the shared drive and run the nds-cluster-config utility again. The utility will now exit."`
			echo "%%% ERROR: $str1$str2"
			write_log "The required data for eDirectory cluster configuration does not exist on the shared drive. Ensure that the NICI and DIB data is located on the shared drive and run the nds-cluster-config utility again. The utility will now exit."
			printCurrentConfiguration
			exit 1
		fi

#		if [ -L "$NICIBASEDIR" ]
#		then
#			str1=`gettext nds "The NICI directory is already linked on the shared drive. eDirectory may be configured on cluster."`
#			echo "%%% WARNING: $str1$str2"
#			write_log "The NICI directory is already linked on the shared drive. eDirectory may be configured on cluster. The utility will now exit."
#			printCurrentConfiguration
#			exit 1
#		fi

	elif [ -L "$NICIBASEDIR" ]
	then
			str1=`gettext nds "The NICI directory is already linked on the shared drive. eDirectory may be configured on cluster."`
			echo "%%% WARNING: $str1 $str2"
			write_log "The NICI directory is already linked on the shared drive. eDirectory may be configured on cluster. The utility will now exit."
			printCurrentConfiguration
			exit 1
	else
		str1=`gettext nds "The required data for eDirectory cluster configuration does not exist on the shared drive. The server is the primary node of the cluster."`
		echo "%%%$str1"
		write_log "The required data for eDirectory cluster configuration does not exist on the shared drive. The server is the primary node of the cluster."
	fi

	if [ $clusterSharedData -eq 1 -o $clusterSharedData -eq 2 ]
	then
		if [ -f "$BINBASEDIR/ndsconfig" ]
		then
			dibdir=`$BINBASEDIR/ndsconfig get n4u.nds.dibdir --config-file "$clusterBaseLocn/conf/nds.conf" 2>> $log_file | grep dibdir | awk -F"=" '{print $2}'`
			sharedDibDir="$clusterBaseLocn/data/dib"
			normalizePathName "$sharedDibDir"
			sharedDibDir="$normalizePath"
			normalizePathName "$dibdir"
			dibdir="$normalizePath"
			if [ ! -z "$dibdir" -a "$dibdir" = "$sharedDibDir" ]
			then
				write_log "The configured DIB directory matches the DIB directory in the shared cluster storage location. Continuing with eDirectory cluster configuration."
			else
				str3=`gettext nds "The shared volume mount point may have changed. Check the specified shared directory and run the nds-cluster-config utility again."`
				echo "%%% WARNING: $str3 $str2"
				write_log "The shared volume mount point may have changed. Check the specified shared directory and run the nds-cluster-config utility again. The utility will now exit."
				exit 1
			fi
		fi
	fi

	write_log "###############################################################"
}

promptForBackup()
{
	write_log "Inside promptForBackup"
	write_log "###############################################################"

	if [ $unattended -eq 0 -a $clusterSharedData -eq 0 ]
	then
		str1=`gettext nds "Ensure that you back up all NICI, DIB, configuration and log files before continuing with the eDirectory cluster configuration."`
		echo "%%%$str1"
		write_log "Ensure that you back up all NICI, DIB, configuration and log files before continuing with the eDirectory cluster configuration."
		ckyornstr=`gettext nds "Do you want to Continue eDirectory cluster configuration  "`
		ckyorn -p "$ckyornstr"
		ans=`echo $ans | tr "[:upper:]" "[:lower:]"`
		case $ans in
			y|yes) return 0 ;;
			n|no) exit 1  ;;
			*) exit 1 ;;
		esac
	fi

	write_log "###############################################################"
}

obtainDirPathToCopy()
{
	write_log "Inside obtainDirPathToCopy"
	write_log "###############################################################"

	nicidir="$NICIBASEDIR"
	
	if [ -f "$CONFBASE/nds.conf" ]
	then
		NDSCONFPATH="$clusterBaseLocn/conf/nds.conf"
	else
		NDSCONFPATH="$CONFBASEDIR/nds.conf"
	fi

	vardir=`$BINBASEDIR/ndsconfig get n4u.server.vardir --config-file "$NDSCONFPATH" 2>> $log_file | grep vardir | awk -F"=" '{print $2}'`
	normalizePathName "$vardir"
	vardir="$normalizePath"

	dibdir=`$BINBASEDIR/ndsconfig get n4u.nds.dibdir --config-file "$NDSCONFPATH" 2>> $log_file | grep dibdir | awk -F"=" '{print $2}'`
	normalizePathName "$dibdir"
	dibdir="$normalizePath"

	logdir=`$BINBASEDIR/ndsconfig get n4u.server.log-file --config-file "$NDSCONFPATH" 2>> $log_file | grep log-file | awk -F"=" '{print $2}'`
	if [ ! -z "$logdir" ]
	then
		logdir=`dirname $logdir`
	else
		logdir="$LOGBASEDIR"
	fi
	normalizePathName "$logdir"
	logdir="$normalizePath"

	confdir=`$BINBASEDIR/ndsconfig get n4u.server.configdir --config-file "$NDSCONFPATH" 2>> $log_file | grep configdir | awk -F"=" '{print $2}'`
	if [ -z "$confdir" ]
	then
		confdir="$CONFBASEDIR"
	fi
	normalizePathName "$confdir"
	confdir="$normalizePath"

	write_log "###############################################################"
}

diskSpaceCheck()
{
	write_log "Inside diskSpaceCheck"
	write_log "###############################################################"

	if [ $clusterSharedData -eq 0 ]
	then
		niciSize=`du -s $nicidir | awk '{print $1}'`
		dibSize=`du -s $dibdir | awk '{print $1}'`
		varSize=`du -s $vardir | awk '{print $1}'`
		logSize=`du -s $logdir | awk '{print $1}'`
		confSize=`du -s $confdir | awk '{print $1}'`

		totalSize=$(($niciSize + $dibSize + $varSize + $logSize + $confSize))

		checkForSubString "$vardir" "$dibdir"
		if [ $subStringFlag -eq 1 ]
		then
			totalSize=$(($totalSize - $dibSize))
		fi

		sharedDiskFree=`df -k -P $clusterBaseLocn | tail -1 | awk '{print $4}'`

		if [ $sharedDiskFree -gt $totalSize ]
		then
			str1=`gettext nds "has sufficient disk space to store shared data. Continuing with eDirectory cluster configuration."`
			echo "%%%$clusterBaseLocn $str1"
			write_log "$clusterBaseLocn has sufficient disk space to store shared data. Continuing with eDirectory cluster configuration."
		else
			str1=`gettext nds "has insufficient disk space to store shared data. Check the specified shared directory and run the nds-cluster-config utility again."`
			echo "%%% ERROR: $clusterBaseLocn $str1. str2"
			write_log "$clusterBaseLocn has insufficient disk space to store shared data. Check the specified shared directory and run the nds-cluster-config utility again. The utility will now exit."
			exit 1
		fi
	fi

	write_log "###############################################################"
}

LinuxcheckForPackageExistence()
{
	pkg=$1
        if rpm -q $pkg >> $log_file 2>&1
        then
		pkg_exists=1
	fi

	return 0
}

findServerStatus()
{
	touch /tmp/root-active-instances
	touch /tmp/root-instances

	if test -f "$BINBASEDIR/ndsmanage"
	then
		echo "q" > /tmp/ndsmanage-input
		activeStr=`gettext nds "ACTIVE"`
		inactiveStr=`gettext nds "INACTIVE"`
		ndsmanage root < /tmp/ndsmanage-input 2>>$log_file | grep "$inactiveStr" | awk '{print $2}' > /tmp/root-inactive-instances
		ndsmanage root < /tmp/ndsmanage-input 2>>$log_file | grep " $activeStr" | awk '{print $2}' > /tmp/root-active-instances

		if test -s /tmp/root-inactive-instances
		then
			rootinactiveinstances=1
		fi

		if test -s /tmp/root-active-instances
		then
			rootactiveinstances=1
		fi
	else
		str1=`gettext nds "eDirectory must be installed in the default installation directory in order to complete the eDirectory cluster configuration process. Please see the NetIQ eDirectory documentation and run the nds-cluster-config utility again."`
		echo "%%% ERROR: $str1. $str2"
		write_log "eDirectory must be installed in the default installation directory in order to complete the eDirectory cluster configuration process. Please see the NetIQ eDirectory documentation and run the nds-cluster config utility again. The utility will now exit."
	fi

	activeInstancesCount=`wc -l /tmp/root-active-instances | awk '{print $1}'`
        inactiveInstancesCount=`wc -l /tmp/root-inactive-instances | awk '{print $1}'`
	totalInstances=$(($activeInstancesCount + $inactiveInstancesCount))
	if [ $totalInstances -gt 1 ]
	then
		str1=`gettext nds "Number of instances configured is"`
		str3=`gettext nds "eDirectory supports only one root instance for eDirectory cluster configuration"`
		echo "%%% ERROR: $str1 $totalInstances, $str3. $str2"
		write_log "Number of instances configured: $totalInstances, eDirectorty supports only one root instance for eDirectory cluster configuration. The utility will now exit."
		exit 1
	fi
}

checkeDirStatus()
{
	write_log "Inside checkeDirStatus"
	write_log "###############################################################"
	$OS"checkForPackageExistence" novell-NDSserv
        if [ $pkg_exists -eq 1 ]
        then
		str1=`gettext nds "eDirectory is installed. Continuing with eDirectory cluster configuration."`
		echo "%%%$str1"
		write_log "eDirectory is installed. Continuing with eDirectory cluster configuration."
	else
		str1=`gettext nds "eDirectory is not installed. Install eDirectory and then run the nds-cluster-config utility again."`
		echo "%%% ERROR: $str1. $str2"
		write_log "eDirectory is not installed. Install eDirectory and then run the nds-cluster-config utility again. The utility will now exit."
		exit 1
	fi

	findServerStatus

	if [ $rootinactiveinstances -eq 1 -o $rootactiveinstances -eq 1 ]
	then
		if [ $clusterSharedData -eq 1 -o $clusterSharedData -eq 2 ]
		then
			str1=`gettext nds "eDirectory is configured. The server can be either primary or secondary node of the cluster."`
			echo "%%%$str1"
			write_log "eDirectory is configured. The server can be either primary or secondary node of the cluster."
		else
			str1=`gettext nds "eDirectory is configured on primary node of the server node."`
			echo "%%%$str1"
			write_log "eDirectory is configured on primary node of the server node."
			confdirTemp=`$BINBASEDIR/ndsconfig get n4u.server.configdir 2>> $log_file | grep configdir | awk -F"=" '{print $2}'`
			normalizePathName "$confdirTemp"
			confdirTemp="$normalizePath"
		        if [ -z "$confdirTemp" ]
        		then
        		        confdirTemp="$CONFBASEDIR"
		        fi
			if [ ! -f "$confdirTemp/nds.conf" ]
			then
				str1=`gettext nds "nds.conf is not in the following directory"`
				echo "%%%$str1: $confdirTemp."
				write_log "nds.conf is not in the following directory: $confdirTemp."
				str1=`gettext nds "nds.conf should be in the following directory for eDirectory cluster configuration"`
				echo "%%% ERROR: $str1 $confdirTemp. $str2"
				write_log "nds.conf should be in the following directory for eDirectory cluster configuration $confdirTemp. The utility will now exit."
				exit 1
			else
				write_log "nds.conf is in $confdirTemp directory."
			fi
		fi
	else
		if [ $clusterSharedData -eq 1 -o $clusterSharedData -eq 2 ]
		then
			str1=`gettext nds "eDirectory is not configured on secondary node of the cluster."`
			echo "%%%$str1"
			write_log "eDirectory is not configured on secondary node of the cluster."
		else
			str1=`gettext nds "eDirectory is not configured on the primary node of the cluster. Configure eDirectory on the primary node of the cluster and run the nds-cluster-config utility again."`
			echo "%%% ERROR: $str1 $str2"
			write_log "eDirectory is not configured on the primary node of the cluster. Configure eDirectory on the primary node of the cluster and run the nds-cluster-config utility again. The utility will now exit."
			printCurrentConfiguration
			exit 1
		fi
	fi

	write_log "###############################################################"
}

getClusterBaseLocn()
{
	write_log "Inside getClusterBaseLocn"
	write_log "###############################################################"

	while [ 1 ]
	do
		str1=`gettext nds "Enter the shared base location"`
		echo_sameline "$str1: "
		read clusterBaseLocn
		if [ -z "$clusterBaseLocn" ]
		then
			str1=`gettext nds "The specified shared drive location is empty"`
			echo "%%%$str1"
			write_log "The specified shared drive location is empty."
		elif [ ! -d "$clusterBaseLocn" ]
		then
			str1=`gettext nds "The specified shared directory doesn't exist"`
			echo "%%% ERROR: $str1: $clusterBaseLocn"
			write_log "The specified shared directory doesn't exist: $clusterBaseLocn"
		else
			normalizePathName "$clusterBaseLocn"
			clusterBaseLocn="$normalizePath"
			clusterpath=1
			break
		fi
	done

	write_log "###############################################################"
}

checkAndCreateClusterPath()
{
	write_log "Inside checkAndCreateClusterPath"
	write_log "###############################################################"

	flag=1
	if [ $clusterpath -eq 1 ]
	then
		if [ -z "$clusterBaseLocn" ]
		then
			flag=0
		fi
	fi

	if [ $clusterpath -eq 0 -o $flag -eq 0 -o ! -d "$clusterBaseLocn" ]
	then
		if [ $unattended -eq 1 ]
		then
			str1=`gettext nds "The specified shared drive location does not exist. Ensure that the shared drive is accessible and run the nds-cluster-config utility again."`
			echo "%%% ERROR: $str1 $str2"
			write_log "The specified shared drive location does not exist. Ensure that the shared drive is accessible and run the nds-cluster-config utility again. The utility will now exit."
			exit 1
		else
			if [ $clusterpath -eq 1 ]
			then
				str1=`gettext nds "The specified shared directory doesn't exist"`
				echo "%%% ERROR: $str1: $clusterBaseLocn"
				write_log "The specified shared directory doesn't exist: $clusterBaseLocn"
			fi
			getClusterBaseLocn
		fi
	fi

	if [[ "$clusterBaseLocn" = */ ]]
	then
		clusterBaseLocn=`echo "$clusterBaseLocn" | sed 's/.$//'`
	fi
	

	write_log "###############################################################"
}

checkeDirRunning()
{
	write_log "Inside checkeDirRunning"
	write_log "###############################################################"

	if [ $rootactiveinstances -eq 1 ]
	then
		str1=`gettext nds "The eDirectory root instance is currently running."`
		str3=`gettext nds "You must stop the eDirectory instance before running cluster configuration. Stop the instance and run the nds-cluster-config utility again."`
		echo "%%% $str1"
		echo "%%% $str3 $str2"
		write_log "The eDirectory root instance is currently running." 
		write_log "You must stop the eDirectory instance before running cluster configuration. Stop the instance and run the nds-cluster-config utility again. The utility will now exit."
		exit 1
	fi
	write_log "###############################################################"
}

dataConsistencyCheck()
{
        sourceDir=$1
        destDir=$2
        md5sumFlag=1

        pwdDir=$PWD

        cd $sourceDir
        find . -type f -name "*" | while read f
        do
                srcmd5sum=`md5sum "$sourceDir/$f" | awk '{print $1}'`
                destmd5sum=`md5sum "$destDir/$f" | awk '{print $1}'`
                if [ "$srcmd5sum" != "$destmd5sum" ]
                then
                        md5sumFlag=0
                        break
                fi
        done

        cd $pwdDir

        if [ $md5sumFlag -eq 1 ]
        then
                write_log "The data copied from $sourceDir to $destDir is consistent."
        else
		str1=`gettext nds "source directory"`
		str2=`gettext nds "destination directory"`
		str3=`gettext nds "The data copied from source directory to destination directory is not consistent, where"`
		echo "%%%$str3"
		echo "%%%$str1 : $sourceDir	$str2 : $destDir"
                write_log "The data copied from source directory to destination directory is not consistent, where"
		write_log "source directory : $sourceDir	destination directory : $destDir"
        fi
}

copyDirData()
{
	sourceDir=$1
	destDir=$2

	copySucessFlag=0
	if [ -d "$destDir" ]
	then
		cp -R $sourceDir/* $destDir 2>> $log_file
		if [ "$?" -eq 0 ]
		then
			copySucessFlag=1
			str3=`gettext nds "nds-cluster-config sucessfully copied data from"` 
			echo "%%%$str3 $sourceDir -> $destDir"
			write_log "nds-cluster-config sucessfully copied data from $sourceDir to $sourceDir"
		else
			str3=`gettext nds "nds-cluster-config could not copy data from"` 
			echo "%%%$str3 $sourceDir -> $destDir"
			write_log "nds-cluster-config could not copy data from $sourceDir to $sourceDir"
		fi
	fi
}

deleteDir()
{
	dir=$1

	if [ ! -z "$dir" -a -d "$dir" ]
	then
		rm -rf $dir 2>> $log_file
		if [ "$?" -eq 0 ]
		then
			write_log "nds-cluster-config sucessfully deleted $dir"
		else
			str1=`gettext nds "nds-cluster-config could not delete"`
			echo "%%%$str1 $dir1"
			write_log "nds-cluster-config could not delete $dir"
		fi
	else
		write_log "nds-cluster-config could not delete $dir, because the directory doesn't exist."
	fi
}

checkAndBindMount()
{
	sourceDir=$1
	destinationDir=$2
	findmnt $destinationDir > /dev/null
	if [ $? = 0 ]
	then
		write_log "$destinationDir already bound to external path"
		return 0
	fi
	grep "$destinationDir" /etc/fstab > /dev/null 2>&1
	if [ $? != 0 ]
	then
		echo -e "\n$sourceDir $destinationDir none defaults,bind 0 0" >> /etc/fstab
	fi
	mkdir -p $destinationDir
	mount $destinationDir
}

checkAndCreateLink()
{
	sourceDir=$1
	linkDir=$2
	linkSuccessFlag=0

	if [ ! -L $linkDir ]
	then
		ln -sf "$sourceDir" "$linkDir" 2>> $log_file
		if [ "$?" -eq 0 ]
		then
			linkSuccessFlag=1
			write_log "nds-cluster-config successfully linked $linkDir to $sourceDir."
		else
			write_log "nds-cluster-config could not link $linkDir to $sourceDir."
		fi
	else
		write_log "Link for $linkDir exists."
	fi
}

cleanupSharedData()
{
	deleteDir "$clusterBaseLocn/conf/"
	deleteDir "$clusterBaseLocn/log/"
	deleteDir "$clusterBaseLocn/data/dib/"
	deleteDir "$clusterBaseLocn/data/"
	deleteDir "$clusterBaseLocn/nici/"
}

checkAndReplaceStringInFile()
{
	searchStr=$1
	replaceStr=$2
	fileName=$3

	grep -i $searchStr $fileName >> /dev/null
	if [ $? -eq 0 ]
	then
		sed -i "/$searchStr/d" $fileName >> /dev/null
		if [ $? -eq 0 ]
        	then
			write_log "nds-cluster-config successfully replaced the parameter "$searchStr"."
		else
			str1=`gettext nds "nds-cluster-config could not replace the parameter"`
			str=`gettext nds "The utility will now exit."`
			echo "%%% ERROR: $str1 $searchStr. $str"
			write_log "nds-cluster-config could not replace the parameter $searchStr. The utility will now exit."
			exit 1
		fi
	fi

	echo "$searchStr=$replaceStr" >> $fileName
	if [ $? -eq 0 ]
	then
		str1=`gettext nds "nds-cluster-config successfully replaced"`
		str2=`gettext nds "in"`
		echo "%%%$str1 $searchStr -> $replaceStr $str2 $fileName."
		write_log "$searchStr was successfully replaced with $replaceStr in $fileName."
	else
		str1=`gettext nds "nds-cluster-config could not replace"`
		str2=`gettext nds "in"`
		echo "%%% ERROR: $str1 $searchStr -> $replaceStr $str2 $fileName $str"
		write_log "nds-cluster-config could not replace $searchStr with $replaceStr in $fileName. The utility will now exit."
		exit 1
	fi
}

checkAndCreateDirectory()
{
	dirPath=$1
	createDirFlag=0
	if [ ! -d "$dirPath" ]
	then
		write_log "Directory $dirPath does not exist on the shared drive."
		mkdir -p "$dirPath"
		if [ "$?" -eq 0 ]
		then
			write_log "nds-cluster-config successfully created the directory $dirPath on the shared drive."
			createDirFlag=1
		else		
			str1=`gettext nds "nds-cluster-config directory could not create the following directory on the shared drive"`
			echo "%%% ERROR: $str1 $dirPath $str"
			write_log "nds-cluster-config directory could not create the following directory on the shared drive: $dirPath. The utility will now exit."
			cleanupSharedData
			exit 1
		fi
	fi

}

checkAndCopyConsistency()
{
	inPathSet=$1
	srcDir=$2
	destDir=$3
	if [ $inPathSet -eq 1 ]
	then
		if [ -d "$destDir" ]
		then
			copyDirData "$srcDir" "$destDir"
#			if [ "$destDir" = "$clusterBaseLocn/conf/" ]
#			then
#				copyDirData "$srcDir/.edir/" "$destDir/.edir/"
#			fi
#	
			dataConsistencyCheck $srcDir "$destDir"
			if [ $copySucessFlag -eq 0 -o $md5sumFlag -eq 0 ]
			then
				cleanupSharedData
				exit 1
			fi
		fi
	fi

}

doSystemdChanges()
{
	write_log "Inside doSystemdChanges"
	write_log "###############################################################"
	ps -p 1 | grep systemd >/dev/null
	if [ $? -eq 0 ] ; then
		existing_ndsconf_dir=`dirname "$NDSCONFPATH"`
		existingTemplateFileAttach=`echo "$existing_ndsconf_dir/env" | sed "s|/|-|g"`
		existingConfigFile=`echo "$NDSCONFPATH" | sed "s|/|-|g"`

		migrated_ndsconf_dir="$clusterBaseLocn/conf"
		migratedTemplateFileAttach=`echo "$migrated_ndsconf_dir/env" | sed "s|/|-|g"`
		migratedConfigFile=`echo "$clusterBaseLocn/conf/nds.conf" | sed "s|/|-|g"`

		existingSystemdTemplateFile="ndsdtmpl$existingConfigFile@$existingTemplateFileAttach.service"
		migratedSystemdTemplateFile="ndsdtmpl$migratedConfigFile@$migratedTemplateFileAttach.service"

		if [ $clusterSharedData -eq 0 ]
		then
			write_log "systemd init system detected. Migrating the ndsd systemd template as well..."
			write_log "Current nds.conf is $NDSCONFPATH"
			write_log "Migrated nds.conf $clusterBaseLocn/conf/nds.conf"

			sed -i "s|$NDSCONFPATH|$clusterBaseLocn/conf/nds.conf|" $clusterBaseLocn/conf/.edir/instances.0 >> /dev/null

			systemctl disable $existingSystemdTemplateFile
			mv "/usr/lib/systemd/system/ndsdtmpl$existingConfigFile@.service" "/usr/lib/systemd/system/ndsdtmpl$migratedConfigFile@.service"
			cp "/usr/lib/systemd/system/ndsdtmpl$migratedConfigFile@.service" $clusterBaseLocn/
			systemctl enable $migratedSystemdTemplateFile

			write_log "Migrating the ndsd systemd template is complete."
		else
			write_log "systemd init system detected and primary node is already configured. Enabling systemd startup in this node as well..."
			cp "$clusterBaseLocn/ndsdtmpl$migratedConfigFile@.service" "/usr/lib/systemd/system/"
			systemctl enable $migratedSystemdTemplateFile
		fi
	else
		write_log "sysV init system detected. No systemd migrations needed..."
	fi
	write_log "###############################################################"
}

checkAndMoveDataToCluster()
{
	write_log "Inside checkAndMoveDataToCluster"
	write_log "###############################################################"

	#If eDir data already exists on shared drive, just do the systemd changes and return
	if [ $clusterSharedData -eq 1 -o $clusterSharedData -eq 2 ]
	then
		write_log "Shared drive has core eDir data already."
	fi

	niciPath=0
	varPath=0
	dibPath=0
	logPath=0
	confPath=0

	if [ $clusterSharedData -eq 0 ]
	then
		dirPath="$clusterBaseLocn/nici/"
		checkAndCreateDirectory "$dirPath"
		niciPath=$createDirFlag

		dirPath="$clusterBaseLocn/data/"
		checkAndCreateDirectory "$dirPath"
		varPath=$createDirFlag

		dirPath="$clusterBaseLocn/data/dib/"
		checkAndCreateDirectory "$dirPath"
		dibPath=$createDirFlag
	fi

	if [ $clusterSharedData -eq 0 -o $clusterSharedData -eq 1 ]
	then
		dirPath="$clusterBaseLocn/log/"
		checkAndCreateDirectory "$dirPath"
		logPath=$createDirFlag

		dirPath="$clusterBaseLocn/conf/"
		checkAndCreateDirectory "$dirPath"
		dirPath="$clusterBaseLocn/conf/.edir/"
		checkAndCreateDirectory "$dirPath"
		confPath=$createDirFlag
	fi

	if [ $clusterSharedData -eq 0 ]
	then
		checkAndCopyConsistency "$niciPath" "$nicidir" "$clusterBaseLocn/nici/"	

		checkAndCopyConsistency "$varPath" "$vardir" "$clusterBaseLocn/data"	

		checkAndCopyConsistency "$dibPath" "$dibdir" "$clusterBaseLocn/data/dib"	
	fi

	if [ $clusterSharedData -eq 0 -o $clusterSharedData -eq 1 ]
	then
		checkAndCopyConsistency "$logPath" "$logdir" "$clusterBaseLocn/log/"	

		checkAndCopyConsistency "$confPath" "$confdir/.edir/" "$clusterBaseLocn/conf/.edir/"	

		checkAndCopyConsistency "$confPath" "$confdir" "$clusterBaseLocn/conf/"	
	fi

	doSystemdChanges

	if [ ! -L $nicidir ]
        then
		deleteDir $nicidir
		checkAndCreateLink "$clusterBaseLocn/nici/" $nicidir
	fi

	if [ $clusterSharedData -eq 1 ]
	then
		ndsConf="$confdir/nds.conf"
	else
		ndsConf="$clusterBaseLocn/conf/nds.conf"
	fi

	if [ ! -z "$dibdir" -a "$dibdir" != "$clusterBaseLocn/data/dib" ]
	then
		write_log "Setting n4u.nds.dibdir"
		checkAndReplaceStringInFile "n4u.nds.dibdir" "$clusterBaseLocn/data/dib" $ndsConf
		deleteDir "$dibdir"
	fi

	if [ "$clusterSharedData" -eq 0 ]
	then
		write_and_log "Setting n4u.server.vardir"
		$BINBASEDIR/ndsconfig set n4u.server.vardir="$clusterBaseLocn/data" --config-file $ndsConf 2>> /dev/NULL 1>> $log_file

		write_and_log "Setting http.server.module-base"
		$BINBASEDIR/ndsconfig set http.server.module-base="$clusterBaseLocn/data/nds-http/" --config-file $ndsConf 2>> /dev/NULL 1>> $log_file

		write_and_log "Setting n4u.server.log-file"
		$BINBASEDIR/ndsconfig set n4u.server.log-file="$clusterBaseLocn/log/ndsd.log" --config-file $ndsConf 2>> /dev/NULL 1>> $log_file

		write_and_log "Setting n4u.server.configdir"
		$BINBASEDIR/ndsconfig set n4u.server.configdir="$clusterBaseLocn/conf" --config-file $ndsConf 2>> /dev/NULL 1>> $log_file

		write_and_log "Setting n4u.server.xdas-conf"
		$BINBASEDIR/ndsconfig set n4u.server.xdas-conf="$clusterBaseLocn/conf/xdasconfig.properties" --config-file $ndsConf 2>> /dev/NULL 1>> $log_file
	fi

	deleteDir "$VARBASEDIR/data"
	checkAndCreateLink "$clusterBaseLocn/data/" "$VARBASEDIR/data"

	deleteDir "$LOGBASEDIR"
	checkAndCreateLink "$clusterBaseLocn/log/" "$LOGBASEDIR"

	deleteDir "$CONFBASEDIR"
	checkAndBindMount "$clusterBaseLocn/conf/" "$CONFBASEDIR"

	write_log "###############################################################"
}


##########################################################################

main()
{
	validateScriptExecution
	write_log "###############################################################"
	write_log "Inside Main"
	write_log "###############################################################"

	validatePlatform
	parseAndValidateCmdLine $cmd_line
	checkeDirStatus
	checkeDirRunning
	promptForBackup
	obtainDirPathToCopy
	diskSpaceCheck
	checkAndMoveDataToCluster
	printCurrentConfiguration

	write_log "###############################################################"
}
main
