LUA ?= lua
PYTHON ?= python3
CC ?= cc
CXX ?= c++
AR ?= ar

CONTRACTS := $(sort $(wildcard lua/api/core/*.lua lua/api/features/*.lua))
LUA_C := $(sort $(wildcard native/src/vendor/lua/*.c))
LUA_OBJECTS := $(patsubst native/src/vendor/lua/%.c,_build/lua/%.o,$(LUA_C))
LUA_LIBRARY := _build/liblua.a
LUA_SMOKE := _build/lua-smoke
RUNTIME_TEST := _build/runtime-test
RUNTIME_CPP := $(sort $(wildcard native/src/runtime/*.cpp native/src/bindings/core/*.cpp \
	native/src/bindings/features/*.cpp))

.PHONY: api test

api:
	@$(PYTHON) tools/gen_api.py

test: $(LUA_SMOKE) $(RUNTIME_TEST)
	@$(PYTHON) tools/gen_api.py --check
	@printf '%-32s ' generated-api; echo ok
	@$(LUA) -e 'assert(_VERSION == "Lua 5.4", "tests require Lua 5.4")'
	@for file in $(CONTRACTS); do $(LUA) -e "assert(loadfile('$$file'))" || exit 1; done
	@printf '%-32s ' contracts; echo ok
	@printf '%-32s ' lua/test/ui.lua; $(LUA) lua/test/ui.lua
	@printf '%-32s ' lua/test/hints.lua; $(LUA) lua/test/hints.lua
	@printf '%-32s ' native/test/lua_smoke.c; $(LUA_SMOKE) && echo ok
	@printf '%-32s ' native/test/runtime_test.cpp; $(RUNTIME_TEST) && echo ok

$(LUA_SMOKE): native/test/lua_smoke.c $(LUA_LIBRARY)
	@$(CC) -std=c99 -DLUA_32BITS -I native/src/vendor/lua $< $(LUA_LIBRARY) -lm -ldl -o $@

$(RUNTIME_TEST): $(RUNTIME_CPP) native/test/runtime_test.cpp $(LUA_LIBRARY)
	@$(CXX) -std=c++11 -Wall -Wextra -DLUA_32BITS -I native/include -I native/src/vendor/lua \
		$(RUNTIME_CPP) native/test/runtime_test.cpp $(LUA_LIBRARY) -lm -ldl -o $@

$(LUA_LIBRARY): $(LUA_OBJECTS)
	@$(AR) rcs $@ $^

_build/lua/%.o: native/src/vendor/lua/%.c
	@mkdir -p $(@D)
	@$(CC) -std=c99 -DLUA_32BITS -I native/src/vendor/lua -c $< -o $@
