PREFIX ?= /usr/local
BINDIR ?= $(PREFIX)/bin
CC ?= cc
PKG_CONFIG ?= pkg-config
WAYLAND_SCANNER ?= wayland-scanner

WLR_PROTO_DIR ?= /usr/share/wlr-protocols/unstable
WAYLAND_PROTO_DIR ?= /usr/share/wayland-protocols/stable/xdg-shell

SCREENCOPY_XML = $(WLR_PROTO_DIR)/wlr-screencopy-unstable-v1.xml
LAYER_SHELL_XML = $(WLR_PROTO_DIR)/wlr-layer-shell-unstable-v1.xml
XDG_SHELL_XML = $(WAYLAND_PROTO_DIR)/xdg-shell.xml

CFLAGS ?= -O2 -Wall -Wextra -Wpedantic
CPPFLAGS += -Ibuild -Isrc
LDLIBS += $(shell $(PKG_CONFIG) --libs wayland-client)
CFLAGS += $(shell $(PKG_CONFIG) --cflags wayland-client)

GEN_H = \
	build/wlr-screencopy-unstable-v1-client-protocol.h \
	build/wlr-layer-shell-unstable-v1-client-protocol.h \
	build/xdg-shell-client-protocol.h

GEN_C = \
	build/wlr-screencopy-unstable-v1-protocol.c \
	build/wlr-layer-shell-unstable-v1-protocol.c \
	build/xdg-shell-protocol.c

OBJS = \
	build/main.o \
	build/wlr-screencopy-unstable-v1-protocol.o \
	build/wlr-layer-shell-unstable-v1-protocol.o \
	build/xdg-shell-protocol.o

all: hyprtile-screener

build:
	mkdir -p build

build/wlr-screencopy-unstable-v1-client-protocol.h: $(SCREENCOPY_XML) | build
	$(WAYLAND_SCANNER) client-header $< $@

build/wlr-screencopy-unstable-v1-protocol.c: $(SCREENCOPY_XML) | build
	$(WAYLAND_SCANNER) private-code $< $@

build/wlr-layer-shell-unstable-v1-client-protocol.h: $(LAYER_SHELL_XML) | build
	$(WAYLAND_SCANNER) client-header $< $@

build/wlr-layer-shell-unstable-v1-protocol.c: $(LAYER_SHELL_XML) | build
	$(WAYLAND_SCANNER) private-code $< $@

build/xdg-shell-client-protocol.h: $(XDG_SHELL_XML) | build
	$(WAYLAND_SCANNER) client-header $< $@

build/xdg-shell-protocol.c: $(XDG_SHELL_XML) | build
	$(WAYLAND_SCANNER) private-code $< $@

build/main.o: src/main.c $(GEN_H) | build
	$(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@

build/%.o: build/%.c | build
	$(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@

hyprtile-screener: $(OBJS)
	$(CC) $(OBJS) $(LDLIBS) -o $@

install: hyprtile-screener
	install -Dm755 hyprtile-screener $(DESTDIR)$(BINDIR)/hyprtile-screener

uninstall:
	rm -f $(DESTDIR)$(BINDIR)/hyprtile-screener

clean:
	rm -rf build hyprtile-screener

.PHONY: all install uninstall clean