#!/bin/sh

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

isOESServer()
{
        if [ -f /etc/novell-release ]; then

                isOES=`grep -Fi -m 1 "Open Enterprise Server" /etc/novell-release`

                if [[ $isOES == *"Open Enterprise Server"* ]];
                then
           		export OESENABLED=1
                fi
	fi
}


version=""
product_name="NetIQ eDirectory"
PATH=$PATH:/usr/local/bin
export PATH
ifSun=`uname  -a|grep -c SunOS`
OS=`uname`
current_user=""
if [ -f /etc/novell-release ]; then
	instance_num=0
	first_instance=1
	instance_source="main_menu"

fi

# if OESENABLED is set certain operation wouldn't allow to do
OESENABLED=0
export OESENABLED
isOESServer

if [ $ifSun -ge 1 ]
then
        AWK=/usr/xpg4/bin/awk
else
        AWK=/bin/awk
fi

# Get the userName in case it is not already present
if [ -z "${current_user}" ]; then
	current_user=`id | awk -F\( '{print $2}' | awk -F\) '{print $1}'`
fi

uname=`id | cut -d'=' -f2|cut -d'(' -f2|cut -d')' -f1`
userid=`id $uname | cut -d'=' -f2|cut -d'(' -f1`
if [ $userid -ne 0 ]
then 
	systemdparam="--user"
fi

isFirstInstance()
{
	if [ "$instance_source" = "main_menu" ]
	then
	        if [ $instance_num -eq 1 ]; then
        	        first_instance=1
	        else
        	        first_instance=0
        	fi
	elif [ "$instance_source" = "start_stop_all" ]
	then
		if [ $inst_count -eq 1 ]; then
			first_instance=1
		else
			first_instance=0
		fi
	elif [  "$instance_source" = "start_stop" ]
	then
        	for instance_file in `echo $uid_list`
		do
                	if [ -w "$instance_file" ]; then

				first_instance_read=$(head -n 1 $instance_file)
			        if [ "$first_instance_read" = $inst_list ]; then
                			first_instance=1
	                	else
                		        first_instance=0
                		fi
			fi	
		done
	fi
}

NonRoot_RHEL7()
{
	ps -p 1 | grep systemd >/dev/null
        if [ $? -ne 0 ]
        then
                return 2
        fi
        for file in $(ls /etc/*release);
        do
            version_RHEL=`grep -Fi -m 1 "Red Hat Enterprise Linux Server" $file`
            version_SLES=`grep -Fi -m 1 "SUSE Linux Enterprise Server" $file`
            if [[ $version_SLES == *"SUSE Linux Enterprise Server"* ]];
            then
                    if [[ $version_SLES == *"11"* || $version_SLES == *"10"* ]];
                    then
                            return 2;
                    else
                            return 3;
                    fi
            elif [[ $version_RHEL == *"Red Hat Enterprise Linux"* ]];
            then
                    if [[ $version_RHEL == *"Maipo"* ]] && [[ $UID != 0 ]]; #RHEL7 non root user
                    then
                            return 2;
                    elif [[ $version_RHEL == *"Santiago"* ]]; #Santiago is RHEL 6, falling back to init.d for both root and nonroot RHEL6
                    then        
			    return 2;
                    fi
            fi
        done
        return 3;  #If we return 3 here, then for RHEL6 , it'll try falling back to systemd
}

print_action()
{
	actioninput=$1
	if [ "$actioninput" = "start" ]
        then
		str=`gettext nds "Starting Opentext eDirectory server..."`
		echo "$str"
	elif [ "$actioninput" = "stop" ]
	then
		str=`gettext nds "Stopping Opentext eDirectory server..."`
		echo "$str"
	fi
}


print_usage()
{
	str=`gettext nds "Usage:"`
	echo $str
	str=`gettext nds "To start or stop a specific instance:"`
	echo $str
        str=`gettext nds "config-file of the instance configured by"`
	echo "    ndsmanage [start|stop] --config-file <$str $current_user>"
	echo ""
	str=`gettext nds "To start or stop all the instances configured by"`
	echo "$str $current_user"
	echo "    ndsmanage [startall|stopall]"
	echo ""
	str=`gettext nds "To list instances configured by a user:"`
	echo $str
        str=`gettext nds "username"`
	echo "    ndsmanage <$str>"
	echo ""
	str=`gettext nds "To list all the instances configured for this installation:"`
	echo $str
	echo "    ndsmanage [-a|--all]"
	echo ""
	str=`gettext nds "To print this help:"`
	echo $str
	echo "    ndsmanage [-h|--help]"
	exit $1
}

GetVersion()
{
	str=`gettext nds "Server instances management utility for "`
	binDir=`dirname $0`
	if [ -x ${binDir}/ndsconfig ]; then
		version=`${binDir}/ndsconfig --version 2> /dev/null | awk '{print substr($0, index($0, "NetIQ"))}'`
	else
		version=${product_name}
	fi
	echo $str $version
}


GetVersion
action=""
actionall=""

conf1_dir=`which $0 |$AWK -F"/" '{for(i=2; i<NF-1; i++) printf "/%s", $i;} END{printf "\n"}'`

base_dir=`echo $conf1_dir|$AWK -F"/opt" '{for(i=1;i<NF;i++)if(i>1)printf("/opt/%s",$i);else printf("%s", $i);}'`
conf_dir=$base_dir/etc/opt/novell/eDirectory/conf/

     if [ "$1" = "start" -o "$1" = "stop" ]
     then
         action="$1"
         if [ "$2" != "--config-file" ]
         then
         print_usage 1
         elif [ -z "$3" ]
         then
                print_usage 1
         else
        	username=`id | cut -d'=' -f2|cut -d'(' -f2|cut -d')' -f1`
        	uid=`id $username | cut -d'=' -f2|cut -d'(' -f1`
                conf_file=$3
                for inst in `cat $conf_dir/.edir/instances.$uid`       # Ensure current_user is loading or unloading its own instance
                do
                        if [ "$conf_file" != "$inst" ]
                        then
                                match=0
                        else
                                match=1
				break
                        fi
                done
                if [ "$match" != 1 ]
                then
                        str=`gettext nds "Current user cannot load the instance"`
                        echo $str
                        exit 1
                fi
         fi
     elif [ $# -gt 1 ]
     then
    	print_usage 1
     elif [ "$1" = "startall" -o "$1" = "stopall" ]
     then
	 actionall="$1"
	 action=`echo $actionall|sed 's/all//'` 
     elif [ "$1" = "-h" -o "$1" = "--help" ]
     then
	print_usage 0
     elif [ "$1" = "-v" -o "$1" = "--version" ]
     then
	exit 0
     elif [ "$1" = "-a" -o "$1" = "--all" ]
     then
         uid="all"
     elif [ "$1" = "-u" ] #implicitly support -u uid
     then
        username="$2"
        uid=`id $username | cut -d'=' -f2|cut -d'(' -f1`
     elif [ -z "$1" ]
     then
        username=`id | cut -d'=' -f2|cut -d'(' -f2|cut -d')' -f1`
        uid=`id $username | cut -d'=' -f2|cut -d'(' -f1`
     else
         username=$1
         uid=`id $1 2>/dev/null| cut -d'=' -f2|cut -d'(' -f1` 
     fi

if [ "$action" != "" -a "$actionall" != "" ]
then
        username=`id | cut -d'=' -f2|cut -d'(' -f2|cut -d')' -f1`
        uid=`id $username | cut -d'=' -f2|cut -d'(' -f1`
fi

if [ -z "$uid" ]
then
 	str=`gettext nds "Invalid user : "`
	echo $str $username	
	exit 1
fi

init_location="etc/init.d"
UTF_CHARMAP="UTF-8"
LOCAL_CHARMAP=`locale charmap`
if [ "$OS" = "HP-UX" ]
then
	init_location="sbin/init.d"
	UTF_CHARMAP="utf8"
	LOCAL_CHARMAP=`locale charmap|cut -f1 -d.|cut -c 2-`
	if [ "$LOCAL_CHARMAP" = "\"" ]
	then
		LOCAL_CHARMAP="iso88591"
	fi
elif [ "$OS" = "AIX" ]
then
	init_location="etc"
fi


no_instances="no"
ctr=0

if [ "$uid" = "all" ]
then
	uid_list=`ls $conf_dir/.edir/instances.* 2>>/dev/null`
	if [ -z "$uid_list" ]
	then
		str=`gettext nds "There are no instances configured for this installation of eDirectory"`
		echo $str
		no_instances="yes"
	fi
else
	uid_list=`echo $conf_dir/.edir/instances.$uid`
	if [ ! -s "$uid_list" ]
	then
		str=`gettext nds "There are no instances configured."`
		echo $str
		no_instances="yes"
	fi
fi

if [ "$action" != "" ]
then
	if [ "$actionall" != "" ]
	then
		if [ ! -f $uid_list ]
		then
			exit 0
		fi
		inst_list=`cat $uid_list`
		if [ -f /etc/novell-release ]; then

			instance_source="start_stop_all"
		fi
	else
		inst_list="$conf_file"
		if [ -f /etc/novell-release ]; then

	                instance_source="start_stop"
		fi
	fi
	
	if [ -f /etc/novell-release ]; then

	        inst_count=0
	fi
	for inst in `echo $inst_list`
	do
		if [ -w "$inst" ]
        	then
			if [ -f /etc/novell-release ]; then

	                        inst_count=$((inst_count+1))
			fi
			str=`gettext nds "Instance at"`
			echo "$str $inst....."
			NonRoot_RHEL7
			if [ $? -eq 3 ] ; then
				ndsconf_dir=`dirname "$inst"`

                                if [ -f /etc/novell-release ]; then
                                         isFirstInstance

                                         if [ $first_instance -eq 1 ]; then
                                                 templateFileAttach="ndsd"
                                                 print_action $action
                                                 systemctl $systemdparam $action $templateFileAttach.service
                                         else
                                                templateFileAttach=`echo "$ndsconf_dir/env" | sed "s|/|-|g"`    
                                                configFile=`echo "$inst" | sed "s|/|-|g"`       
                                                print_action $action    
                                                systemctl $systemdparam $action ndsdtmpl$configFile@$templateFileAttach.service 
                                        fi
                                else
                                        templateFileAttach=`echo "$ndsconf_dir/env" | sed "s|/|-|g"`
                                        configFile=`echo "$inst" | sed "s|/|-|g"`
                                        print_action $action
                                        systemctl $systemdparam $action ndsdtmpl$configFile@$templateFileAttach.service
                                fi

			else
	 			NDS_CONF=$inst $base_dir/$init_location/ndsd $action
			fi
		else
			print_usage 1
	fi
	done
	exit 0
fi


echo_prompt_line()
{
	if [ "$OS" = "Linux" ]
	then
		echo -n "$1"
	else
		echo "$1\c"
	fi
}

validate()
{
	value=$1
	check=$2
	testvalue=""
	case $check in
		"TREENAME")
			testvalue=`echo "$value" | grep '[^a-zA-Z0-9_\-]'`
			if [ "$testvalue" = "$value" ]
			then
				str=`gettext nds "The tree name can only contain alphanumeric characters, underscore or hyphens."`
				str_special="[a-z,A-Z,0-9,_,-]"
				echo "$str $str_special"
				return 1
			fi;;
		"SERVERNAME")
			testvalue=`echo "$value"| iconv -f "$LOCAL_CHARMAP" -t "$UTF_CHARMAP"	| iconv -f "$UTF_CHARMAP" -t "$LOCAL_CHARMAP"`
			if [ "$testvalue" != "$value" ]
			then
				str=`gettext nds "The server name is invalid"`
                                echo "$str"
				return 1
			fi
			testvalue=`echo "$value"| grep '[]/:*?~@$%^&()|[}{]'`
			if [ "$testvalue" = "$value" ]
			then
				str=`gettext nds "The server name can only be alphanumeric characters and none of these special characters."`
				str_special="[]/:*?~@$%^&()|{}"
				echo "$str $str_special"
				return 1
			fi;;
		"ADMINUSER"|"SERVERCONTEXT")
			testvalue=`echo "$value"| iconv -f "$LOCAL_CHARMAP" -t "$UTF_CHARMAP"	| iconv -f "$UTF_CHARMAP" -t "$LOCAL_CHARMAP"`
			if [ "$testvalue" != "$value" ]
			then
				str=`gettext nds "The admin user/server context is invalid"`
                                echo "$str"
				return 1
			else
				testvalue=`echo "$value"|grep '[+\.+]'`
				if [ "$testvalue" != "$value" ] && [ "$check" = "ADMINUSER" ]
				then
					str=`gettext nds "The admin user must have a full dot-delimited context."`
					echo "$str"
					return 1
				fi
			fi
			testvalue=`echo "$value"| grep '[]/:*?~@$%^&()|[}{]'`
			if [ "$testvalue" = "$value" ]
			then
				str=`gettext nds "The admin user/context can only be alphanumeric characters and none of these special characters."`
				str_special="[]/:*?~@$%^&()|{}"
				echo "$str $str_special"
				return 1
			fi;;
		"PATH"|"FILE")
		        testvalue=`echo "$value"|grep '[/+]'` 	
			if [ "$testvalue" != "$value" ]
			then
				str=`gettext nds "The path specified must include a slash"`
				echo "$str"
				return 1
			fi;;
		"PORT")
			testvalue=`echo "$value" | grep '^[0-9]*$'` 
			if [ "$testvalue" != "$value" ]
			then
				str=`gettext nds "The port number must be entirely numeric."`
				echo "$str"
				return 1
			fi
			if [ "$current_user" = "root" ]
			then
				min_port=1
			else
				min_port=1024
			fi
			max_port=65535
			if [ "$value" -lt "$min_port" -o "$value" -gt "$max_port" ]
			then
				str=`gettext nds "The port specified must be between the range $min_port and $max_port."`
				echo "$str"
				return 1
			fi;;
		"IPADDRESS")
			testvalue=`echo "$value" | grep '^[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*[\:]*[0-9]*$'`
			if [ "$testvalue" != "$value" ]
                        then
                                testvalue=`echo "$value" | grep '^\[[0-9a-f]*\:[0-9a-f]*\:[0-9a-f]*[:]*[0-9a-f]*[:]*[0-9a-f]*[:]*[0-9a-f]*[:]*[0-9a-f]*[:]*[0-9a-f]*\][\:]*[0-9]*$'`
                        fi

			if [ "$testvalue" != "$value" ]
			then
				str=`gettext nds "The IP address specified is not valid."`
				echo "$str"
				return 1
			fi;;
		"ADMINGRPCHK")
                        if [ "$value" = "Y" -o "$value" = "y" -o "N" -o "n" ]
			then
				return 0;
			else
				return 1;
			fi;;

		"ADMINGRPNAME")
                        testvalue=`cat /etc/group | cut -d: -f1 | grep -e"$value" -w`
                        if [ "$testvalue" != "$value" ]
                        then
                                str=`gettext nds "eDiretory group is not found. Create the group and try."`
                                echo "$str"
                                return 1
                        fi;;

		*)return 0
	esac
	return 0
}

read_valid()
{
        temp_reader=""
        while [ -z "$temp_reader" ]
        do
				echo_prompt_line "$2"
				temp_reader=`$AWK '{print; exit;}'`
				validate $temp_reader $3
				if [ $? -eq 1  ]; then
					 temp_reader=""
				fi
        done
        eval $1=$temp_reader
}
operation_OES()
{
	if [ -n "$YAST_IS_RUNNING" ]
	then
		return 0
	else 
		str=`gettext nds "This Operation is not allowed in OES."`
		echo "$str"
		return 1
	fi
}
create_new_instance()
{
	while true
	str=`gettext nds "Create a new tree ? "`
	echo_prompt_line "$str"
	echo_prompt_line "(y or [n]): "
	read ans
	optional_param=""
	do
		if [ "$ans" = "y" -o "$ans" = "Y" ]
		then
			operation="new"
			str=`gettext nds "Choose a tree name that can be unique in the network."`
			optional_param="-i"
			break
		fi
		if [ "$ans" = "n" -o "$ans" = "N" ]
		then
			operation="add"
			str=`gettext nds "Ensure that the tree you are going to add server into is discoverable by this host."`
			break
		fi
	done
	echo "$str"
	echo ""
	str=`gettext nds "TREE NAME: "`
	read_valid "tree_name" "$str" "TREENAME"
	echo ""
	
	if [ "$operation" = "add" ]
	then
		str=`gettext nds "Provide the IP address of the server holding the master replica. [Ex: 100.150.200.250:1524 / [2015::50]:1524"`
		echo "$str"
		echo ""
		str=`gettext nds "MASTER ADDRESS: "`
		read_valid "master_ip" "$str" "IPADDRESS"
		echo ""
		optional_param="-p $master_ip"
	fi
	
	str1=`gettext nds "Server name is the representation of this instance's server object in the eDirectory tree. [Ex:"` 
        echo "$str1 $HOSTNAME-$current_user-$ctr]"
	echo ""
	str=`gettext nds "SERVER NAME: "`
	read_valid "server_name" "$str" "SERVERNAME"
	echo ""

	CheckUniqServerName
	server_status=$?
	while [ "$server_status" -ne 1 ]
	do
		str=`gettext nds "Server Name Already Exists. Enter a New Server Name: "`
		read_valid "server_name" "$str" "Server Name Already Exists. Enter a New Server Name: "
		CheckUniqServerName
		server_status=$?
	done
	echo ""


	str=`gettext nds "Server context is the Fully Distinguished Name (FDN) of the container under with the server object resides. [Ex: ou=servers.o=myorg]"` 
	echo "$str"
	echo ""
	str=`gettext nds "SERVER CONTEXT: "`
	read_valid "server_cxt" "$str" "SERVERCONTEXT"
	echo""

	str=`gettext nds "You need the credentials of a user in the tree for configuring the server. (Refer to the eDirectory Administration Guide for the effective rights required for such a user). [Ex: cn=admin.ou=users.o=myorg]"`
	echo "$str"
	echo ""
	str=`gettext nds "ADMIN USER: "`
	read_valid "admin_usr" "$str" "ADMINUSER"
	echo ""
	
	str=`gettext nds "Set eDirectory Admin group[y/n]: "`
	read_valid "admin_grpchk" "$str" "ADMINGRPCHK"
	if [ "$admin_grpchk" = "Y" -o "$admin_grpchk" = "y" ]
	then
        	str=`gettext nds "eDirectory Admin group: "`
        	read_valid "admin_grp" "$str" "ADMINGRPNAME"
	fi
	echo ""
        
	str=`gettext nds "NCP Port number to listen on: "`
        read_valid "port_number" "$str" "PORT"
        echo ""

	str1=`gettext nds "Please specify the absolute location for this instance of eDirectory. The dib and log files go into this directory. [Ex: "` 
	echo "$str1 /home/$username/instance$ctr/]"
	echo ""
	str=`gettext nds "Instance location: "`
	read_valid "instdir" "$str" "PATH"
	echo ""

	str1=`gettext nds "Please specify the absolute location and filename of the configuration file. [Ex:"`
        echo "$str1 /home/$username/instance$ctr/nds.conf]"
	echo ""
	str=`gettext nds "Configuration file: "`
	read_valid "conf_file" "$str" "FILE"
	echo ""
	ndsconfig $operation -t $tree_name $optional_param -S $server_name -n $server_cxt -a $admin_usr -b $port_number -d "$instdir/data/dib" -D $instdir --config-file $conf_file -g$admin_grp 
	# Check that the instance was configured successfully
	grep -q "$conf_file" "$uid_list" 2>/dev/null
	if [ $? -eq 0 ]; then
		no_instances="no"
	fi
}

##### Check Server Name is Uniq  ##############
CheckUniqServerName()
{
	if [ -f "$trac_file" ]; then
		cat $trac_file | xargs grep "n4u.nds.server-name" | awk -F"=" '{print $2}' | grep "^${server_name}$" >/dev/null 2>&1
       		var=$?
        	if [ "$var" -eq "0" ]
        	then
			return 0
        	else
             		return 1
       		fi
	else
		return 1
	fi
}
#### list_instances() ####
# List the details of the configured eDirectory server instances 
list_instances()
{
	ctr=0
	for inst in `echo $uid_list`
	do
		username=`ls -l $inst| $AWK '{print $3}'`
		id $username >/dev/null 2>&1
		if [ $? -ne 0 ]
		then
			if [ "$current_user" = "root" ]
			then
				str=`gettext nds "Unable to resolve user with UID"`
				echo "$str : $username!"
				echo
				str=`gettext nds "CAVEAT: It might be possible that the user is temporarily not resolvable due to non-avaibalitly of a name service."`
				echo $str
				echo
				str=`gettext nds "Would you like to remove the list of instances configured by this user?"`
				echo_prompt_line "$str ('y' or 'n') [n]: "
				read if_y
				if [ "$if_y" = "y" -o "$if_y" = "Y" ]
				then
					rm -f $inst
				fi
			fi
			continue
		fi
		echo
       	 if [ "$no_instances" = "no" ]
		then	
			str=`gettext nds "The following are the instances configured by"`
			echo "$str $username"
		fi
	
		for line in `cat $inst`
		do
			ctr=`expr $ctr + 1`
			if test ! -r "$line"
			then
				if [ "$current_user" = "root" -o "$current_user" = "$username" ]
				then
					str=`gettext nds "Unable to read the configuration file"`
					echo "$str : $line"
					echo
					str=`gettext nds "CAVEAT: It is possible that the filesystem is temporarily not mounted or not accessible."`
					echo $str
					echo
					str=`gettext nds "Remove this from the list of instances configured by "`
					echo_prompt_line "$str $username? ('y' or 'n') [n]: "
					read if_y
					if [ "$if_y" = "y" -o "$if_y" = "Y" ]
					then
						slash_line=`echo $line |awk -F'/' '{for(i=2;i<=NF;i++)printf("\\\/%s", $i);}'`
						sed_cmd="sed '/^$slash_line$/D' $inst | tee $inst 1>/dev/null"
						eval $sed_cmd
					fi
				fi
				continue
			fi
			echo
			DisplayInstance $line $ctr
		done
	done
}
#### End of list_isnances() ####


#### DisplayInstance() ####
# Display the details of the server instances such as the conf filelocation,
# server DN, server IP & port, server UP/DOWN
DisplayInstance()
{
	confFile=$1
	instNum=$2
	interface=`grep "n4u\.server\.interfaces" $confFile | cut -f2 -d'='`

	utf_server_name=`grep -i "n4u\.nds\.server-name" $confFile 2>/dev/null | cut -f2 -d=` 
	echo "$utf_server_name" | iconv -f $UTF_CHARMAP -t $LOCAL_CHARMAP > /dev/null 2>&1

	if [ "$?" -eq 0 ]
	then
		server_name=`echo "$utf_server_name" | iconv -f $UTF_CHARMAP -t $LOCAL_CHARMAP`
	else
		server_name="$utf_server_name"
	fi

	utf_server_cxt=`grep -i "n4u\.nds\.server-context" $confFile | sed 's/n4u\.nds\.server-context=//'`
	echo "$utf_server_cxt" | iconv -f $UTF_CHARMAP -t $LOCAL_CHARMAP > /dev/null 2>&1
	if [ "$?" -eq 0 ]
	then
		server_cxt=`echo "$utf_server_cxt" | iconv -f $UTF_CHARMAP -t $LOCAL_CHARMAP`
	else
		server_cxt="$utf_server_cxt"
	fi

	tree_name=`grep -i "n4u\.base\.tree-name" $confFile 2>/dev/null | cut -f2 -d=`

	server_FDN=" .CN=$server_name.$server_cxt.T=$tree_name."
	tr_server_FDN=`echo $server_FDN |tr "[a-z]" "[A-Z]"`
	tl_server_FDN=`echo $tr_server_FDN |sed s/[a-zA-Z]*=//g`

	# test_interface_name=`echo $ip_address|grep [a-zA-Z]`

	PIDDIR=`grep -i "n4u.server.vardir" $confFile | cut -f2 -d=`

	if [ -f "$PIDDIR/ndsd.pid" ]
	then
		ndsd_pid=`cat $PIDDIR/ndsd.pid`

		if [ -z "$ndsd_pid" ]
		then
			activity=0
		else
 			activity=`ps -p $ndsd_pid | grep -c ndsd` 
		fi
	else
		activity=0
	fi

	if [ "$activity" -gt 0 ]
	then
		status=`gettext nds "ACTIVE"`
		echo "[$instNum] $confFile : $tl_server_FDN : $interface : $status"
	else
		status=`gettext nds "INACTIVE"`
		echo "[$instNum] $confFile : $tl_server_FDN : $interface : $status"
	fi
}
#### End of DisplayInstance() ####
display_menu()
{
echo

       	str=`gettext nds "Enter "`
       	echo_prompt_line "$str"
#	if [ "$uid" = "all"  -o "$current_user" != "$username" ]
#	then 
		echo_prompt_line "[r] "
		str=`gettext nds "to refresh list, "`
		echo_prompt_line "$str"
#	fi
	if [ "$uid" != "all"  -a "$current_user" = "$username" -a "$uid_list" = "$trac_file" ]
#	if [ "$uid_list" = "$trac_file" ]
	then
		if [ $ctr -ge 1 ]
		then
        		echo_prompt_line  "[1 - $ctr] "
        		str=`gettext nds "for more options, "`
        		echo_prompt_line "$str"
		fi

      		echo_prompt_line "[c] "
        	str=`gettext nds "for creating a new instance "`
        	echo_prompt_line "$str"
	fi
	str=`gettext nds "or "`
	echo_prompt_line "$str"
       	echo_prompt_line "[q] "
       	str=`gettext nds "to quit: "`
       	echo_prompt_line "$str"
	read selection
	if [ -f /etc/novell-release ]; then
		instance_num=$selection
	fi
	display_second_menu $selection
}

main_menu()
{
	 trac_file=`echo $conf_dir/.edir/instances.$uid`

	 if [ "$no_instances" = "no" ]; then
		  list_instances

		  if [ "$uid"  = "all" ]; then
				exit
		  fi
	 else
		if [ "$uid"  = "all" ]; then
                                exit
                fi
		uid_list="$trac_file"
	 fi
	 
	 display_menu
}

display_second_menu()
{
local_selection=$1
instance_choice="no"
echo $local_selection  | grep '^[1-9][0-9]*$' > /dev/null 2>&1
if [ "$?" -eq "0" ]
then
	instance_choice="yes" 
else
	instance_choice="no"
fi
if [ "$instance_choice" = "yes" -a "$uid" != "all"  -a "$current_user" = "$username" ]
then
	if [ "$local_selection" -gt "$ctr" -o "$local_selection" -le 0 ]
	then
		str=`gettext nds "Invalid selection!"` 
		echo $str
		display_menu
	else
		tot_lines=`wc -l $trac_file|awk '{print $1}'`
		less_lines=`expr $tot_lines - $local_selection`
		conf_file=`head -$local_selection $trac_file | tail -1` 

		echo
		str=`gettext nds "SELECTED INSTANCE:"`
		echo ${str}
		DisplayInstance $conf_file $local_selection
		echo
		str=`gettext nds "List the replicas on the server"`
		echo "[l] $str"
		str=`gettext nds "Start the instance"`
		echo "[s] $str"
		str=`gettext nds "Stop the instance"`
		echo "[k] $str"
		str=`gettext nds "Run ndstrace"`
		echo "[t] $str"
		str=`gettext nds "Deconfigure"`
		echo "[d] $str"
		str=`gettext nds "Back to previous menu"`
		echo "[b] $str"
		str=`gettext nds "Quit"`
		echo "[q] $str"
		echo
		str=`gettext nds "What do you want to do with this instance? [ Choose from above]: "`
		echo_prompt_line "$str"
		read response
	fi
fi
		perform_choice $local_selection $response
}


perform_choice()
{
local_selection=$1
local_response=$2
echo
if [ "$instance_choice" = "yes" ]
then
		case $local_response in
		l|L) $base_dir/opt/novell/eDirectory/bin/ndsstat -r  --config-file $conf_file;;
		s|S) 
			NonRoot_RHEL7
			if [ $? -eq 3 ] ; then

				ndsconf_dir=`dirname "$conf_file"`

                                if [ -f /etc/novell-release ]; then
			                instance_source="main_menu"
                                        isFirstInstance
                                        if [ $first_instance -eq 1 ]; then
                                                templateFileAttach="ndsd"
                                                print_action start
                                                systemctl $systemdparam start $templateFileAttach.service
                                        else
                                                templateFileAttach=`echo "$ndsconf_dir/env" | sed "s|/|-|g"`
                                                configFile=`echo "$conf_file" | sed "s|/|-|g"`
                                                print_action start
                                                systemctl $systemdparam start ndsdtmpl$configFile@$templateFileAttach.service
                                        fi
                                else
                                        templateFileAttach=`echo "$ndsconf_dir/env" | sed "s|/|-|g"`
                                        configFile=`echo "$conf_file" | sed "s|/|-|g"`
                                        print_action start
                                        systemctl $systemdparam start ndsdtmpl$configFile@$templateFileAttach.service
                                fi
			else
				NDS_CONF=$conf_file $base_dir/$init_location/ndsd start
			fi
		;;

		k|K) 
			NonRoot_RHEL7
			if [ $? -eq 3 ] ; then
				ndsconf_dir=`dirname "$conf_file"`

                                if [ -f /etc/novell-release ]; then
			                instance_source="main_menu"
                                        isFirstInstance
                                        if [ $first_instance -eq 1 ]; then
                                                templateFileAttach="ndsd"
                                                print_action stop
                                                systemctl $systemdparam stop $templateFileAttach.service
                                        else
                                                templateFileAttach=`echo "$ndsconf_dir/env" | sed "s|/|-|g"`
                                                configFile=`echo "$conf_file" | sed "s|/|-|g"`
                                                print_action stop
                                                systemctl $systemdparam stop ndsdtmpl$configFile@$templateFileAttach.service
                                        fi
                                else
                                        templateFileAttach=`echo "$ndsconf_dir/env" | sed "s|/|-|g"`
                                        configFile=`echo "$conf_file" | sed "s|/|-|g"`
                                        print_action stop
                                        systemctl $systemdparam stop ndsdtmpl$configFile@$templateFileAttach.service
                                fi

			else
				NDS_CONF=$conf_file $base_dir/$init_location/ndsd stop
			fi
		;;

		t|T) $base_dir/opt/novell/eDirectory/bin/ndstrace --config-file $conf_file;;
		d|D)
			if [ "$OESENABLED" = "1" ]
			then
				operation_OES
				operation_OES_Status=$?
                                if [ "$operation_OES_Status" = "1" ]; then
                                        display_second_menu $local_selection
                                fi
			fi
			$base_dir/opt/novell/eDirectory/bin/ndsconfig rm --config-file $conf_file
			# Set the 'no_instances' flag if it was the last instance that was deconfigured
			if [ "`wc -l ${uid_list} | ${AWK} '{print $1}'`" = "0" ]; then
				no_instances="yes"
				ctr=0
			fi
			main_menu
		;;

		b|B) main_menu;;
		q|Q) exit;;
		*)
			str=`gettext nds "Invalid selection!"` 
			echo $str
		esac
		echo
		display_second_menu $local_selection $local_response
else 
	case $selection in
		r|R) main_menu;;
		q|Q) exit;;
		c|C) 
			if [ "$OESENABLED" = "1" ]
			then
				operation_OES
				operation_OES_Status=$?
                                if [ "$operation_OES_Status" = "1" ]; then
                                        main_menu
                                fi
			fi
			str=`gettext nds "You have opted to create a new instance of eDirectory. Ensure that you have all the configuration planned before you proceed further. (Refer to the eDirectory Installation Guide for more information on the configuration.)"`
			echo "$str"
			echo ""
			str=`gettext nds "If you choose to continue and if you are unsure of any of the configuration values, please abort and use the ndsconfig utility to create the new instance."`
			echo "$str"
			echo ""
			str=`gettext nds "Do you want to continue? "`
			echo_prompt_line "$str (y or [n]): "
			read ans
			if [ "$ans" = "y" -o "$ans" = "Y" ]
			then
				create_new_instance
			fi
			main_menu;;
		*)	str=`gettext nds "Invalid selection!"` 
			echo $str
			display_menu
	esac
fi
}
main_menu
exit 0
