#!/bin/sh
# shellcheck shell=sh

# Copyright (C) 2024-2025 Intel Corporation
# Under the Apache License v2.0 with LLVM Exceptions. See LICENSE.TXT.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
# SPDX-License-Identifier: MIT

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
 
# This script is setting up the environment variables for the UMF project.
# This script is meant to be sourced, not run directly.

get_script_path() (
  script="$1"
  while [ -L "$script" ] ; do
    script_dir=$(command dirname -- "$script")
    # see also: https://superuser.com/a/1574553/229501
    if [ -n "${ZSH_VERSION:-}" ] ; then
      script_dir=$(builtin cd "$script_dir" && command pwd -P)
    else
      script_dir=$(command cd "$script_dir" && command pwd -P)
    fi
    script="$(readlink "$script")"
    case $script in
      (/*) ;;
       (*) script="$script_dir/$script" ;;
    esac
  done
  script_dir=$(command dirname -- "$script")
  if [ -n "${ZSH_VERSION:-}" ] ; then
    script_dir=$(builtin cd "$script_dir" && command pwd -P)
  else
    script_dir=$(command cd "$script_dir" && command pwd -P)
  fi
  printf "%s" "$script_dir"
)

_vars_get_proc_name() {
  if [ -n "${ZSH_VERSION:-}" ] ; then
    script="$(ps -p "$$" -o comm=)"
  else
    script="$1"
    while [ -L "$script" ] ; do
      script="$(readlink "$script")"
    done
  fi
  basename -- "$script"
}

_vars_this_script_name="vars.sh"
if [ "$_vars_this_script_name" = "$(_vars_get_proc_name "$0")" ] ; then
  echo "   ERROR: Incorrect usage: this script must be sourced."
  echo "   Usage: . path/to/${_vars_this_script_name}"
  return 255 2>/dev/null || exit 255
fi

resolve_symlink() {
    target_file="$1"
    # Check if the target file is a symlink
    while [ -L "$target_file" ]; do
        # Read the symlink
        target_file=$(readlink "$target_file")
        # Handle relative symlinks by prefixing them with the directory of the symlink
        case $target_file in
            /*) ;; # Absolute path; no need to change
            *) target_file="$(dirname "$1")/$target_file" ;; # Relative path; prepend directory part
        esac
    done
    echo "$target_file"
}

# prepend_path() avoids dangling ":" that affects some env vars (PATH, LD_LIBRARY_PATH, etc.)
prepend_path() {
    new_path="$1"
    var_name="$2"
    # Resolve symlinks in the new path
    resolved_path=$(resolve_symlink "$new_path")
    current_val=$(eval echo \$$var_name)
    if [ -z "$current_val" ]; then
        eval export $var_name="'$resolved_path'"
    else
        eval export $var_name="'$resolved_path':$current_val"
    fi
}

vars_script_name=""
vars_script_shell="$(ps -p "$$" -o comm=)"
# ${var:-} needed to pass "set -eu" checks
# see https://unix.stackexchange.com/a/381465/103967
# see https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02
if [ -n "${ZSH_VERSION:-}" ] && [ -n "${ZSH_EVAL_CONTEXT:-}" ] ; then     # zsh 5.x and later
  # shellcheck disable=SC2249,SC2296
  case $ZSH_EVAL_CONTEXT in (*:file*) vars_script_name="${(%):-%x}" ;; esac ;
elif [ -n "${KSH_VERSION:-}" ] ; then                                     # ksh, mksh or lksh
  if [ "$(set | grep -Fq "KSH_VERSION=.sh.version" ; echo $?)" -eq 0 ] ; then # ksh
    # shellcheck disable=SC2296
    vars_script_name="${.sh.file}" ;
  else # mksh or lksh or [lm]ksh masquerading as ksh or sh
    # shellcheck disable=SC2296
    # force [lm]ksh to issue error msg; which contains this script's path/filename, e.g.:
    # mksh: /home/ubuntu/intel/oneapi/vars.sh[137]: ${.sh.file}: bad substitution
    vars_script_name="$( (echo "${.sh.file}") 2>&1 )" || : ;
    vars_script_name="$(expr "${vars_script_name:-}" : '^.*sh: \(.*\)\[[0-9]*\]:')" ;
  fi
elif [ -n "${BASH_VERSION:-}" ] ; then        # bash
  # shellcheck disable=SC2128,SC3028
  (return 0 2>/dev/null) && vars_script_name="${BASH_SOURCE}" ;
elif [ "dash" = "$vars_script_shell" ] ; then # dash
  # shellcheck disable=SC2296
  # force dash to issue error msg; which contains this script's rel/path/filename, e.g.:
  # dash: 146: /home/ubuntu/intel/oneapi/vars.sh: Bad substitution
  vars_script_name="$( (echo "${.sh.file}") 2>&1 )" || : ;
  vars_script_name="$(expr "${vars_script_name:-}" : '^.*dash: [0-9]*: \(.*\):')" ;
elif [ "sh" = "$vars_script_shell" ] ; then   # could be dash masquerading as /bin/sh
  # shellcheck disable=SC2296
  # force a shell error msg; which should contain this script's path/filename
  # sample error msg shown; assume this file is named "vars.sh"; as required by setvars.sh
  vars_script_name="$( (echo "${.sh.file}") 2>&1 )" || : ;
  if [ "$(printf "%s" "$vars_script_name" | grep -Eq "sh: [0-9]+: .*vars\.sh: " ; echo $?)" -eq 0 ] ; then # dash as sh
    # sh: 155: /home/ubuntu/intel/oneapi/vars.sh: Bad substitution
    vars_script_name="$(expr "${vars_script_name:-}" : '^.*sh: [0-9]*: \(.*\):')" ;
  fi
else  # unrecognized shell or dash being sourced from within a user's script
  # shellcheck disable=SC2296
  # force a shell error msg; which should contain this script's path/filename
  # sample error msg shown; assume this file is named "vars.sh"; as required by setvars.sh
  vars_script_name="$( (echo "${.sh.file}") 2>&1 )" || : ;
  if [ "$(printf "%s" "$vars_script_name" | grep -Eq "^.+: [0-9]+: .*vars\.sh: " ; echo $?)" -eq 0 ] ; then # dash
    # .*: 164: intel/oneapi/vars.sh: Bad substitution
    vars_script_name="$(expr "${vars_script_name:-}" : '^.*: [0-9]*: \(.*\):')" ;
  else
    vars_script_name="" ;
  fi
fi

if [ "" = "$vars_script_name" ] ; then
  >&2 echo "   ERROR: Unable to proceed: possible causes listed below."
  >&2 echo "   This script must be sourced. Did you execute or source this script?" ;
  >&2 echo "   Unrecognized/unsupported shell (supported: bash, zsh, ksh, m/lksh, dash)." ;
  >&2 echo "   May fail in dash if you rename this script (assumes \"vars.sh\")." ;
  >&2 echo "   Can be caused by sourcing from ZSH version 4.x or older." ;
  return 255 2>/dev/null || exit 255
fi

# ############################################################################
# UMF-specific part
# ############################################################################

UMF_ROOT=""

my_script_path=$(get_script_path "${vars_script_name:-}")
component_root=$(dirname -- "${my_script_path}")

if [ -n "$component_root" ]; then
    prepend_path "$component_root" "UMF_ROOT"
fi

# If anything failed, set UMF_ROOT based on ONEAPI_ROOT
if [ -z "$UMF_ROOT" ]; then
    prepend_path "$ONEAPI_ROOT/umf/latest" "UMF_ROOT"
fi

# Set these env vars only if UMF library is available
if [ -e "$UMF_ROOT/lib/libumf.so" ]; then
    prepend_path "$UMF_ROOT/lib" "LD_LIBRARY_PATH"
    prepend_path "$UMF_ROOT/lib" "LIBRARY_PATH"
    prepend_path "$UMF_ROOT/include" "CPATH"
    prepend_path "$UMF_ROOT/include" "C_INCLUDE_PATH"
    prepend_path "$UMF_ROOT/include" "CPLUS_INCLUDE_PATH"
else
    printf "WARNING: UMF library not found in %s\n" "$UMF_ROOT/lib"
fi

# Set TCM_ROOT to the root directory of the TCM project files where hwloc libs are
if [ -z "$TCM_ROOT" ]; then
    prepend_path "$ONEAPI_ROOT/tcm/latest" "TCM_ROOT"
fi

# Set these env vars only if hwloc library is available
if [ -e "$TCM_ROOT/lib/libhwloc.so" ]; then
    prepend_path "$TCM_ROOT/lib" "LD_LIBRARY_PATH"
    prepend_path "$TCM_ROOT/lib" "LIBRARY_PATH"
else
    printf "WARNING: hwloc library not found in %s\n" "$TCM_ROOT/lib"
fi
