include $(TOPDIR)/rules.mk

PKG_NAME:=quickjs
PKG_RELEASE:=1

PKG_SOURCE_PROTO:=git
PKG_SOURCE_URL:=https://github.com/bellard/quickjs.git
PKG_SOURCE_DATE:=2025-07-09
PKG_SOURCE_VERSION:=1fdc768fdc8571300755cdd3e4654ce99c0255ce
PKG_MIRROR_HASH:=skip
PKG_LICENSE:=MIT

PKG_INSTALL:=1
PKG_BUILD_PARALLEL:=1

include $(INCLUDE_DIR)/package.mk

define Package/quickjs
  SECTION:=lang
  CATEGORY:=Languages
  TITLE:=QuickJS Javascript engine
  URL:=https://bellard.org/quickjs/
  MAINTAINER:=Erik Karlsson <erik.karlsson@genexis.eu>
  DEPENDS:=+libatomic
endef

define Package/quickjs/description
  QuickJS is a small and embeddable Javascript engine. It supports
  the ES2020 specification including modules, asynchronous
  generators, proxies and BigInt.
endef

MAKE_FLAGS = \
	PREFIX=/usr \
	EXTRA_LIBS="-latomic" \
	CROSS_PREFIX="$(TARGET_CROSS)"

define Build/Compile
	# The upstream Makefile uses the same CFLAGS for host and target builds,
	# which breaks cross-compilation. We work around this by first building
	# the host tools ('host-qjsc', 'unicode_gen') with the host compiler
	# and flags.
	# We still pass MAKE_FLAGS so the upstream Makefile knows we're cross-compiling.
	CFLAGS="$(HOST_CFLAGS)" \
	LDFLAGS="$(HOST_LDFLAGS)" \
	$(MAKE) -C $(PKG_BUILD_DIR) \
		$(MAKE_FLAGS) \
		host-qjsc unicode_gen

	# Then we proceed with the default build process for the target binaries.
	# Make should not rebuild the host tools as they are already up-to-date.
	$(call Build/Compile/Default)
endef

define Build/InstallDev
	$(INSTALL_DIR) $(1)/usr/lib
	$(CP) $(PKG_INSTALL_DIR)/usr/lib/quickjs/libquickjs.a $(1)/usr/lib/
	$(INSTALL_DIR) $(1)/usr/include/quickjs
	$(CP) $(PKG_INSTALL_DIR)/usr/include/quickjs/quickjs.h $(1)/usr/include/quickjs/
	$(CP) $(PKG_INSTALL_DIR)/usr/include/quickjs/quickjs-libc.h $(1)/usr/include/quickjs/
endef

define Package/quickjs/install
	$(INSTALL_DIR) $(1)/usr/bin
	$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/qjs $(1)/usr/bin/
endef

$(eval $(call BuildPackage,quickjs))
