#!/bin/sh
PATH=/usr/xpg4/bin:$PATH
dir=`which ndsautotrace`
NDSHOME=`echo $dir | awk -F"opt" '{print $1}'`

TEXTDOMAINDIR="$NDSHOME/opt/novell/eDirectory/share/locale"
export TEXTDOMAINDIR

#    Author: PAH
#   Company: NetIQ 
# Copyright: (c) 2013 NetIQ Corporation and its affiliates. All Rights Reserved. 
#            All rights reserved.
#  
#   Purpose: To automatically start 'ndstrace' at the first opportunity,
#            enable the specified tags and trace to the log file 
#
# Code Standard: To allow the script to run on multiplatforms, ensure that
#                functions follow the following standard:
#
#                # Comment describing what the function does
#                functionName()
#                {
#                       doActionsInsideFunction
#                }


##### Start of general script variables #####
setVars_General()
{
        # Script version and title
        SCRIPT_VERSION_MAJOR=1
        SCRIPT_VERSION_MINOR=0
        SCRIPT_VERSION_REVISION=5
        SCRIPT_VERSION="$SCRIPT_VERSION_MAJOR.$SCRIPT_VERSION_MINOR.$SCRIPT_VERSION_REVISION"
        SCRIPT_TITLE="Autotracing for 'ndstrace'"

        # Supported Operating Systems for this script
        SUPPORTED_OS="Linux SunOS HPUX AIX"

        # Null Device
        NULLDEV=/dev/null

        # Default CMD Variables
        CMD_HOSTOS="uname -s"

        # List of the signals that can be trapped by the script eg: If someone h its CTRL-C then we want to be able to clean up the temp files etc.
        TRAP_SIGNALS="1 2 3 5"
                                   
        # Script configuration file
        CONF_FILE="ndsautotrace.conf"
        CONF_PATHS="$NDSHOME/etc/opt/novell/eDirectory/conf $NDSHOME/etc"

        # Configuration file keyword deliminator
        CONF_FILE_DELIM="="

        # Configuration file comment character
        CONF_FILE_COMMENT="#"

        # List of terminal types that should have color OFF by default
        TERMINAL_TYPES="xterm"

        # Initialize the values for "YES", "NO", "INVALID", "TRUE", "FALSE" "ENABLED" and "DISABLED"
        TRUE=0; FALSE=1; YES=$TRUE; NO=$FALSE; INVALID=999; ENABLED=1; DISABLED=2

        # Debug messages or not?
        DEBUG=$DISABLED

        # End Of Line Marker
        EOL="\n"

        # Standard NDSTrace tags that we ALWAYS want
        NDSTRACE_TAGS_STANDARD="+TIME +TAGS"

        # Default NDS tags
        NDSTRACE_TAGS_DEFAULT=ALL

        # Default NDS Trace file size in bytes (20MB default)
        NDSTRACE_MAX_FILE_SIZE=20971520

        # Default number of instances
        INSTANCE_COUNT=0

	# Error message
	ERR_MSG=`gettext nds "Internal error"`
}
##### End of general script variables #####


##### Start of Host OS specific Variables #####
# Set the Linux specific variables
setVars_Linux()
{
        FULLHOSTNAME="`hostname --long`"

        # Language for the script
        #SCRIPT_LANG="en_US"

        # Ensure language is set to $SCRIPT_LANG
        #if [ ! -z "$LANG" -a "$LANG" != "$SCRIPT_LANG" ]
        #then
        #        debug "LANG is not set to $SCRIPT_LANG, currently $LANG. Changing."
        #        OLD_LANG="$LANG"
        #        LANG="en_US"
        #        export LANG
        #        debug "LANG=$LANG OLD_LANG=$OLD_LANG"
        #fi
}

# Set the SunOS specific variables
setVars_SunOS()
{
        FULLHOSTNAME="`hostname`.`domainname`"
}

# Set the HP-UX specific variables
setVars_HPUX()
{
        FULLHOSTNAME="`hostname`.`domainname`"
}

# Set the AIX specific variables
setVars_AIX()
{
        FULLHOSTNAME="`hostname`.`domainname`"
}
##### End of Host OS Variables #####

# Enable the colors but not if an XTERM
enableColorsIfNeeded()
{
        for TERM_TYPE in $TERMINAL_TYPES
        do
                if [ "$TERM_TYPE" = "$TERM" ]
                then
                        setANSIColours "OFF"                    
                        return 0
                fi
        done

        setANSIColours "ON"
}

##### Set the ANSI colours #####
# Enable or disable ANSI colours
# Input: $1="ON" or "OFF"
setANSIColours()
{
        if [ -z "$1" ]
        then
                dispError "Internal Error:  setANSIColours() was not passed a parameter."
                abortScript "1"
        else
                case $1 in
                "on" |"ON")
                        enableANSIColours;;
                "off" |"OFF")
                        disableANSIColours;;
                *)
                        dispError "Internal Error:  setANSIColours() was passed an invalid parameter of '$1'."
                        abortScript "1"
                esac
        fi
}

enableANSIColours()
{
  #esc="\033"
  esc=""

  fgblack="${esc}[30m";   fgred="${esc}[31m";    fggreen="${esc}[32m";
  fgyellow="${esc}[33m";  fgblue="${esc}[34m";   fgpurple="${esc}[35m";
  fgcyan="${esc}[36m";    fgwhite="${esc}[37m";
  
  bgblack="${esc}[40m";   bgred="${esc}[41m";   bggreen="${esc}[42m";
  bgyellow="${esc}[43m";  bglue="${esc}[44m";   bgpurple="${esc}[45m";
  bgcyan="${esc}[46m";    bgwhite="${esc}[47m";

  boldon="${esc}[1m";    boldoff="${esc}[22m";
  italicson="${esc}[3m"; italicsoff="${esc}[23m";
  ulon="${esc}[4m";      uloff="${esc}[24m";
  invon="${esc}[7m";     invoff="${esc}[27m";

  reset="${esc}[0m";
}

# Disable the ANSI colours
disableANSIColours()
{
  esc=""
  
  fgblack="";   fgred="";    fggreen="";
  fgyellow="";   fgblue="";   fgpurple="";
  fgcyan="";    fgwhite="";
  
  bgblack="";   bgred="";   bggreen="";
  bgyellow="";   bglue="";   bgpurple="";
  bgcyan="";    bgwhite="";

  boldon="";    boldoff="";
  italicson=""; italicsoff="";
  ulon="";      uloff="";
  invon="";     invoff="";

  reset="";
}

# Reset the ANSI colours on the terminal back to normal
resetANSIcolours()
{
        printf "${reset}"
}
##### End of the ANSI colours #####


##### Start of Auxillary Functions #####
# Determine which OS the script is being run on
# Output: OS contains operating system
getHostOS()
{
        OS="`$CMD_HOSTOS`"

        # Convert HP-UX to HPUX as function or variable names don't like hyphens in them
        if [ "$OS" = "HP-UX" ]
        then
                OS="HPUX"
        fi
}

# Verify the the host OS that this script is executing on is supported
# by the script
verifySupportedOS()
{
        for CHECKOS in $SUPPORTED_OS
        do
                if [ "$OS" = "$CHECKOS" ]
                then
                        return 1
                fi
        done
        str=`gettext nds "Sorry, the following operating system is not supported by this script : "`
	printf "$str$OS"
        exit 1
}


# Restore the language environment variable
restoreLanguage()
{
        debug "LANG=$LANG  OLD_LANG=$OLD_LANG"
        #if [ ! -z "$OLD_LANG" ]
        #then
                #LANG="$OLD_LANG"
                #export LANG
                #debug "Previous language environment restored. LANG=$LANG"
        #fi
}

# Calculates the length of a string
# Input: $1=string to calculate
# Output: LENGTH= number of chars in string from $1
length()
{
        LENGTH="`echo \"$1\"| wc -c`"
        # remove one from the total due to the CR at the end
        LENGTH="`expr $LENGTH - 1`"
}

# Register for signal trapping.  This is used so that the temp files can be cleaned up.
registerSignalTraps()
{
        trap 'abortScriptFromUser' $TRAP_SIGNALS
}

# Unregister from signal traps
unregisterSignalTraps()
{
        trap - $TRAP_SIGNALS
}

# Aborts the script because the user requested to. This function is what the signal traps are registered for.
abortScriptFromUser()
{
        echo
        abortScript "99" "$YES"
}

# Display debug message and log it to default log file
# Input: $1=Debug Message
debug()
{
        if [ "$DEBUG" = "$ENABLED" ]
        then
                printf "DBG: $1\n"
#                logger "$PRODUCT_SHORT_NAME-$PRODUCT_VERSION(DBG): $1"
        fi
}

# Display debug message and log it to default log file without the eol char
# Input: $1=Debug Message
debugNoEOL()
{
        if [ "$DEBUG" = "$ENABLED" ]
        then
                printf "DBG: $1"
#                logger "$PRODUCT_SHORT_NAME-$PRODUCT_VERSION(DBG): $1"
        fi
}

# Display debug message and log it to default log file without displaying the DBG prefix
# Input: $1=Debug Message
debugNoPrefix()
{
        if [ "$DEBUG" = "$ENABLED" ]
        then
                printf "$1\n"
#                logger "$PRODUCT_SHORT_NAME-$PRODUCT_VERSION(DBG): $1"
        fi
}


# Clear the screen
clearscreen()
{
        # Only clear the screen if debug is NOT enabled
        if [ "$DEBUG" != "$ENABLED" ]
        then
                clear
        fi
}

# Abort the script.  
# Input:  $1=OPTIONAL! exit code 
#         $2=OPTIONAL! (requires $1) "$YES" = Really abort - ignore whatever the FORCE switch is set to 
abortScript()
{
        SCRIPT_ABORTED_MSG="${boldon}${fgred}Script execution has been aborted.\n${reset}"
        SCRIPT_NOT_ABORTED_MSG="${boldon}${fgred}Script was not aborted due to FORCE installation enabled on the command line.\n${reset}"

        if [ -z "$1" ]
        then
                EXIT_CODE=0
        else
                EXIT_CODE=$1
        fi

        if [ "$FORCE" = "$TRUE" ]
        then
                if [ "$2" != "$YES" ]
                then
                        printf "$SCRIPT_NOT_ABORTED_MSG"
                else
                        restoreLanguage
                        printf "$SCRIPT_ABORTED_MSG"
                        exit $EXIT_CODE
                fi
        else
                restoreLanguage
                #printf "$SCRIPT_ABORTED_MSG"
                exit $EXIT_CODE
        fi
}

# Display the script title
dispTitle()
{
        printf "${reset}${boldon}$EOL"
        printf "+-----------------------------------------------------------------------------+$EOL"
        printf "| %45s %31s$EOL" "$PRODUCT_TITLE $SCRIPT_TITLE" "|"     
        printf "| Product Version: %-9s     OS: %-10s     Script Version: %-10s|$EOL" "$PRODUCT_VERSION" "$OS" "$SCRIPT_VERSION"
        printf "+-----------------------------------------------------------------------------+${reset}$EOL"
}

# Prompt the user for Yes or No
# Input: $1= Prompt message
#        $2= $YES or $NO for default
promptForYesOrNo()
{
        if [ -z "$1" ]
        then
                dispError "Internal Error: promptForYesOrNo() was not passed a parameter."
                abortScript "1"
        fi
        
        # Initialize certain variables
        RC=$INVALID
        DEFAULT="$2"

        # If unattended installation was requested then do not display the prompt
        if [ "$UNATTENDED" = "$TRUE" ]
        then
                printf "${reset}${fgcyan}Unattended installation was requested - proceeding with patch installation.${reset}"
        else
                if [ "$DEFAULT" = "$YES" ]
                then
                        PROMPT_KEYS="Y/n"
                else
                        PROMPT_KEYS="y/N"
                fi
                
                # Loop until either "Y", "N" or ENTER is pressed.
                while [ "$RC" = "$INVALID" ]
                do
                        #printf "%s" "$PROMPT_MSG"
                        printf "${boldon}${fgyellow}$1 ${fgwhite}[$PROMPT_KEYS]${reset} "

                        INPUT=
                        read INPUT

                        case $INPUT in
                                "")             RC=$DEFAULT ;;
                                "n" | "N")      RC=$NO ;;
                                "y" | "Y")      RC=$YES ;;
                                *)              printf "${boldon}${fgred}Please enter either \"${fgwhite}Y${fgred}\", \"${fgwhite}N${fgred}\" or just press <ENTER> to accept the default.${reset}$EOL" ;;
                        esac

                        if [ -z "$RC" ]
                        then
                                dispError "Internal Error:  promptForYesOrNo() was provided a default that was not handled."
                                abortScript "1"
                        fi
                done
        fi

        return $RC
}

# Display an error message. It will 'bordered' by equal signs (eg: ====). 
# If "NO_ERRORS" is true then don't display the error. Not really a good idea
# as you won't know why the error occured.
dispError()
{
        if [ "$NO_ERRORS" != "$TRUE" ]
        then
                printf "%s${boldon}${fgred}==================================== ERROR ====================================${reset}$EOL" ""
                printf "%s${boldon}${fgred}$1${reset}$EOL" ""
                printf "%s${boldon}${fgred}===============================================================================${reset}$EOL" ""
        fi
}

# Display a note on the screen to the user. It will 'bordered' by equal signs (eg: ====). 
dispNote()
{
        printf "%s${fgcyan}${boldon}==================================== NOTE ====================================${reset}$EOL" ""
        printf "%s${fgcyan}${boldon}$1${reset}$EOL" ""
        printf "%s${fgcyan}${boldon}==============================================================================${reset}$EOL" ""
        printf "$EOL"
}

# Display a line for certain length
# Input: $1=Char to use
#        $2=Number of chars to display
dispLine()
{
    TMP_COUNTER=0
    CHAR_TO_USE="$1"
    NUM_CHARS="$2"
    while [ $TMP_COUNTER -lt $NUM_CHARS ]
    do
        printf "$CHAR_TO_USE"
        TMP_COUNTER="`expr $TMP_COUNTER + 1`"
    done
}

# Read a keyword from the configuration file and return
# the value(s) in $CONF_FILE_RESULT
# Input:  $1 = Keyword 
#         $2 = (Boolean) Keyword is optional
# Output: $CONF_FILE_RESULT = Data after the keyword. If blank then no data or keyword not found
readConfFile()
{
        if [ -z "$1" ]
        then
                dispError "Internal Error:  readConfFile() was not passed a parameter."
                abortScript "1"
        fi
        CONF_FILE_RESULT=

        KEYWORD_IS_OPTIONAL=$2
        if [ -z "$KEYWORD_IS_OPTIONAL" ]
        then
                KEYWORD_IS_OPTIONAL=$TRUE
        fi

        # As long as the configuration file exists then read it, ignoring comments
        if [ -f "$CONF_FILE" ]
        then
                debug "readConfFile(): Reading keyword $1"
                debug "readConfFile(): cat $CONF_FILE | egrep -v \"^$CONF_FILE_COMMENT\" | grep $1"
                CONF_FILE_DATA="`cat $CONF_FILE | egrep -v \"^$CONF_FILE_COMMENT\" | grep $1`"
                debug "readConfFile(): CONF_FILE_DATA=$CONF_FILE_DATA"
                if [ ! -z "$CONF_FILE_DATA" ]
                then
                        CONF_FILE_RESULT="`echo $CONF_FILE_DATA | cut -d $CONF_FILE_DELIM -f 2`"
                        debug "readConfFile(): CONF_FILE_RESULT=$CONF_FILE_RESULT"
                fi
        fi

        if [ -z "$CONF_FILE_RESULT" -a $KEYWORD_IS_OPTIONAL = $FALSE ]
        then
            dispError "Internal Error: $1 was not set in $CONF_FILE"
            abortScript "1"
        fi

}

# Determine if multiple instances are support, and prompt for one if necessary
determineInstance()
{
        # Determine if this version of eDirectory supports multiple instances
        ndsmanage --version 1>$NULLDEV 2>$NULLDEV
        RC=$?

        if [ "$RC" = "0" ]
        then
                MULTIPLE_INSTANCE_SUPPORT="$YES"
                # eDirectory supports multiple instances, most likely to be rosalind.
                debug "[>=rosalind] 'ndsmanage' found. eDirectory supports multiple instances"

                # If config file has already been supplied by the user then don't bother with determining 
                # which instance to run against.
                if [ "$USER_SUPPLIED_CONF" != "" ]
                then
                        debug "determineInstance() Instance '$USER_SUPPLIED_CONF' has been supplied via the command line"
                        INSTANCE_CONF="$USER_SUPPLIED_CONF"
                        INSTANCE_CONF_FILE="$INSTANCE_CONF"
                        CONFIG_FILE_PARM="--config-file" 
                        return
                fi

                #ndstrace $CONFIG_FILE_PARM $INSTANCE_CONF
                # determine number of instances installed
                # if more than one, then prompt for selection, otherwise just use the only one found
                instanceCount
                if [ "$INSTANCE_COUNT" = 0 ]
                then
                        dispError "No instances of eDirectory have been configured."
                        abortScript "1"
                fi

                INSTANCE_NUMBER=1
                if [ "$INSTANCE_COUNT" -gt 1 ]
                then
                        str1=`gettext nds "Please select the instance to run ndsautotrace against:"`
			echo "$str1"
                        instanceDisplayAll
			if [ "$OS" = "SunOS" ]
			then
                        	str1=`gettext nds "Instance: "`
				echo "$str1"
                        	read INSTANCE_NUMBER
			else
                        	str1=`gettext nds "Instance: "`
	                        read -p "$str1" INSTANCE_NUMBER
			fi
                fi
                instanceGetConf $INSTANCE_NUMBER

                if [ "$INSTANCE_CONF" = "" ]
                then
                        dispError "Must select a valid eDirectory instance."
                        abortScript "1"
                fi

                INSTANCE_CONF_FILE="$INSTANCE_CONF"
                CONFIG_FILE_PARM="--config-file" 
        else
                MULTIPLE_INSTANCE_SUPPORT="$NO"
                # Could not find ndsmanage, try ndstrace
                ndstrace --version 1>$NULLDEV 2>$NULLDEV
                RC=$?
                if [ "$RC" = "0" ]
                then
                        # eDirectory doesn't support multiple instances, but is currently installed.
                        # Most likely to be at least falcon.
                        debug "[<=falcon] ndsmanage wasn't found, but ndstrace was. Will not use multiple instances"
                        # If config file has already been supplied by the user then don't bother with determining 
                        # which instance to run against.
                        if [ "$USER_SUPPLIED_CONF" != "" ]
                        then
                                debug "determineInstance() Instance '$USER_SUPPLIED_CONF' has been supplied via the command line"
                                INSTANCE_CONF_FILE="$USER_SUPPLIED_CONF"
                                return
                        fi

                        INSTANCE_CONF_FILE=$NDSHOME/etc/nds.conf
                else
                        # Couldn't find ndstrace or ndsmanage, this could mean:
                        # 1. eDirectory nor installed
                        # 2. eDirectory is 8.8, installed, but ndspath was not run. Really can't do anything.
                        debug "Unable to find either ndsmanage or ndstrace. ndspath may not be setup in environment".
                        dispError "Must have eDirectory installed and configured."
                        abortScript "1"
                fi
        fi
}

# Determine number of eDirectory instances
# Output: INSTANCE_COUNT = number of multiple instances found
instanceCount()
{
        INSTANCE_COUNT=`ndsmanage -a | egrep "\[" | wc -l`
        RC=$?
        debug "instanceCount() RC=$? INSTANCE_COUNT=$INSTANCE_COUNT"
        if [ "$RC" != "0" ]
        then
                INSTANCE_COUNT=0
        fi
}

# Display list of eDirectory instances
instanceDisplayAll()
{
        ndsmanage -a | egrep "\["
}

# Determine which nds.conf file is for a particular instance number
# Input: $1 = instance number based on results from instanceDisplayAll
# Output: INSTANCE_CONF = file path for instance configuration file
instanceGetConf()
{
        debug "instanceGetConf() Getting conf file for instance $1"
        INSTANCE_CONF=`ndsmanage -a | grep "\[$1" | awk -F" " '{print $2}'`
        debug "instanceGetConf() Conf file for instance $1 is: $INSTANCE_CONF"
}

# Get the NDS Trace tags
# Input: $1=Tag group from $CONF_FILE
getNDSTraceTags() 
{
        if [ -z "$1" ]
        then
                NDSTRACE_TAG_GROUP="DEFAULT"
        else
                NDSTRACE_TAG_GROUP="$1"
        fi
        
        readConfFile "$NDSTRACE_TAG_GROUP"
        NDSTRACE_TAGS="$NDSTRACE_TAGS_STANDARD $CONF_FILE_RESULT"
}

# Determine if ndstrace is, and has been started via ndsautotrace
# Output: NDSTRACE_RUNNING=$YES | $NO
isNDSTraceRunning()
{
        if [ "$USER_SUPPLIED_CONF" != "" ]
        then
                if [ -f "$USER_SUPPLIED_CONF" ]
                then
                	INSTANCE_CONF="$USER_SUPPLIED_CONF"
		else
                        debug "Provided nds config file with input parameter -c does not exist$EOL"
        		printf "$EOL"
                	dispError "Provided nds config file with input parameter -c does not exist"
                	abortScript "1"
		fi
        fi

	NDSTRACE_PS="`ndstrace $CONFIG_FILE_PARM $INSTANCE_CONF -c "modules" 2>/dev/null | grep "dstrace" | grep "Running"`"
        debug "isNDSTraceRunning() INSTANCE_COUNT=$INSTANCE_COUNT INSTANCE_CONF=$INSTANCE_CONF NDSTRACE_PS=$NDSTRACE_PS"
        
        if [ "$NDSTRACE_PS" = "" ]
        then
                debug "isNDSTraceRunning() NDSTrace is not running"
                NDSTRACE_RUNNING=$NO
        else
                debug "isNDSTraceRunning() NDSTrace is already running"
                NDSTRACE_RUNNING=$YES
        fi
}

# Get the NDS Trace max file size
getNDSTraceMaxFileSize()
{
        # If a dstrace max file size is set in the conf file then 
        # change it to whatever is specified
        readConfFile "MAX_FILE_SIZE" $TRUE
        if [ ! -z "$CONF_FILE_RESULT" ]
        then
                NDSTRACE_MAX_FILE_SIZE="$CONF_FILE_RESULT"
        fi
        debug "NDSTrace Max File Size is $NDSTRACE_MAX_FILE_SIZE"
}

# Set the NDS Trace tags from the global var NDSTRACE_TAGS
setNDSTraceTags()
{
        for NDSTRACE_TAG in $NDSTRACE_TAGS
        do
                debug "Setting dstrace tag $NDSTRACE_TAG"
                executeNDSTraceCmd "set dstrace=$NDSTRACE_TAG"
                str=`gettext nds "The following tag has been set : "`
		echo "$str$NDSTRACE_TAG"
        done
}

# Execute a trace command
# Input: $1=Trace command
executeNDSTraceCmd()
{
        NDSTRACE_COMMAND_COMPLETE=1
        while [ $NDSTRACE_COMMAND_COMPLETE != 0 ]
        do
                debug "Executing ndstrace command: $1"
                ndstrace $CONFIG_FILE_PARM $INSTANCE_CONF -c "$1"
                NDSTRACE_COMMAND_COMPLETE=$?
                debug "Return code from command '$1' was: $NDSTRACE_COMMAND_COMPLETE"
                if [ $NDSTRACE_COMMAND_COMPLETE != 0 ]
                then
                        sleep 1
                fi
        done
}

# Start NDS Trace
startNDSTrace()
{
        IS_NDSD_RUNNING=1
	TMP_COUNTER=1
        str1=`gettext nds "Attempting to start 'ndstrace'..."`
	printf "$str1"
        while [ $IS_NDSD_RUNNING = $FALSE ]
        do
                printf "."
                debug "startNDSTrace() Checking for $INSTANCE_CONF_FILE"
                if [ -f "$INSTANCE_CONF_FILE" ]
                then
                        if [ "$MULTIPLE_INSTANCE_SUPPORT" = "$NO" ]
                        then
                                CONFIG_FILE_PARM=
                                INSTANCE_CONF=
                        fi

                        debug "startNDSTrace() executing: ndstrace $CONFIG_FILE_PARM $INSTANCE_CONF -c modules" 
                        ERR_MSG=`ndstrace $CONFIG_FILE_PARM $INSTANCE_CONF -c "modules" 2>&1`
                        RC=$?
                        debug "Attempt to check if ndsd is loaded returned $RC"
                        if [ $RC = 0 ]
                        then
                                IS_NDSD_RUNNING=$TRUE
			elif [ $TMP_COUNTER -eq 10 ]
			then
        	        	printf "$EOL"
                	       	dispError "$ERR_MSG"
	        		abortScript "1"
			fi
		else
                	printf "$EOL"
                       	dispError "Instance config file $INSTANCE_CONF_FILE does not exist"
	        	abortScript "1"
                fi

                # Wait for a little bit, so that once the ndsd daemon
                # starts, the loader can load the other libs that
                # ndstrace depends on
                sleep 1
        	TMP_COUNTER="`expr $TMP_COUNTER + 1`"
        done

        printf "$EOL"
        debug "ndstrace was successful with 'modules'"

        # Spawn ndstrace to background process and redirect 
        nohup ndstrace -l $CONFIG_FILE_PARM $INSTANCE_CONF 1>$NULLDEV 2>$NULLDEV &
        debug "Launch of ndstrace -l $CONFIG_FILE_PARM $INSTANCE_CONF returned $?"
        
        # Sleep for a second so that there is time for ndstrace to register
        # its commands
        sleep 1

        executeNDSTraceCmd "set dstrace=nodebug"
        executeNDSTraceCmd "ndstrace file on" # 1>$NULLDEV 2>$NULLDEV
        
        # Set the max file size for ndstrace
        if [ ! -z "$NDSTRACE_MAX_FILE_SIZE" ]
        then
                executeNDSTraceCmd "set dstrace=*M$NDSTRACE_MAX_FILE_SIZE"
                str1=`gettext nds "ndstrace maximum file size is set to the following : "`
		echo "$str1$NDSTRACE_MAX_FILE_SIZE"
        fi      

        return $RC
}

# Stop NDS Trace
stopNDSTrace()
{
        debug "stopNDSTrace() Stopping ndstrace..."
        determineInstance
        isNDSTraceRunning
        if [ "$NDSTRACE_RUNNING" = "$NO" ]
        then
                dispError "ndsautotrace should be running before attemping to stop it. \nPlease start it first via ndsautotrace."
                abortScript "1"
        fi
        ndstrace $CONFIG_FILE_PARM $INSTANCE_CONF -c "dstrace file off"
        ndstrace $CONFIG_FILE_PARM $INSTANCE_CONF -c "dstrace screen off"
        ndsstat $CONFIG_FILE_PARM $INSTANCE_CONF -c "unload dstrace"
        RC=$?

        if [ $RC = 0 ]
        then
                str1=`gettext nds "ndstrace has been stopped."`;
		echo "$str1"
        else
                exit 0
        fi
}

##### End of Action Functions #####

# Check the command line to see if any command line switches were provided
checkCommandline()
{
        while [ "$#" -gt "0" ]
        do
            COMMAND_LINE="$COMMAND_LINE $1"
            case $1 in
                    "-h" | "--help")          dispCommandlineHelp ;;
                    "-n" | "--noansi")        setANSIColours "OFF";;
                    "-y" | "--yesansi")       setANSIColours "ON";;
                    "-d" | "--debug")         DEBUG=$ENABLED ;;
                    "-s" | "--stop")          stopNDSTrace ;
                                              exit 0;;
                    "-c" | "--config-file")   shift ;
                                              USER_SUPPLIED_CONF="$1";;
                    *)                        dispCommandlineHelp ;;

            esac
            shift
        done     

        debug "Command line: $COMMAND_LINE"
}

# Display the command line help
dispCommandlineHelp()
{
        setANSIColours "OFF"
        dispTitle
	str1=`gettext nds "Syntax:"`
	str2=`gettext nds "[options]"`
        printf "$str1 $0 $str2$EOL"
	str3=`gettext nds "Where [options] is one of the following switches:"`
        printf "$str3$EOL"
        printf "$EOL"
        printf "  -n   --noansi$EOL"
	str5=`gettext nds "       Disable the use of ANSI colours.  If the terminal type is 'xterm'"`
        printf "$str5$EOL"
	str6=`gettext nds "       then colours will be disabled by default."`
        printf "$str6$EOL"
        printf "$EOL"
        printf "  -y   --yesansi$EOL"
	str8=`gettext nds "       Enable the use of ANSI colours."`
        printf "$str8$EOL"
        printf "$EOL"
	str9=`gettext nds "   --stop"`
        printf "  -s$str9$EOL"
	str10=`gettext nds "       Stops ndstrace."`
        printf "$str10$EOL"
        printf "$EOL"
	str11=`gettext nds "   --config-file"`
        printf "  -c$str11$EOL"
	str12=`gettext nds "       Config file for eDirectory installation."`
        printf "$str12$EOL"
        printf "$EOL"
	str13=`gettext nds "   --help"`
        printf "  -h$str13$EOL"
	str14=`gettext nds "       Displays this command line help."`
        printf "$str14$EOL"
        printf "$EOL"
        exit 2
}


# Main function
main()
{
        setVars_General
        registerSignalTraps
        getHostOS
        verifySupportedOS
        setVars_$OS
        
        enableColorsIfNeeded
        checkCommandline $*
        if [ "$DEBUG" = "$ENABLED" ]
        then
                dispNote "DEBUG Mode has been enabled. Only do this if requested by NetIQ."
        fi

        # Find the conf file, and if not found, create in /etc
        for CONF_PATH in $CONF_PATHS
        do
            debug "Searching for $CONF_PATH/$CONF_FILE..."
            if [ -f "$CONF_PATH/$CONF_FILE" ]
            then
                CONF_FILENAME="$CONF_PATH/$CONF_FILE"
                break
            fi
        done

        if [ -z "$CONF_FILENAME" ]
        then
            CONF_FILE="$NDSHOME/etc/$CONF_FILE"
        else
            CONF_FILE="$CONF_FILENAME"
        fi

        # If multiple instances are setup, then determine which one to work with
        determineInstance

        # Ensure the same instance of ndstrace is not running already
        isNDSTraceRunning
        if [ "$NDSTRACE_RUNNING" = "$YES" ]
        then
                dispError "Another copy of ndstrace is running. Please stop it and try again."
                abortScript "1"
        fi

        # Ensure that the config file exists and if it isn't there
        # just create it with the default settings.
        if [ ! -f "$CONF_FILE" ]
        then
                debug "$CONF_FILE does not exist! Creating it with default settings."
                echo "# NDSTrace Tag groups for 'ndsautotrace'" >> $CONF_FILE
                echo "# Must have a default tag group called \"DEFAULT\"" >> $CONF_FILE
                echo "# Tags are space delimited. Tags $NDSTRACE_TAGS_STANDARD are always set." >> $CONF_FILE
                echo "DEFAULT=$NDSTRACE_TAGS_DEFAULT" >> $CONF_FILE
                echo "MAX_FILE_SIZE=$NDSTRACE_MAX_FILE_SIZE" >> $CONF_FILE
        fi

        getNDSTraceTags
        getNDSTraceMaxFileSize
        startNDSTrace
        setNDSTraceTags

        # Just display the resulting tags
        executeNDSTraceCmd "ndstrace"

	str1=`gettext nds "Max File Size:"`
	str2=`gettext nds "Enabled Tags:"`
	str3=`gettext nds "'ndstrace' is now running in the background and tracing to the log file."`
        printf "$str1 $NDSTRACE_MAX_FILE_SIZE$EOL"
        printf "$str2 $NDSTRACE_TAGS$EOL"
        printf "$EOL$str3$EOL"

        resetANSIcolours
        restoreLanguage
        exit $RC
}

main $*
