# Maintainer: Martell Malone <martellmalone@gmail.com>

_realname=luajit
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=2.1.0_beta3
pkgrel=2
_sourcedir=${_realname}-${pkgver//_/-}
pkgdesc="Just-in-time compiler and drop-in replacement for Lua 5.1 (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32')
url="https://luajit.org/"
license=('MIT')
depends=('winpty')
conflicts=("${MINGW_PACKAGE_PREFIX}-lua51"
           "${MINGW_PACKAGE_PREFIX}-luajit-git")
provides=("${MINGW_PACKAGE_PREFIX}-lua51"
          "${MINGW_PACKAGE_PREFIX}-luajit-git")
replaces=("${MINGW_PACKAGE_PREFIX}-lua51"
          "${MINGW_PACKAGE_PREFIX}-luajit-git")
makedepends=("${MINGW_PACKAGE_PREFIX}-gcc")
options=('strip' 'staticlibs')
source=("https://luajit.org/download/LuaJIT-${pkgver//_/-}.tar.gz"
        001-make-import-library.patch
        002-fix-pkg-config-file.patch)
sha256sums=('1ad2e34b111c802f9d0cdf019e986909123237a28c746b21295b63c9e785d9c3'
            '43084f57315e0d5b55094d71c5f46cf4a5b72d7cecb2f82a409213a598c699e5'
            '4df486e82b0bbeead01dcf6001e90c51477a3a8ac18611d60d7067f2c7013428')

prepare() {
  cd "${srcdir}/${_sourcedir}"
  patch -p1 -i ${srcdir}/001-make-import-library.patch
  patch -p1 -i ${srcdir}/002-fix-pkg-config-file.patch
  sed -i "s|export PREFIX= /usr/local|export PREFIX="${MINGW_PREFIX}"|g" ${srcdir}/${_sourcedir}/Makefile
}

build() {
  cd "${srcdir}/${_sourcedir}"

  msg "Build static version"
  make amalg BUILDMODE=static XCFLAGS=-DLUAJIT_ENABLE_GC64

  msg "Build dynamic version"
  make XCFLAGS=-DLUAJIT_ENABLE_GC64
}

package() {
  cd "${srcdir}/${_sourcedir}"
  make DESTDIR=${pkgdir} install

  echo "#!/usr/bin/env bash" > "${pkgdir}${MINGW_PREFIX}/bin/${_realname}"
  echo '/usr/bin/winpty "$( dirname ${BASH_SOURCE[0]} )/'${_realname}'.exe" "$@"' >> "${pkgdir}${MINGW_PREFIX}/bin/${_realname}"

  install -v -Dm644 "${srcdir}/${_sourcedir}/src/lua51.dll" "${pkgdir}${MINGW_PREFIX}/bin/lua51.dll" || exit 1
  install -v -Dm644 "${srcdir}/${_sourcedir}/src/luajit.exe" "${pkgdir}${MINGW_PREFIX}/bin/luajit.exe" || exit 1
  install -v -Dm644 "${srcdir}/${_sourcedir}/src/libluajit-5.1.dll.a" "${pkgdir}${MINGW_PREFIX}/lib/libluajit-5.1.dll.a" || exit 1

  cp ${pkgdir}${MINGW_PREFIX}/lib/pkgconfig/lua{jit,5.1}.pc
}
