#!/usr/bin/env bash
# shellcheck disable=SC1091
set -ex


if [[ -f "${RECIPE_DIR}/common/handle-files" ]] ; then
  source "${RECIPE_DIR}/common/handle-files"
else
  echo "error: common/handle-files is not available"
  exit 1
fi

conda clean --all --yes

{(
  
  declare -gx from named
  from="include" named="*cutensornet.h*" files move "${PREFIX}/include"
  from="include/cutensornet" named="*.h*" files move "${PREFIX}/include/cutensornet"
  from="lib" named="*cutensornet.so*" files move "${PREFIX}/lib"
  
  check-glibc ${PREFIX}/lib/*cutensornet.so*
  
  if [[ "${mpi}" != "nompi" ]]; then
  #if [[ -f "${PREFIX}/lib/libmpi.so" ]] ; then
    echo " detected mpi lib, building wrappers" 
    # build the mpi wrapper lib  
    if ! [[ -f "distributed_interfaces/cutensornet_distributed_interface_mpi.c" ]] ; then
      echo "error: distributed interface source not found in expected location"
      exit 1
    fi
    declare -a compile_command
    compile_command=(
        "${GCC}" "-shared" "-std=c11" "-fPIC" ${CFLAGS} "-I${PREFIX}/include"
        "distributed_interfaces/cutensornet_distributed_interface_mpi.c"
        "-L${PREFIX}/lib" "-lmpi"
        "-o" "${PREFIX}/lib/libcutensornet_distributed_interface_mpi.so"
      )
    echo "compile_command[@]"
    "${compile_command[@]}"
    if ! [[ -f "${PREFIX}/lib/libcutensornet_distributed_interface_mpi.so" ]] ; then
      echo "error: cutensornet communication library not found in expected location"
      exit 1
    fi

    check-glibc ${PREFIX}/lib/libcutensornet_distributed_interface_mpi.so
    
    # copy activate/deactivate scripts
    mkdir -p "${PREFIX}/etc/conda/activate.d"
    cp "${RECIPE_DIR}/cutensornet/cutn-activate.sh" "${PREFIX}/etc/conda/activate.d/cutn-activate.sh" 
    mkdir -p "${PREFIX}/etc/conda/deactivate.d"
    cp "${RECIPE_DIR}/cutensornet/cutn-deactivate.sh" "${PREFIX}/etc/conda/deactivate.d/cutn-deactivate.sh"
  else
    echo "no mpi library found, not building wrappers"
  fi
  
)}


