# Maintainer: Junjie Mao <eternal.n08@gmail.com>

_bootstrap_flexdll=1

_realname=flexdll
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=0.43
pkgrel=1
pkgdesc="An implementation of a dlopen-like API for Windows (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64')
url='https://github.com/ocaml/flexdll'
license=('spdx:Zlib')
makedepends=("${MINGW_PACKAGE_PREFIX}-ocaml"
             "${MINGW_PACKAGE_PREFIX}-cc"
             $( (( _bootstrap_flexdll )) && echo \
               "${MINGW_PACKAGE_PREFIX}-flexdll-bootstrap" || echo \
               "${MINGW_PACKAGE_PREFIX}-flexdll"))
source=("https://github.com/ocaml/flexdll/archive/${pkgver}/flexdll-${pkgver}.tar.gz"
        "0003-Remove-the-usages-of-stdout-to-workaround-the-missin.patch"
        "0004-use-lib-flexdll-as-the-default-library-path.patch")
sha256sums=('10e171ab7d2f8b2f238b53bb9944d4b26686f5703fbc1c059532791bc91be949'
            '3d9470049d1e8070861cf344b6e31caca89c98ab9801483b48d69e81a45c1d1e'
            'c5e6d9891557866d1dfaed3a693dfaa294babfbecec1970ac2f51ae9eabc10d8')

if [ "${CARCH}" == "x86_64" ]; then
  chain="mingw64"
fi

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

  patch -p1 -i "${srcdir}"/0003-Remove-the-usages-of-stdout-to-workaround-the-missin.patch
  patch -p1 -i "${srcdir}"/0004-use-lib-flexdll-as-the-default-library-path.patch
  sed -e "s|MSVC_DETECT=1|MSVC_DETECT=0|g" -i Makefile

  export _cc_ver=$(${CC} -dumpversion)
  if [[ ${MINGW_PACKAGE_PREFIX} == *-clang-* ]]; then
    export _cc_lib_dir=${MINGW_PREFIX}/lib/clang/${_cc_ver}/windows/
  else
    export _cc_lib_dir=${MINGW_PREFIX}/lib/gcc/${MINGW_CHOST}/${_cc_ver}/
  fi

  SEDTEXT="s:LINKFLAGS = -cclib \"-link \$(RES)\":LINKFLAGS = -cclib \"-link \$(RES) -L${MINGW_PREFIX}/lib -L${_cc_lib_dir}\":g"
  sed -i "${SEDTEXT}" Makefile

  export CAMLLIB=$(cygpath -m $MINGW_PREFIX/lib/ocaml)
}

build() {
  [[ -d "${srcdir}"/build-${MSYSTEM} ]] && rm -rf "${srcdir}"/build-${MSYSTEM}
  cp -rf ${_realname}-${pkgver} build-${MSYSTEM}
  cd "${srcdir}"/build-${MSYSTEM}

  make flexlink.exe
  make build_${chain}
}

check() {
  # The test demo works on x86_64 but fails on i686. Root causes of the failure
  # is still unknown, but the tool is good enough to be used in other
  # applications such as ocaml and coq.
  plain "skip"
}

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

  install -Dm755 flexlink.exe "${pkgdir}"${MINGW_PREFIX}/bin/flexlink.exe
  for f in flexdll_${chain}.o flexdll_initer_${chain}.o flexdll.h flexdll.c flexdll_initer.c default.manifest default_amd64.manifest; do
    install -D ${f} "${pkgdir}"${MINGW_PREFIX}/lib/flexdll/${f}
  done
  [ -f LICENSE ] && install -Dm644 LICENSE "${pkgdir}"${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE
  [ -f CHANGES ] && install -Dm644 CHANGES "${pkgdir}"${MINGW_PREFIX}/share/licenses/${_realname}/CHANGES
}
