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

declare -gx FILES_LIB="./common/handle-files"
if ! [[ -f "${FILES_LIB}" ]] ; then
  echo "error: files-lib is not available"
  exit 1
else
  source "${FILES_LIB}"
fi

declare -agx filepaths=(
  "${PREFIX}/include/custabilizer.h"
  "${PREFIX}/lib/libcustabilizer.so"
)

if ! files exist "${filepaths[@]}" ; then
  echo "error: custabilizer files are not available"
  exit 1
fi

declare -gx CUQUANTUM_VER="${1}"
if [[ -n "${CUQUANTUM_VER}" ]] ; then
  declare -agx CUQUANTUM_VERSION
  mapfile -t CUQUANTUM_VERSION <<< "${CUQUANTUM_VER//./$'\n'}"
  {(

    declare -gx IFS_PREV="${IFS}" ; IFS="."
      git clone --branch "v${CUQUANTUM_VERSION[*]:0:3}" "https://github.com/NVIDIA/cuQuantum.git" "cuquantum-custabilizer"
    IFS="${IFS_PREV}" ; unset IFS_PREV
    cd "cuquantum-custabilizer/samples/custabilizer" || exit 1
    declare -agx examples
    mapfile -t examples < <(
      find . -name "*.cpp" -type f -print
    )
    declare -a compile_command

    declare example ; for example in "${examples[@]}" ; do
      if [[ "${example}" != *"mpi"* ]] ; then
        echo "${example}"
        compile_command=(
          "${NVCC:-"nvcc"}" "${NVCC_FLAGS:-"--verbose"}" "--std=c++17"
          "-I${PREFIX}/include" "-L${PREFIX}/lib" "-L${PREFIX}/lib/stubs"
          "-lcustabilizer" "${example}" "-o" "${example}.out"
        )  
        echo "${compile_command[@]}"
        "${compile_command[@]}"
      fi
    done
  )}
fi
