#!/bin/bash

# Copyright Intel Corporation
# SPDX-License-Identifier: MIT
# https://opensource.org/licenses/MIT

# This function takes no arguments
# It tries to determine the name of this file in a programatic way.
function _get_sourced_filename() {
    if [ -n "${BASH_SOURCE[0]}" ]; then
        basename "${BASH_SOURCE[0]}"
    elif [ -n "${(%):-%x}" ]; then
        # in zsh use prompt-style expansion to introspect the same information
        # see http://stackoverflow.com/questions/9901210/bash-source0-equivalent-in-zsh
        basename "${(%):-%x}"
    else
        echo "UNKNOWN FILE"
    fi
}

# The arguments to this are:
# 1. activation nature {activate|deactivate}
# 2. toolchain nature {build|host|ccc}
# 3. machine (should match -dumpmachine)
# 4. prefix (including any final -)
# 5+ program (or environment var comma value)
# The format for 5+ is name{,,value}. If value is specified
#  then name taken to be an environment variable, otherwise
#  it is taken to be a program. In this case, which is used
#  to find the full filename during activation. The original
#  value is stored in environment variable CONDA_BACKUP_NAME
#  For deactivation, the distinction is irrelevant as in all
#  cases NAME simply gets reset to CONDA_BACKUP_NAME.  It is
#  a fatal error if a program is identified but not present.
function _tc_activation() {
  local act_nature=$1; shift
  local tc_prefix=$1; shift
  local thing
  local newval
  local from
  local to
  local pass

  if [ "${act_nature}" = "activate" ]; then
    from=""
    to="CONDA_BACKUP_"
  else
    from="CONDA_BACKUP_"
    to=""
  fi

  for pass in check apply; do
    for thing in "$@"; do
      case "${thing}" in
        *,*)
          newval=$(echo "${thing}" | sed "s,^[^\,]*\,\(.*\),\1,")
          thing=$(echo "${thing}" | sed "s,^\([^\,]*\)\,.*,\1,")
          ;;
        *)
          newval="${CONDA_PREFIX}/bin/${tc_prefix}${thing}"
          thing=$(echo ${thing} | tr 'a-z+-' 'A-ZX_')
          if [ ! -x "${newval}" -a "${pass}" = "check" ]; then
            echo "ERROR: This cross-compiler package contains no program ${newval}"
            return 1
          fi
          ;;
      esac
      if [ "${pass}" = "apply" ]; then
        eval oldval="\$${from}$thing"
        if [ -n "${oldval}" ]; then
          eval export "${to}'${thing}'=\"${oldval}\""
        else
          eval unset '${to}${thing}'
        fi
        if [ -n "${newval}" ]; then
          eval export "'${from}${thing}=${newval}'"
        else
          eval unset '${from}${thing}'
        fi
      fi
    done
  done
  return 0
}

CONDA_BUILD_SYSROOT_USED="${CONDA_PREFIX}/x86_64-conda-linux-gnu/sysroot"

_CMAKE_ARGS="-DCMAKE_AR=${CONDA_PREFIX}/bin/x86_64-conda-linux-gnu-llvm-ar -DCMAKE_CXX_COMPILER_AR=${CONDA_PREFIX}/bin/x86_64-conda-linux-gnu-llvm-ar -DCMAKE_C_COMPILER_AR=${CONDA_PREFIX}/bin/x86_64-conda-linux-gnu-llvm-ar"
_CMAKE_ARGS="${_CMAKE_ARGS} -DCMAKE_RANLIB=${CONDA_PREFIX}/bin/x86_64-conda-linux-gnu-llvm-ranlib -DCMAKE_CXX_COMPILER_RANLIB=${CONDA_PREFIX}/bin/x86_64-conda-linux-gnu-llvm-ranlib -DCMAKE_C_COMPILER_RANLIB=${CONDA_PREFIX}/bin/x86_64-conda-linux-gnu-llvm-ranlib"
_CMAKE_ARGS="${_CMAKE_ARGS} -DCMAKE_LINKER=${CONDA_PREFIX}/bin/x86_64-conda-linux-gnu-ld.lld"

if [ "${CONDA_BUILD:-0}" = "1" ]; then
  # add some more CMAKE stuff first.
  _CMAKE_ARGS="${_CMAKE_ARGS} -DCMAKE_FIND_ROOT_PATH_MODE_PROGRAM=NEVER -DCMAKE_FIND_ROOT_PATH_MODE_LIBRARY=ONLY -DCMAKE_FIND_ROOT_PATH_MODE_INCLUDE=ONLY"
  _CMAKE_ARGS="${_CMAKE_ARGS} -DCMAKE_FIND_ROOT_PATH=${PREFIX};${BUILD_PREFIX}/x86_64-conda-linux-gnu/sysroot"
  _CMAKE_ARGS="${_CMAKE_ARGS} -DCMAKE_INSTALL_PREFIX=${PREFIX} -DCMAKE_INSTALL_LIBDIR=lib"

  CFLAGS_USED="-Wformat -Wformat-security -O3 -fp-model strict -fomit-frame-pointer -xSSE4.2 -axCORE-AVX2,CORE-AVX512 -fPIC -fstack-protector-all -fno-plt -ftree-vectorize -ffunction-sections -pipe --target=x86_64-conda-linux-gnu --gcc-toolchain=${CONDA_PREFIX} --sysroot ${CONDA_BUILD_SYSROOT_USED} -isystem ${BUILD_PREFIX}/include -isystem ${PREFIX}/include -fdebug-prefix-map=${SRC_DIR}=/usr/local/src/conda/${PKG_NAME}-${PKG_VERSION} -fdebug-prefix-map=${PREFIX}=/usr/local/src/conda-prefix"
  DEBUG_CFLAGS_USED="-Wformat -Wformat-security -O3 -fp-model strict -fomit-frame-pointer -xSSE4.2 -axCORE-AVX2,CORE-AVX512 -fPIC -fstack-protector-all -fno-plt -ftree-vectorize -ffunction-sections -pipe -Wformat -Wformat-security -O0g -g -fp-model strict -fomit-frame-pointer -xSSE4.2 -axCORE-AVX2,CORE-AVX512 -fPIC -fstack-protector-all -fno-plt -ftree-vectorize -ffunction-sections -pipe  --target=x86_64-conda-linux-gnu --gcc-toolchain=${CONDA_PREFIX} --sysroot ${CONDA_BUILD_SYSROOT_USED} -isystem ${BUILD_PREFIX}/include -isystem ${PREFIX}/include -fdebug-prefix-map=${SRC_DIR}=/usr/local/src/conda/${PKG_NAME}-${PKG_VERSION} -fdebug-prefix-map=${PREFIX}=/usr/local/src/conda-prefix"
  CPPFLAGS_USED="-DNDEBUG -D_FORTIFY_SOURCE=2 -isystem ${PREFIX}/include"
  DEBUG_CPPFLAGS_USED="-D_DEBUG -D_FORTIFY_SOURCE=2 -Og -isystem ${PREFIX}/include"
  CXXFLAGS_USED="-std=c++17 -Wformat -Wformat-security -O3 -fp-model strict -fomit-frame-pointer -xSSE4.2 -axCORE-AVX2,CORE-AVX512 -fPIC -fstack-protector-all --target=x86_64-conda-linux-gnu --gcc-toolchain=${CONDA_PREFIX} --sysroot ${CONDA_BUILD_SYSROOT_USED} -isystem ${BUILD_PREFIX}/include -isystem ${PREFIX}/include -fdebug-prefix-map=${SRC_DIR}=/usr/local/src/conda/${PKG_NAME}-${PKG_VERSION} -fdebug-prefix-map=${PREFIX}=/usr/local/src/conda-prefix"
  DEBUG_CXXFLAGS_USED="-std=c++17 -Wformat -Wformat-security -O3 -fp-model strict -fomit-frame-pointer -xSSE4.2 -axCORE-AVX2,CORE-AVX512 -fPIC -fstack-protector-all -std=c++17 -Wformat -Wformat-security -O0g -g -fp-model strict -fomit-frame-pointer -xSSE4.2 -axCORE-AVX2,CORE-AVX512 -fPIC -fstack-protector-all --target=x86_64-conda-linux-gnu --gcc-toolchain=${CONDA_PREFIX} --sysroot ${CONDA_BUILD_SYSROOT_USED} -isystem ${BUILD_PREFIX}/include -isystem ${PREFIX}/include -fdebug-prefix-map=${SRC_DIR}=/usr/local/src/conda/${PKG_NAME}-${PKG_VERSION} -fdebug-prefix-map=${PREFIX}=/usr/local/src/conda-prefix"
  LDFLAGS_USED="-Wl,-O3 -Wl,--sort-common -Wl,--as-needed -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now -Wl,--disable-new-dtags -Wl,--gc-sections -fuse-ld=lld --target=x86_64-conda-linux-gnu -Wl,-rpath,${PREFIX}/lib -Wl,-rpath-link,${PREFIX}/lib -L${PREFIX}/lib -Wl,-rpath,${BUILD_PREFIX}/lib -Wl,-rpath-link,${BUILD_PREFIX}/lib -L${BUILD_PREFIX}/lib"
  LDFLAGS_LD_USED="-O0g -g --sort-common --as-needed -z noexecstack -z relro -z now --disable-new-dtags --gc-sections -fuse-ld=lld --target=x86_64-conda-linux-gnu -rpath ${PREFIX}/lib -rpath-link ${PREFIX}/lib -L${PREFIX}/lib -rpath ${BUILD_PREFIX}/lib -rpath-link ${BUILD_PREFIX}/lib -L${BUILD_PREFIX}/lib"
  CMAKE_PREFIX_PATH_USED="${PREFIX}:${CONDA_PREFIX}/x86_64-conda-linux-gnu/sysroot/usr"
  CPATH_USED="${PREFIX}/include:${CONDA_PREFIX}"
  LIBRARY_PATH_USED="${PREFIX}/compiler/lib:${LIBRARY_PATH}"
  LD_LIBRARY_PATH_USED="${PREFIX}/compiler/lib/intel64_lin:${PREFIX}/compiler/lib:${PREFIX}/lib:${LD_LIBRARY_PATH}"
else
  CFLAGS_USED="-Wformat -Wformat-security -O3 -fp-model strict -fomit-frame-pointer -xSSE4.2 -axCORE-AVX2,CORE-AVX512 -fPIC -fstack-protector-all -fno-plt -ftree-vectorize -ffunction-sections -pipe -isystem ${CONDA_PREFIX}/include"
  DEBUG_CFLAGS_USED="-Wformat -Wformat-security -O0g -g -fp-model strict -fomit-frame-pointer -xSSE4.2 -axCORE-AVX2,CORE-AVX512 -fPIC -fstack-protector-all -fno-plt -ftree-vectorize -ffunction-sections -pipe -isystem ${CONDA_PREFIX}/include"
  CPPFLAGS_USED="-DNDEBUG -D_FORTIFY_SOURCE=2 -isystem ${CONDA_PREFIX}/include"
  DEBUG_CPPFLAGS_USED="-D_DEBUG -D_FORTIFY_SOURCE=2 -Og -isystem ${CONDA_PREFIX}/include"
  CXXFLAGS_USED="-std=c++17 -Wformat -Wformat-security -O3 -fp-model strict -fomit-frame-pointer -xSSE4.2 -axCORE-AVX2,CORE-AVX512 -fPIC -fstack-protector-all -isystem ${CONDA_PREFIX}/include"
  DEBUG_CXXFLAGS_USED="-std=c++17 -Wformat -Wformat-security -O0g -g -fp-model strict -fomit-frame-pointer -xSSE4.2 -axCORE-AVX2,CORE-AVX512 -fPIC -fstack-protector-all -isystem ${CONDA_PREFIX}/include"
  LDFLAGS_USED="-Wl,-O3 -Wl,--sort-common -Wl,--as-needed -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now -Wl,--disable-new-dtags -Wl,--gc-sections -fuse-ld=lld -Wl,-rpath,${CONDA_PREFIX}/lib -Wl,-rpath-link,${CONDA_PREFIX}/lib -L${CONDA_PREFIX}/lib"
  LDFLAGS_LD_USED="-O0g -g --sort-common --as-needed -z noexecstack -z relro -z now --disable-new-dtags --gc-sections -fuse-ld=lld -rpath ${CONDA_PREFIX}/lib -rpath-link ${CONDA_PREFIX}/lib -L${CONDA_PREFIX}/lib"
  CMAKE_PREFIX_PATH_USED="${CONDA_PREFIX}:${CONDA_PREFIX}/x86_64-conda-linux-gnu/sysroot/usr"
  CPATH_USED="${CONDA_PREFIX}/include:${CONDA_PREFIX}"
  LIBRARY_PATH_USED="${CONDA_PREFIX}/compiler/lib:${LIBRARY_PATH}"
  LD_LIBRARY_PATH_USED="${CONDA_PREFIX}/compiler/lib/intel64_lin:${CONDA_PREFIX}/compiler/lib:${CONDA_PREFIX}/lib:${LD_LIBRARY_PATH}"
fi

if [ "${CONDA_BUILD:-0}" = "1" ]; then
  if [ -f /tmp/old-env-$$.txt ]; then
    rm -f /tmp/old-env-$$.txt || true
  fi
  env > /tmp/old-env-$$.txt
fi

_tc_activation \
  activate x86_64-conda-linux-gnu- "HOST,x86_64-conda-linux-gnu" "BUILD,x86_64-conda-linux-gnu" \
  "CC,${CC:-x86_64-conda-linux-gnu-icx}" \
  "CXX,${CXX:-x86_64-conda-linux-gnu-icpx}" \
  "LD,${LD:-x86_64-conda-linux-gnu-ld.lld}" \
  "AR,${AR:-x86_64-conda-linux-gnu-llvm-ar}" \
  "RANLIB,${RANLIB:-x86_64-conda-linux-gnu-llvm-ranlib}" \
  "CFLAGS,${CFLAGS:-${CFLAGS_USED}}" \
  "DEBUG_CFLAGS,${DEBUG_CFLAGS:-${DEBUG_CFLAGS_USED}}" \
  "CPPFLAGS,${CPPFLAGS:-${CPPFLAGS_USED}}" \
  "DEBUG_CPPFLAGS,${DEBUG_CPPFLAGS:-${DEBUG_CPPFLAGS_USED}}" \
  "CXXFLAGS,${CXXFLAGS:-${CXXFLAGS_USED}}" \
  "DEBUG_CXXFLAGS,${DEBUG_CXXFLAGS:-${DEBUG_CXXFLAGS_USED}}" \
  "LDFLAGS,${LDFLAGS:-${LDFLAGS_USED}}" \
  "LDFLAGS_LD,${LDFLAGS_LD:-${LDFLAGS_LD_USED}}" \
  "CONDA_BUILD_SYSROOT,${CONDA_BUILD_SYSROOT_USED:-}" \
  "_CONDA_PYTHON_SYSCONFIGDATA_NAME,${_CONDA_PYTHON_SYSCONFIGDATA_NAME:-_sysconfigdata_x86_64_conda_linux_gnu}" \
  "CMAKE_ARGS,${_CMAKE_ARGS:-}" \
  "CONDA_BUILD_CROSS_COMPILATION," \
  "CMAKE_PREFIX_PATH,${CMAKE_PREFIX_PATH_USED}" \
  "CPATH,${CPATH:-${CPATH_USED}}" \
  "LIBRARY_PATH,${LIBRARY_PATH:-${LIBRARY_PATH_USED}}" \
  "LD_LIBRARY_PATH,${LD_LIBRARY_PATH:-${LD_LIBRARY_PATH_USED}}"

unset _CMAKE_ARGS

if [ $? -ne 0 ]; then
  echo "ERROR: $(_get_sourced_filename) failed, see above for details"
else
  if [ "${CONDA_BUILD:-0}" = "1" ]; then
    if [ -f /tmp/new-env-$$.txt ]; then
      rm -f /tmp/new-env-$$.txt || true
    fi
    env > /tmp/new-env-$$.txt

    echo "INFO: $(_get_sourced_filename) made the following environmental changes:"
    diff -U 0 -rN /tmp/old-env-$$.txt /tmp/new-env-$$.txt | tail -n +4 | grep "^-.*\|^+.*" | grep -v "CONDA_BACKUP_" | sort
    rm -f /tmp/old-env-$$.txt /tmp/new-env-$$.txt || true
  fi
fi
