# Linux port: run from this directory.
#   make test        panel core tests (no hardware, no libraries)
#   make gtk         window with simulated panel and on-screen keys
#   make target      i2c-dev and DRM frontends for the real panel
#   make dtbo        device tree overlay
#   make module      DRM driver, against KDIR (default: running kernel source)

BUILD   := build
CC      ?= gcc
CFLAGS  ?= -O2 -g
CFLAGS  += -std=gnu11 -Wall -Wextra -MMD -MP
CFLAGS  += -Idriver -Isim -Iapp
KDIR    ?= /usr/src/linux

CORE     := driver/s1d13700_core.c
SIM      := sim/s1d13700_sim.c
APP      := app/app_core.c app/ui_render.c app/mpd_client.c app/log_kmsg.c
PLATFORM := app/platform_linux.c

APP_PKGS := glib-2.0 cairo pangocairo libmpdclient
GTK_PKGS := gtk+-3.0 $(APP_PKGS)

objs = $(addprefix $(BUILD)/,$(1:.c=.o))

.PHONY: all test asan gtk target dtbo module clean
all: test gtk

# ---- tests -----------------------------------------------------------------
$(BUILD)/test_panel: tests/test_panel.c $(CORE) $(SIM)
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -o $@ $^

$(BUILD)/test_panel_asan: tests/test_panel.c $(CORE) $(SIM)
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -fsanitize=address,undefined -fno-sanitize-recover=all -o $@ $^

test: $(BUILD)/test_panel
	$<

asan: $(BUILD)/test_panel_asan
	$<

# ---- applications ----------------------------------------------------------
gtk: $(BUILD)/radio-gtk
target: $(BUILD)/radio-i2c $(BUILD)/radio-drm

$(BUILD)/radio-gtk: CFLAGS += $(shell pkg-config --cflags $(GTK_PKGS))
$(BUILD)/radio-gtk: LDLIBS += $(shell pkg-config --libs $(GTK_PKGS))
$(BUILD)/radio-gtk: $(call objs,app/main_gtk.c $(APP) $(CORE) $(SIM))
	$(CC) $(CFLAGS) -o $@ $^ $(LDLIBS)

$(BUILD)/radio-i2c: CFLAGS += $(shell pkg-config --cflags $(APP_PKGS))
$(BUILD)/radio-i2c: LDLIBS += $(shell pkg-config --libs $(APP_PKGS))
$(BUILD)/radio-i2c: $(call objs,app/main_i2c.c $(PLATFORM) $(APP) $(CORE))
	$(CC) $(CFLAGS) -o $@ $^ $(LDLIBS)

$(BUILD)/radio-drm: CFLAGS += $(shell pkg-config --cflags $(APP_PKGS) libdrm)
$(BUILD)/radio-drm: LDLIBS += $(shell pkg-config --libs $(APP_PKGS) libdrm)
$(BUILD)/radio-drm: $(call objs,app/main_drm.c $(PLATFORM) $(APP))
	$(CC) $(CFLAGS) -o $@ $^ $(LDLIBS)

$(BUILD)/%.o: %.c
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -c -o $@ $<

# ---- device tree and kernel module -----------------------------------------
dtbo: $(BUILD)/radio-panel.dtbo

$(BUILD)/radio-panel.dtbo: dts/radio-panel.dts
	@mkdir -p $(dir $@)
	dtc -@ -I dts -O dtb -o $@ $<

module:
	$(MAKE) -C $(KDIR) M=$(CURDIR)/driver modules

clean:
	rm -rf $(BUILD)
	-$(MAKE) -C $(KDIR) M=$(CURDIR)/driver clean

-include $(shell find $(BUILD) -name '*.d' 2>/dev/null)
