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

_realname=surrealdb
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=2.4.0
pkgrel=1
pkgdesc="A scalable, distributed, collaborative, document-graph database, for the realtime web (mingw-w64)"
arch=('any')
mingw_arch=('ucrt64' 'clang64' 'clangarm64')
url='https://surrealdb.com'
msys2_repository_url='https://github.com/surrealdb/surrealdb'
msys2_references=(
  'aur: surrealdb'
  'purl: pkg:cargo/surrealdb'
)
license=('spdx:BUSL-1.1')
depends=("${MINGW_PACKAGE_PREFIX}-bzip2"
         "${MINGW_PACKAGE_PREFIX}-cc-libs"
         "${MINGW_PACKAGE_PREFIX}-zstd")
makedepends=("${MINGW_PACKAGE_PREFIX}-rust"
             "${MINGW_PACKAGE_PREFIX}-clang"
             "${MINGW_PACKAGE_PREFIX}-pkgconf"
             "${MINGW_PACKAGE_PREFIX}-cargo-edit"
             'git')
options=('!strip')
source=("git+${msys2_repository_url}#tag=v${pkgver}"
        "zstd-sys.tar.gz::https://crates.io/api/v1/crates/zstd-sys/2.0.15+zstd.1.5.7/download"
        "bzip2-sys.tar.gz::https://crates.io/api/v1/crates/bzip2-sys/0.1.13+1.0.8/download"
        "bzip2-sys-use-pkgconfig.patch"
        "zstd-sys-remove-statik.patch")
sha256sums=('1512a171685c8df61f197e473c4c53ef8a5f16e3f4c35de8c78c2bd3c9152d79'
            'eb81183ddd97d0c74cedf1d50d85c8d08c1b8b68ee863bdee9e706eedba1a237'
            '225bff33b2141874fe80d71e07d6eec4f85c5c216453dd96388240f96e1acc14'
            'f73309fb98b89b2085bccee6ffb66820082628d096bc989922b25d33a1f5f378'
            '48f4900ceb02d3aaf9a1020f33d56629156e96759f456c0e7ca18bfcf910767b')

prepare() {
  cd "${_realname}"

  patch -d ../bzip2-sys-0.1.13+1.0.8 -i ../bzip2-sys-use-pkgconfig.patch
  patch -d ../zstd-sys-2.0.15+zstd.1.5.7 -i ../zstd-sys-remove-statik.patch
  cat >> Cargo.toml <<END

[patch.crates-io]
bzip2-sys.path = "../bzip2-sys-0.1.13+1.0.8"
zstd-sys.path = "../zstd-sys-2.0.15+zstd.1.5.7"
END

  rm rust-toolchain.toml
  cargo update -p bzip2-sys -p zstd-sys
  cargo upgrade -p rocksdb@0.24.0
  cargo fetch --locked --target "${RUST_CHOST}"
}

build() {
  cd "${_realname}"

  export BINDGEN_EXTRA_CLANG_ARGS="--target=${CARCH}-pc-windows-gnu"
  export RUSTFLAGS="${RUSTFLAGS/+crt-static/-crt-static}"
  export LIBCLANG_PATH="${MINGW_PREFIX}/bin"
  export ZSTD_SYS_USE_PKG_CONFIG=1
  cargo build --release --frozen
}

package() {
  cd "${_realname}"

  install -Dm755 target/release/surreal "${pkgdir}${MINGW_PREFIX}/bin/surreal"
  install -Dm644 LICENSE "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
}
