#!/usr/bin/env sh

# conda customization for CDT packages; are we targeting Linux with a cross compiler
if [[ ${HOST} =~ .*linux.* ]] && [[ $(basename ${CC}) =~ .*-.*-.* ]]; then
  # From https://cgit.freedesktop.org/pkg-config/tree/main.c#n520
  # it can be seen that the logic is:
  # PKG_CONFIG_PATH, if set, always comes first
  # if PKG_CONFIG_LIBDIR is set it comes next
  # .. otherwise PC_PATH comes next.
  # If we tried to send sysroot paths in via PKG_CONFIG_PATH they would
  # get precedence over PREFIX (pkg_config_pc_path). We never want that.
  # Instead pass PKG_CONFIG_LIBDIR as PC_PATH:SYSROOT and allow the user
  # to take precedence over all that iff PKG_CONFIG_PATH is set.
  PC_PATH="$(${PREFIX}/bin/pkg-config.bin --variable pc_path pkg-config)"
  if [[ ${HOST} =~ .*x86_64.* ]]; then
    SRLIBDIR=lib64
  else
    SRLIBDIR=lib
  fi
  if [[ ${CONDA_BUILD_PKG_CONFIG_LOG} == yes ]]; then
    echo "Calling: PKG_CONFIG_LIBDIR=${PC_PATH}:$(${CC} -print-sysroot)/usr/share/pkgconfig:$(${CC} -print-sysroot)/usr/${SRLIBDIR}/pkgconfig \
      ${PREFIX}/bin/pkg-config.bin --define-prefix --debug "$@" > /tmp/pkg-config-$$.log"
    PKG_CONFIG_LIBDIR="${PC_PATH}":"$(${CC} -print-sysroot)/usr/share/pkgconfig:$(${CC} -print-sysroot)/usr/${SRLIBDIR}/pkgconfig" \
      ${PREFIX}/bin/pkg-config.bin --define-prefix --debug "$@" >> /tmp/pkg-config-$$.log 2>&1 || true
  fi
  PKG_CONFIG_LIBDIR="${PC_PATH}":"$(${CC} -print-sysroot)/usr/share/pkgconfig:$(${CC} -print-sysroot)/usr/${SRLIBDIR}/pkgconfig" \
    ${PREFIX}/bin/pkg-config.bin --define-prefix "$@"
else
  # We might need --define-prefix here sometimes, but would be better off ensuring /usr is replaced by ${prefix}
  # in all source .pc files in our packages. TODO :: Make conda-build / conda-verify detect this.
  ${PREFIX}/bin/pkg-config.bin "$@"
fi
