# Maintainer: Alexey Pavlov <alexpux@gmail.com>

_realname=libatomic_ops
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=7.10.0
pkgrel=1
pkgdesc="Provides semi-portable access to hardware provided atomic memory operations (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://github.com/bdwgc/libatomic_ops"
msys2_references=(
  "cpe: cpe:2.3:a:libatomic_ops_project:libatomic_ops"
)
license=('spdx:GPL-2.0' 'spdx:MIT')
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
source=("https://github.com/bdwgc/${_realname}/releases/download/v${pkgver}/${_realname}-${pkgver}.tar.gz"
        001-fix-pkgconfig.patch)
sha256sums=('0db3ebff755db170f65e74a64ec4511812e9ee3185c232eeffeacd274190dfb0'
            '4d8a9037a3f6cd831f1cfe9dcb9f51c993b767f0115018306ca547acbdd5b4e8')

prepare() {
  cd "${srcdir}"/${_realname}-${pkgver}
  patch -p1 -i "${srcdir}"/001-fix-pkgconfig.patch
}

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

  if [[ ${MSYSTEM} == MINGW64 || ${MSYSTEM} == UCRT64 ]]; then
    _extra_config+=("-Denable_atomic_intrinsics=OFF")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  "${MINGW_PREFIX}"/bin/cmake.exe \
    -GNinja \
    -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
    -DAO_BUILD_SHARED_LIBS=ON \
    -DBUILD_TESTING=OFF \
    -DCMAKE_DLL_NAME_WITH_SOVERSION=ON \
    "${_extra_config[@]}" \
    ../${_realname}-${pkgver}

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

check() {
  cd "${srcdir}"/build-${MSYSTEM}
  "${MINGW_PREFIX}"/bin/cmake.exe -DBUILD_TESTING=ON ../${_realname}-${pkgver}
  "${MINGW_PREFIX}"/bin/cmake.exe --build .
  "${MINGW_PREFIX}"/bin/ctest || echo "Tests failed"
}

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

  DESTDIR="${pkgdir}" "${MINGW_PREFIX}"/bin/cmake.exe --install .

  install -D -m644 "${srcdir}"/${_realname}-${pkgver}/LICENSE "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
}
