# SPDX-License-Identifier: GPL-2.0
#
# Builds the driver against the kernel tree in ../kbuild, which
# ../make_kbuild.sh makes. The build itself is described in Kbuild.
#
#   make          klog.ko, and compile_commands.json for clangd
#   make load     load it (sudo), and make its files in /dev if they are missing
#   make nodes    make the files of devices that appeared later (OrbStack)
#   make unload   unload it
#   make clean    remove the build output (compile_commands.json stays)
#
# The CMake build (the Build button in VS Code) runs `make` here too.

MODULE := klog
KDIR   ?= $(abspath $(CURDIR)/../kbuild)
M      := $(CURDIR)

# Build with the compiler the kernel was built with: clang for OrbStack,
# GCC for most distributions.
ifneq ($(shell grep -s '^CONFIG_CC_IS_CLANG=y' $(KDIR)/.config),)
KFLAGS += LLVM=1
endif

.PHONY: all modules compile_commands.json load nodes unload clean check-kdir

all: modules compile_commands.json

check-kdir:
	@test -f $(KDIR)/Makefile || \
		{ echo "No kernel tree in $(KDIR): run ./make_kbuild.sh in the project folder first." >&2; exit 1; }

modules: check-kdir
	$(MAKE) -C $(KDIR) M=$(M) $(KFLAGS) modules

compile_commands.json: modules
	$(MAKE) -C $(KDIR) M=$(M) $(KFLAGS) compile_commands.json

# The kernel (devtmpfs) makes the files in /dev when the module registers its
# devices, and udev then adjusts them. Some machines (OrbStack) have no
# devtmpfs on /dev: there `nodes` makes them from the numbers in sysfs, for
# every device of the module (/sys/class/<class>/<module>*/dev). That is
# /dev/klog here, and /dev/<name>0, /dev/<name>1, ... for a USB driver, one
# per board. Run `make nodes` again for a board plugged in later.
load: modules
	sudo insmod ./$(MODULE).ko
	@sleep 0.5; $(MAKE) --no-print-directory nodes

nodes:
	@for d in /sys/class/*/$(MODULE) /sys/class/*/$(MODULE)[0-9]*; do \
		[ -f "$$d/dev" ] || continue; n=$$(basename $$d); \
		[ -e /dev/$$n ] || sudo mknod -m 0666 /dev/$$n c $$(tr : ' ' < $$d/dev); \
	done

unload:
	sudo rmmod $(MODULE)
	@for f in /dev/$(MODULE) /dev/$(MODULE)[0-9]*; do \
		if [ -c "$$f" ]; then sudo rm -f "$$f"; fi; \
	done

clean:
	@if [ -f $(KDIR)/Makefile ]; then $(MAKE) -C $(KDIR) M=$(M) $(KFLAGS) clean; fi
