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

_realname=wasmer
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}"
         "${MINGW_PACKAGE_PREFIX}-lib${_realname}")
pkgver=6.1.0
pkgrel=1
pkgdesc="The leading Wasm Runtime supporting WASIX, WASI and Emscripten (mingw-w64)"
arch=('any')
mingw_arch=('ucrt64' 'clang64')
url="https://github.com/wasmerio/wasmer"
msys2_references=(
  'purl: pkg:cargo/wasmer'
)
license=('spdx:MIT')
makedepends=("${MINGW_PACKAGE_PREFIX}-rust"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-pkgconf"
             "${MINGW_PACKAGE_PREFIX}-openssl"
             "${MINGW_PACKAGE_PREFIX}-nodejs"
             'git')
source=("git+${url}.git#tag=v${pkgver}"
        "reproducible-builds.patch")
sha256sums=('97f8fc7ad39024b9e040614728c1cb300b68dd968fb4492c24992397ffdcd208'
            '005429971f0eb52593dd8dc56ae4aa03b21ef0391b66dd64b2efedc2d64b661b')

prepare() {
  cd "${_realname}"
  rm rust-toolchain

  patch -Np1 -i "../reproducible-builds.patch"

  cargo fetch --locked --target "${RUST_CHOST}"
}

build() {
  cd "${_realname}"

  export OPENSSL_NO_VENDOR=1
  export WINAPI_NO_BUNDLED_LIBRARIES=1
  export WASMER_INSTALL_PREFIX=${MINGW_PREFIX}
  make -O ENABLE_SINGLEPASS=1 ENABLE_CRANELIFT=1 ENABLE_LLVM=0
}

# tests require rustup binary
# check() {
#   cd "${_realame}"
#   make test-examples
# }

package_wasmer() {
  install -Dm755 "${_realname}"/target/release/wasmer "${pkgdir}${MINGW_PREFIX}/bin/wasmer"
  install -Dm644 "${_realname}"/LICENSE "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
}

package_libwasmer() {
  pkgdesc+=' (C-API)'
  conflicts=("${MINGW_PACKAGE_PREFIX}-libwasmtime")

  install -Dm755 "${_realname}"/target/release/wasmer.dll "${pkgdir}${MINGW_PREFIX}/bin/wasmer.dll"
  install -Dm755 "${_realname}"/target/release/wasmer.dll.a "${pkgdir}${MINGW_PREFIX}/lib/wasmer.dll.a"
  install -Dm755 "${_realname}"/target/release/libwasmer.a "${pkgdir}${MINGW_PREFIX}/lib/libwasmer.a"
  install -vDm644 "${_realname}"/lib/c-api/*.h -t "${pkgdir}${MINGW_PREFIX}/include/"
  "${_realname}"/target/release/wasmer config --pkg-config | install -Dm644 /dev/stdin \
    "${pkgdir}${MINGW_PREFIX}/lib/pkgconfig/wasmer.pc"
  install -Dm644 "${_realname}"/LICENSE "${pkgdir}${MINGW_PREFIX}/share/licenses/lib${_realname}/LICENSE"
}

# 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
