# Maintainer: Diego Sogari <diego.sogari@gmail.com>

_realname=librdkafka
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=2.11.1
pkgrel=1
pkgdesc="The Apache Kafka C/C++ client library (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://github.com/confluentinc/librdkafka"
msys2_references=(
  'archlinux: librdkafka'
)
license=('spdx:BSD-2-Clause')
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
depends=("${MINGW_PACKAGE_PREFIX}-cyrus-sasl"
         "${MINGW_PACKAGE_PREFIX}-curl"
         "${MINGW_PACKAGE_PREFIX}-lz4"
         "${MINGW_PACKAGE_PREFIX}-openssl"
         "${MINGW_PACKAGE_PREFIX}-zlib"
         "${MINGW_PACKAGE_PREFIX}-zstd")
source=("https://github.com/confluentinc/librdkafka/archive/v${pkgver}/${_realname}-${pkgver}.tar.gz")
sha256sums=('a2c87186b081e2705bb7d5338d5a01bc88d43273619b372ccb7bb0d264d0ca9f')

build() {
  mkdir -p "${srcdir}/build-${MSYSTEM}" && cd "${srcdir}/build-${MSYSTEM}"

  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -G"Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    ${_extra_config[@]} \
    -DWITHOUT_WIN32_CONFIG=OFF \
    -DWITH_CURL=ON \
    -DWITH_LIBDL=ON \
    -DWITH_PLUGINS=ON \
    -DWITH_SASL=ON \
    -DWITH_SSL=ON \
    -DWITH_ZLIB=ON \
    -DWITH_ZSTD=ON \
    "../${_realname}-${pkgver}"

  ${MINGW_PREFIX}/bin/cmake.exe --build ./
}

check() {
  cd "${srcdir}/build-${MSYSTEM}"

  # Prepend build directory with PATH to get DLL file
  PATH=$PWD/src:$PWD/src-cpp:$PATH ${MINGW_PREFIX}/bin/ctest.exe ./ || warning "Tests failed"
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake.exe --install ./

  # remove reference to MSYS2 install directory
  local PREFIX_WIN=$(cygpath -wm ${MINGW_PREFIX})
  for _f in "${pkgdir}${MINGW_PREFIX}"/lib/cmake/RdKafka/*.cmake; do
    sed -e "s|${PREFIX_WIN}|\$\{_IMPORT_PREFIX\}|g" -i ${_f}
  done
}
