# Maintainer: Andrew Sun <adsun701@gmail.com>

_realname=benchmark
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=1.9.4
pkgrel=1
pkgdesc="A microbenchmark support library, by Google (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://github.com/google/benchmark"
license=('spdx:Apache-2.0')
depends=("${MINGW_PACKAGE_PREFIX}-cc-libs")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
# checkdepends=("${MINGW_PACKAGE_PREFIX}-gtest")
source=("https://github.com/google/benchmark/archive/v${pkgver}/${_realname}-${pkgver}.tar.gz"
        "0001-fix-pkgconfig-files.patch")
sha256sums=('b334658edd35efcf06a99d9be21e4e93e092bd5f95074c1673d5c8705d95c104'
            '0f761dbc24ecc0f7dc902fd14cc16fdd448fb1b4204e08adbaee056fed8db1ef')

# Helper macros to help make tasks easier #
apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying ${_patch}"
    patch -Nbp1 -i "${srcdir}/${_patch}"
  done
}
# =========================================== #

prepare() {
  cd "${_realname}-${pkgver}"

  apply_patch_with_msg 0001-fix-pkgconfig-files.patch
}

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

  # Shared Build
  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    cmake -B "build-${MSYSTEM}-shared" -S "${_realname}-${pkgver}" -GNinja \
      -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
      -DBUILD_SHARED_LIBS=ON \
      -DBENCHMARK_ENABLE_GTEST_TESTS=OFF \
      -DBENCHMARK_ENABLE_LTO=ON \
      -DBENCHMARK_ENABLE_WERROR=OFF \
      -DBENCHMARK_USE_BUNDLED_GTEST=OFF \
      "${extra_config[@]}"

  cmake --build "build-${MSYSTEM}-shared"

  # Static Build
  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    cmake -B "build-${MSYSTEM}-static" -S "${_realname}-${pkgver}" -GNinja \
      -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
      -DBUILD_SHARED_LIBS=OFF \
      -DBENCHMARK_ENABLE_GTEST_TESTS=OFF \
      -DBENCHMARK_ENABLE_WERROR=OFF \
      -DBENCHMARK_USE_BUNDLED_GTEST=OFF \
      "${extra_config[@]}"

  cmake --build "build-${MSYSTEM}-static"
}

check() {
  # Shared Check
  PATH=$PWD/src:$PATH cmake --build "build-${MSYSTEM}-shared" --target test || true

  # Static Check
  cmake --build "build-${MSYSTEM}-static" --target test || true
}

package() {
  # Static Install
  DESTDIR="${pkgdir}" cmake --install "build-${MSYSTEM}-static"

  # Shared Install
  DESTDIR="${pkgdir}" cmake --install "build-${MSYSTEM}-shared"

  # License
  install -Dm644 "${srcdir}/${_realname}-${pkgver}/LICENSE" -t "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}"
}
