# Taken from: https://stackoverflow.com/questions/2214575/passing-arguments-to-make-run
# If the first argument is "new"...
ifeq (new,$(firstword $(MAKECMDGOALS)))
  # use the rest as arguments for "new"
  NEW_ARGS := $(wordlist 2,$(words $(MAKECMDGOALS)),$(MAKECMDGOALS))
  # ...and turn them into do-nothing targets
  $(eval $(NEW_ARGS):;@:)
endif

BIN := $(shell basename $$(pwd))
PLUGINS := $(wildcard modules/*)

MAKE += --no-print-directory

MANSECTION := 1
MANPAGE := $(BIN).$(MANSECTION)

SRCS := $(wildcard *.cpp)
OBJS := $(subst .cpp,.o,$(SRCS))
DEPS := $(subst .cpp,.d,$(SRCS))

CXX ?= g++
PKG_CONFIG ?= pkg-config

PREFIX ?= /usr/local
BINDIR ?= $(PREFIX)/bin
CONFIGDIR ?= $(PREFIX)/etc
DATADIR ?= $(PREFIX)/share
MANDIR ?= $(DATADIR)/man/man
DOCDIR ?= $(DATADIR)/$(BIN)/doc

RM := /bin/rm -f
INSTALL := /usr/bin/install -c

CXXFLAGS := $(CXXFLAGS) -Wshadow -Wall -Wpedantic -Wextra -g -fno-strict-aliasing -std=c++17 -pthread
ifeq ($(DEBUG),1)
	CXXFLAGS += -D DEBUG -O0
else
	CXXFLAGS += -D NDEBUG -O3
endif

LDLIBS := -lm -lpthread -lscgui -lSDL2 -lcairo -lscerror -lscstring -lscscreensaver -ldl

.PHONY: all clean install modules new

all: $(BIN) modules

$(BIN): $(OBJS) $(DEPS)
	$(CXX) $(OBJS) $(LDFLAGS) $(LDLIBS) -o $(BIN)

%.o: %.cpp %.d Makefile
	$(CXX) $(CXXFLAGS) -MMD -MP -MT $@ -MF $*.d -c $<

-include *.d

%.d: ;

new:
	@./newmodule $(NEW_ARGS)

modules: $(PLUGINS)
	mkdir -p plugins
	@for plug in $(PLUGINS) ;\
	do \
		cd $$plug && $(MAKE) && $(MAKE) install ;\
		cd ../.. ;\
	done

clean:
	$(RM) $(OBJS) $(DEPS) $(BIN)
	$(RM) -r plugins
	@for plug in $(PLUGINS) ;\
	do \
		$(MAKE) -C $$plug clean ;\
	done

install: $(BIN)
	$(INSTALL) -d $(BINDIR)
	$(INSTALL) $(BIN) $(BINDIR)
	$(INSTALL) -d $(MANDIR)$(MANSECTION)
	$(INSTALL) $(MANPAGE) $(MANDIR)$(MANSECTION)