PKG_CPPFLAGS = -I"include" -I"quickjs" -D_GNU_SOURCE
PKG_LIBS = libquickjs.o

ifeq ($(OS),Windows_NT)
	DLL := .dll
else
	DLL := .so
endif

ifdef R_HOME
	R_CC := $(shell $(R_HOME)/bin$(R_ARCH_BIN)/R CMD config CC)
	R_CXX := $(shell $(R_HOME)/bin$(R_ARCH_BIN)/R CMD config CXX)
else
	R_CC := $(CC)
	R_CXX := $(CXX)
endif

CLANG_CHECK := $(shell echo | $(R_CC) -dM -E - | grep -i __clang__)

ifneq (,$(CLANG_CHECK))
# Clang on armel needs libatomic
	ifeq ($(shell uname -m), armv7l)
	  CC_TARGET := $(shell $(R_CXX) -v 2>&1 | grep Target | cut -d ' ' -f 2)
		ifeq ($(findstring gnueabihf,$(CC_TARGET)),)
			PKG_LIBS += -latomic
		endif
	endif
else
# Explicit -latomic is needed for 32-bit builds only on GCC
	ifeq ($(shell getconf LONG_BIT), 32)
		PKG_LIBS += -latomic
	endif
endif

SOURCES = quickjsr.cpp init.cpp
OBJECTS = $(SOURCES:.cpp=.o)

$(SHLIB): $(OBJECTS)
$(OBJECTS): build-static

build-static:
#	@mkdir -p ../inst/include/quickjs
#	@cp $(wildcard quickjs/*.h) ../inst/include/quickjs
	$(R_CC) $(ALL_CPPFLAGS) $(ALL_CFLAGS) -funsigned-char -std=gnu11 -c libquickjs.c
#	@mkdir -p ../inst/lib/$(R_ARCH)
#	$(AR) -rs ../inst/lib/$(R_ARCH)/libquickjs.a libquickjs.o

clean:
	$(RM) libquickjs.o $(OBJECTS)
	$(RM) -r ../inst/lib ../inst/include/quickjs
