#! /bin/sh
#
# Copyright 2003-2022 Intel Corporation.
#
# This software and the related documents are Intel copyrighted materials, and your use of
# them is governed by the express license under which they were provided to you (License).
# Unless the License provides otherwise, you may not use, modify, copy, publish, distribute,
# disclose or transmit this software or the related documents without Intel's prior written
# permission.
#
# This software and the related documents are provided as is, with no express or implied
# warranties, other than those that are expressly stated in the License.
#
# set locale, PATH, LD_LIBRARY_PATH, INTEL_LICENSE_FILE 
# and start Intel(R) Trace Analyzer

absolutize_path() # <file> <parentDir>
{
    firstChar=`echo "$1" | cut -c1`
    if [ "$firstChar" = "/" ]; then
        echo "$1"
    else
        echo "$2/$1"
    fi
}

follow_link() # <file>
{
    file="$1"
    parentDir=`dirname "$file"`
    if [ ! -h "$file" ]; then
        echo "$file"
    else
        link=`ls -l "$file" | sed -e "s/.*->[ ]*//"`
        link=`absolutize_path "$link" "$parentDir"`
        follow_link "$link"
    fi
}

 # Command line interface?
cli=no
for i in $*; do
    if [ "$i" = "--cli" ]; then
        cli=yes
    fi
done

 # Check DISPLAY:
if [ "$cli" = no ]; then
    xdpyinfo >/dev/null 2>&1
    if [ $? = 1 ]; then
        echo "Error: Can't open display: $DISPLAY"
        exit 1
    fi
fi

 # Determine absolute path name of the Intel(R) Trace Analyzer directory:
dir=`follow_link "$0"`
dir=`dirname "$dir"`/..
dir=`( cd "$dir"; pwd )` # guarantees an absolute path name

 # Set a default locale:
LANG=C
export LANG
allLocaleVars=`env | grep "^LC_"`
for var in $allLocaleVars; do
    varName=`echo $var | sed -e "s/=.*//g"`
    eval "$varName="
    eval "export $varName"
done

 # Set general Intel(R) Trace Analyzer and Collector environment:
if test -r "$dir/bin/itacvars.sh"; then
    . $dir/bin/itacvars.sh >/dev/null 2>&1
fi

 # PATH (for finding stftool):
if test -z "${PATH}"
then
    PATH="$dir/bin"
else
    PATH="$dir/bin:${PATH}"
fi
export PATH

 # LD_LIBRARY_PATH:
if test -z "${LD_LIBRARY_PATH}"
then
    LD_LIBRARY_PATH="$dir/bin/rtlib:$dir/bin"
else
    LD_LIBRARY_PATH="$dir/bin/rtlib:$dir/bin:${LD_LIBRARY_PATH}"
fi
export LD_LIBRARY_PATH

 # INTEL_LICENSE_FILE:
if test -z "${INTEL_LICENSE_FILE}"
then
    INTEL_LICENSE_FILE="$dir"
else
    INTEL_LICENSE_FILE="${dir}:${INTEL_LICENSE_FILE}"
fi
export INTEL_LICENSE_FILE

 # Check whether all required shared libraries are found:
ldd "$dir/bin/traceanalyzer.bin" | grep "not found"

 # Start Intel(R) Trace Analyzer:
if [ "$cli" = no ]; then
    exec "$dir/bin/traceanalyzer.bin" "$@" >/dev/null 2>&1
else
    exec "$dir/bin/traceanalyzer.bin" "$@" 2>/dev/null
fi
