export OUT = $(PWD)/out

export ARCH = x86
export OS = lin
export BITS = 64

export TARGET = $(ARCH).$(OS).$(BITS)

moddirs = $(wildcard k*)
modules = $(moddirs:k%=%)
headers = $(moddirs:k%=$(OUT)/k/%.h)
objects = $(modules:%=$(OUT)/k%.o)
makefiles = $(moddirs:%=%/makefile)

binaries = $(wildcard */exe.*.c)
binmods = $(sort $(dir $(binaries)))

all: obj defs tool
obj: $(moddirs:%=%.obj)
defs: $(headers)
tool: $(binmods:%=%.tool)

lists = moddirs modules headers objects makefiles binaries binmods
dbg:
	@echo -e lists: $(foreach var, $(lists), "\\n - \\e[1m$(var)\\e[m = $($(var))")

%.obj: %/makefile ${TARGET}.calls $(OUT)
	cd $* && $(MAKE) obj

%.tool: %/makefile $(OUT)
	cd $* && $(MAKE) tool

%.dbg: %/makefile $(OUT)
	cd $* && $(MAKE) dbg

%.calls: arch/makefile
	cd arch && make calls.$*.s

$(OUT)/libk.so: mods $(OUT)
	$(CC) -shared -o $@ $(objects)

$(OUT)/libk.a: mods $(OUT)
	# using `ar c` and ranlib here instead of
	# `ar cs` in case `ar` isn't the GNU version
	ar c $@ $(objects)
	ranlib $@

$(OUT)/k/%.h: k%/makefile $(OUT)/k
	cd k$* && $(MAKE) $@

$(OUT) $(OUT)/k:
	mkdir -p $@
