# Maintainer: Dobroslaw Kijowski [dobo] <dobo90_at_gmail.com>

pkgbase=lief
pkgname=(lief python-lief)
pkgver=1.0.0
pkgrel=1
pkgdesc='Library to instrument executable formats'
arch=(armv7h aarch64 x86_64)
url='https://lief.quarkslab.com/'
license=(apache)
makedepends=(git cmake ninja python python-build python-installer python-wheel
             python-pydantic-core python-pydantic python-tomli python-scikit-build-core
             python-pyproject-metadata python-pathspec python-setuptools
             nlohmann-json tl-expected) # mbedtls
provides=(libLIEF.so)
source=("git+https://github.com/lief-project/LIEF#tag=${pkgver}")
md5sums=('50970e818b94e5a1f76df6c59f9f0a48')

prepare() {
  cd LIEF

  sed -i '1 i\#include <stdint.h>' include/LIEF/DEX/Field.hpp

  # Try to delete first to make sure it exists
  rm cmake/strip.cmake
  # Don't strip
  echo > cmake/strip.cmake

  sed -i 's/==.*//' api/python/build-requirements.txt
}

build() {
  cd LIEF

  # For https://github.com/python/cpython/issues/151547
  export CC=gcc
  export CXX=g++

  mkdir -p build
  CFLAGS+=" -ffile-prefix-map=${srcdir}=${DBGSRCDIR:-/usr/src/debug}"
  CXXFLAGS+=" -ffile-prefix-map=${srcdir}=${DBGSRCDIR:-/usr/src/debug}"
  export CFLAGS
  export CXXFLAGS
  # LIEF doesn't use cmake install for python plugin so it'll have
  # the build time RPATH with it. Avoid it by not setting it during build time.
  # The python command below will run cmake configure again
  # but it should remember the flags we set here.
  cmake . -B build -DCMAKE_BUILD_TYPE=Release \
        -DBUILD_SHARED_LIBS=On \
        -DCMAKE_SKIP_BUILD_RPATH=On \
        -DLIEF_PYTHON_API=On \
        -DLIEF_C_API=On \
        -DLIEF_OPT_NLOHMANN_JSON_EXTERNAL=ON \
        -DLIEF_OPT_EXTERNAL_EXPECTED=ON \
        -DLIEF_EXAMPLES=Off -G Ninja
  # LIEF uses functions that was made private in mbedtls 3.6
  # -DLIEF_OPT_MBEDTLS_EXTERNAL=ON
  cmake --build build

  cd api/python
  python -m build --wheel --no-isolation
}

package_lief() {
  cd LIEF/build

  DESTDIR="${pkgdir}" ninja install
}

package_python-lief() {
  pymin_ver=$(python -c 'import sys; print(sys.version_info.minor)')
  ((pynext_min=pymin_ver + 1))
  depends+=("python>=3.${pymin_ver}.0" "python<3.${pynext_min}.0" lief)

  cd LIEF/api/python

  python -m installer --destdir="$pkgdir" dist/*.whl
}
