# Maintainer: Maksim Bondarenkov <maksapple2306@gmail.com>

_realname=BLAKE3
pkgbase=mingw-w64-blake3
pkgname=("${MINGW_PACKAGE_PREFIX}-b3sum"
         "${MINGW_PACKAGE_PREFIX}-libblake3")
pkgver=1.8.2
pkgrel=1
pkgdesc="BLAKE3 hash function (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url='https://github.com/BLAKE3-team/BLAKE3'
license=('spdx:CC0-1.0 OR Apache-2.0 OR Apache-2.0 WITH LLVM-exception')
msys2_reference=(
  'anitya: 369414'
  'archlinux: b3sum'
  'gentoo: dev-libs/blake3'
  'purl: pkg:cargo/b3sum'
)
depends=("${MINGW_PACKAGE_PREFIX}-cc-libs")
makedepends=("${MINGW_PACKAGE_PREFIX}-rust"
             "${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-pkgconf"
             "${MINGW_PACKAGE_PREFIX}-tbb")
source=("${url}/archive/${pkgver}/${_realname}-${pkgver}.tar.gz")
sha256sums=('6b51aefe515969785da02e87befafc7fdc7a065cd3458cf1141f29267749e81f')

prepare() {
  cargo fetch \
    --locked \
    --manifest-path="${_realname}-${pkgver}"/b3sum/Cargo.toml \
    --target "$(rustc -vV | sed -n 's/host: //p')"
}

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

  export RUSTFLAGS="${RUSTFLAGS/+crt-static/-crt-static}"
  cargo build \
    --release \
    --frozen \
    --manifest-path="${_realname}-${pkgver}/b3sum/Cargo.toml"

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    cmake \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
      "${extra_config[@]}" \
      -DBUILD_SHARED_LIBS=ON \
      -DCMAKE_DLL_NAME_WITH_SOVERSION=ON \
      -DBLAKE3_USE_TBB=ON \
      -S "${_realname}-${pkgver}/c" \
      -B "build-${MSYSTEM}"

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

check() {
  cargo test \
    --release \
    --frozen \
    --manifest-path="${_realname}-${pkgver}/b3sum/Cargo.toml"
}

package_b3sum() {
  pkgdesc="Command line implementation of the BLAKE3 hash function (mingw-w64)"

  cargo install \
    --offline \
    --no-track \
    --frozen \
    --path "${_realname}-${pkgver}/b3sum" \
    --root "${pkgdir}${MINGW_PREFIX}"

  install -Dm644 "${_realname}-${pkgver}"/LICENSE_{A2,A2LLVM,CC0} -t "${pkgdir}${MINGW_PREFIX}/share/licenses/b3sum/"
}

package_libblake3() {
  pkgdesc="C implementation of the BLAKE3 hash function (mingw-w64)"
  depends+=("${MINGW_PACKAGE_PREFIX}-tbb")

  DESTDIR="${pkgdir}" cmake --install "build-${MSYSTEM}"
  install -Dm644 "${_realname}-${pkgver}"/LICENSE_{A2,A2LLVM,CC0} -t "${pkgdir}${MINGW_PREFIX}/share/licenses/libblake3/"
}

# vim: set ft=bash :

# generate wrappers
for _name in "${pkgname[@]}"; do
  _short="package_${_name#${MINGW_PACKAGE_PREFIX}-}"
  _func="$(declare -f "${_short}")"
  eval "${_func/#${_short}/package_${_name}}"
done
