# Maintainer: Torsten Keßler <tpkessler at archlinux dot org>
# Maintainer: Christian Heusel <gromit@archlinux.org>
# Contriubtor: Markus Näther <naetherm@informatik.uni-freiburg.de>
# Contributor: acxz <akashpatel2008 at yahoo dot com>

pkgname=rccl
pkgver=7.1.1
pkgrel=1
pkgdesc="ROCm Communication Collectives Library"
arch=('x86_64' 'aarch64')
url='https://rocm.docs.amd.com/projects/rccl/en/latest/index.html'
license=('BSD-3-Clause')
depends=('rocm-core' 'glibc' 'gcc-libs' 'hip-runtime-amd' 'rocm-smi-lib')
makedepends=('git' 'cmake' 'rocm-cmake' 'hipify-clang' 'python')
source_aarch64=("aarch64.patch")
source=(
  "${pkgname}::git+https://github.com/ROCm/rccl#tag=rocm-$pkgver"
  "${pkgname}-json::git+https://github.com/nlohmann/json.git"
  "${pkgname}-mscclpp::git+https://github.com/microsoft/mscclpp.git"
  "reduce_jobs_for_hipcc.patch"
  rccl-launchpad-build-fix.patch::https://salsa.debian.org/rocm-team/rccl/-/raw/debian/experimental/debian/patches/rccl-launchpad-build-fix.patch
)
sha256sums_aarch64=('a95bac48a8cd13b3481038b1f78ac4873cc513491a68ba63d7166a20420b3bf1')
sha256sums=('7da1096165934e4c678f3c48b07b573f07784699a0eac156d181a88648a3801c'
            'SKIP'
            'SKIP'
            '62f6ffdc7f448993bd553a8511ba31fc7a51247f180cf73ae82d2cd6bf593b10'
            '347ba56bcbfc52d2fb093220043cf85f381b4f3a16cfdb0f975a88bb2928afa5')
options=(!lto)

prepare() {
  cd "$pkgname"
  git submodule init

  git config submodule."ext-src/json".url "${srcdir}/${pkgname}"-json
  git config submodule."ext-src/mscclpp".url "${srcdir}/${pkgname}"-mscclpp

  git -c protocol.file.allow=always submodule update --init --recursive
  [[ $CARCH == aarch64 ]] && patch -Np1 -i "${srcdir}/aarch64.patch"
#  patch -Np1 -i "${srcdir}/reduce_jobs_for_hipcc.patch"
  patch -Np1 -i "${srcdir}/rccl-launchpad-build-fix.patch"
}

build() {
  export VERBOSE=1
  export ROCM_PATH=/opt/rocm
  export PATH="$PATH":"$ROCM_PATH/bin"
  # Compile source code for supported GPU archs in parallel
  #export HIPCC_COMPILE_FLAGS_APPEND="-parallel-jobs=$(nproc)"
  #export HIPCC_LINK_FLAGS_APPEND="-parallel-jobs=$(nproc)"
  export CXX=/opt/rocm/llvm/bin/amdclang++
  export CC=/opt/rocm/llvm/bin/amdclang
  # -fcf-protection is not supported by HIP, see
  # https://rocm.docs.amd.com/projects/llvm-project/en/latest/reference/rocmcc.html#support-status-of-other-clang-options
  CXXFLAGS+=" -fcf-protection=none"
  local cmake_args=(
    -Wno-dev
    -S "$pkgname"
    -B build
    -D CMAKE_BUILD_TYPE=None
    -D CMAKE_TOOLCHAIN_FILE="$srcdir/$pkgname"/toolchain-linux.cmake
    -D CMAKE_INSTALL_PREFIX=/opt/rocm
    -D ENABLE_MSCCL_KERNEL=OFF
    -D ENABLE_MSCCLPP=OFF
  )
  cmake "${cmake_args[@]}"
  cmake --build build
}

package() {
  DESTDIR="$pkgdir" cmake --install build

  install -Dm644 "$srcdir/$pkgname/LICENSE.txt" "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
}
