#! /bin/sh

# Copyright 2005-2012 The MathWorks, Inc.

#========================= realpath.sh (start) ============================
#-----------------------------------------------------------------------------
# Usage: realpath <filename>
# Returns the actual path in the file system of a file. It follows links. 
# It returns an empty path if an error occurs.
# Return status: 0 if successful.
# If return status is 0, the function echoes out the real path to the file.
# Return status 1 Exceeded the maximum number of links to follow.
# Return status 2 Some other error occurred.
realpath() {
    filename_rpath=$1
    SUCCESS_STATUS_rpath=0
    MAX_LINKS_EXCEEDED_rpath=1
    OTHER_ERROR_rpath=2
    #
    # Now filename_rpath is either a file or a link to a file.
    #
    cpath_rpath=`pwd`

    #
    # Follow up to 8 links before giving up. Same as BSD 4.3
    # We cd into the directory where the file is located, and do a /bin/pwd 
    # to get the name of the CWD.  If the file is a symbolic link, we update 
    # the basename of the file and cd into the directory that the link points 
    # to and repeat the process.
    # Once we arrive in a directory where we do not have a soft-link, we are 
    # done.
    n_rpath=1
    maxlinks_rpath=8
    while [ $n_rpath -le $maxlinks_rpath ]
    do
        #
        # Get directory part of $filename_rpath correctly!
        #
        newdir_rpath=`dirname "$filename_rpath"`
        # dirname shouldn't return empty instead of ".", but let's be paranoid.
        if [ -z "${newdir_rpath}" ]; then
            newdir_rpath=".";
        fi
        (cd "$newdir_rpath") > /dev/null 2>&1
        if [ $? -ne 0 ]; then
            # This should not happen.  The file is in a non-existing directory.
            cd "$cpath_rpath"
            return $OTHER_ERROR_rpath
        fi
        cd "$newdir_rpath"
        #
        # Need the function pwd - not the shell built-in one.  The command 
        # /bin/pwd resolves all symbolic links, but the shell built-in one 
        # does not.
        #
        newdir_rpath=`/bin/pwd`
        # Stip the directories off the filename_rpath.
        newbase_rpath=`basename "$filename_rpath"`

        lscmd=`ls -l "$newbase_rpath" 2>/dev/null`
        if [ ! "$lscmd" ]; then
            # This should not happen, the file does not exist.
            cd "$cpath_rpath"
            return $OTHER_ERROR_rpath
        fi
        #
        # Check for link.  The link target is everything after ' -> ' in 
        # the output of ls.
        #
        if [ `expr "$lscmd" : '.*->.*'` -ne 0 ]; then
            filename_rpath=`echo "$lscmd" | sed 's/.*-> //'`
        else
            #
            # We are done.  We found a file and not a symbolic link.
            # newdir_rpath contains the directory name, newbase_rpath contains 
            # the file name.
            cd "$cpath_rpath"
            echo "$newdir_rpath/$newbase_rpath"
            return $SUCCESS_STATUS_rpath
        fi
        n_rpath=`expr $n_rpath + 1`
    done
    # We exceeded the maximum number of links to follow.
    cd "$cpath_rpath"
    return $MAX_LINKS_EXCEEDED_rpath
}
#========================= realpath.sh (end) ==============================

#========================= pathsetup.sh (start) ============================
#-----------------------------------------------------------------------------
# Usage: warnIfNotInBin <full path> <scriptname>
warnIfNotInBin() {
    # Search for toolbox/distcomp/bin in $1.
    if [ `expr "$1" : ".*toolbox/distcomp/bin/util$"` -eq 0 ]; then
        echo "Warning: $2 should be run only from toolbox/distcomp/bin/util,"
        echo "or using a symbolic link to toolbox/distcomp/bin/util/$2."
        echo ""
    fi
}

# THIS MUST BE RUN FIRST BEFORE SETTING UP THE APPLICATION VARIABLES
# Get the fully qualified path to the script
SCRIPT="$0"
REALPATH=`realpath "$SCRIPT"`
# Get the path to distcomp bin BASE from this by removing the name of the shell
# script.
BASE=`echo $REALPATH | sed -e 's;\/[^\/]*$;;g'`
warnIfNotInBin "$BASE" clusterlogs
# Make sure we are in the correct directory to run setbase.sh
cd "$BASE"
# We're in the bin/util directory, so go up one directory to get to bin
cd ..
# Set base directory variables
. util/setbase.sh
cd "$BASE"
#-----------------------------------------------------------------------------
#========================= pathsetup.sh (end) ==============================

usage()
{
echo
echo "clusterlogs:  Set the log level of the mdce service and the processes which"
echo "                it maintains."
echo "                The mdce service must already be running on the specified "
echo "                computer."
echo
echo
echo "Usage:  clusterlogs [ setLevel logLevel | getLevel | getLocation ]"
echo "                    [ -remotehost ]"
echo "                    [ -jobmanagername ]"
echo "                    [ -v ]"
echo "                    [ -help ]"
echo
echo "setLevel        Set the log level of the mdce service and the processes which"
echo "                it maintains."
echo
echo "getLevel        Get the log level of the mdce service and the processes which"
echo "                it maintains."
echo
echo "getLocation     Get the location of the logs of the mdce service and the"
echo "                processes it maintains."
echo
echo "-v              Be verbose.  Display the progress of the command execution."
echo
echo "-help           Print this help information."
echo
echo "Examples:       1) Set the cluster log level to 6."
echo
echo "                clusterlogs setLevel 6"
echo
echo "See also:       mdce, startjobmanager, stopjobmanager, startworker, and"
echo "                stopworker. "
echo
}
#-----------------------------------------------------------------------------

# If either of these variables is null then we will not start the relevent service
REMOTE_COMMAND_VERBOSITY="false"
while [ -n "$1" ] ; do
    case $1 in 
    setLevel)
        REMOTE_COMMAND_ACTION="setLevel"
        READ_LOG_LEVEL=$2
        shift
        ;;
    getLevel)
        REMOTE_COMMAND_ACTION="getLevel"
        ;;
    getLocation)
        REMOTE_COMMAND_ACTION="getLocation"
        ;;
    -remotehost)
        REMOTE_HOSTNAME=$2
        shift
        ;;
    -jobmanagername)
        JOB_MANAGER_NAME=$2
        shift
        ;;
    -baseport)
        READ_BASE_PORT=$2
        shift
        ;;
    -v)
        REMOTE_COMMAND_VERBOSITY="true"
        ;;
    -help|-h)
        usage
        exit 1
        ;;
    *)
        echo "Error: unrecognized option: $1"
        usage
        exit 1
        ;;
    esac
    shift
done    

# Set the general MDCE environment
. "$UTILBASE/setmdceenv"
sourceMdceDef
defineJRECMD

REMOTE_HOSTNAME=${REMOTE_HOSTNAME:-$HOSTNAME}
BASE_PORT=${READ_BASE_PORT:-$BASE_PORT}
INFO_LEVEL=${READ_INFO_LEVEL:-$INFO_LEVEL}
LOG_LEVEL=${READ_LOG_LEVEL:-"-1"}

$JRECMD \
${COMMAND_LINE_JRE_MEMORY} \
${COMMAND_LINE_JRE_GC} \
-classpath  "$REMOTE_COMMAND_CLASSPATH" \
-Djava.security.policy="$CONFIGBASE/jsk-all.policy" \
-Dcom.mathworks.toolbox.distcomp.remote_command_type="clusterlogs" \
-Dcom.mathworks.toolbox.distcomp.remote_command_action=$REMOTE_COMMAND_ACTION \
-Dcom.mathworks.toolbox.distcomp.remote_hostname=$REMOTE_HOSTNAME \
-Dcom.mathworks.toolbox.distcomp.base_port=$BASE_PORT \
-Dcom.mathworks.toolbox.distcomp.remote_command_verbosity=$REMOTE_COMMAND_VERBOSITY \
-Dcom.mathworks.toolbox.distcomp.log_level=$LOG_LEVEL \
-Dcom.mathworks.toolbox.distcomp.jobmanagername=$JOB_MANAGER_NAME \
com.mathworks.toolbox.distcomp.control.RunCommandSender \
"$CONFIGBASE/cluster-logs.config"
