PREFIX ?= /usr/local
BINDIR = $(PREFIX)/bin
MANDIR = $(PREFIX)/share/man/man1
INSTALL ?= install
MKDIR ?= mkdir -p

MULTITHREADED ?= off
STATIC ?= off
# TODO: crystal might incorporate these options as default or through a separate flag
#  see https://github.com/crystal-lang/crystal/issues/11046
HARDENING ?= off

BIN = bin/exfetch
MANPAGE = packaging/exfetch.1

all: check $(BIN)

check:
	@command -v crystal >/dev/null 2>&1 || { echo "Error: crystal is not installed."; exit 1; }
	@command -v shards >/dev/null 2>&1 || { echo "Error: shards is not installed."; exit 1; }

$(BIN):
	@flags=""; \
	if [ "$(MULTITHREADED)" = "on" ]; then flags="$$flags -Dpreview_mt"; fi; \
	if [ "$(STATIC)" = "on" ]; then flags="$$flags --static"; fi; \
	if [ "$(HARDENING)" = "on" ]; then flags="$$flags --link-flags -Wl,-zrelro,-znow"; fi; \
	ascii_files="$$(find src/exfetch/ascii -type f -name '*.ascii' | xargs -n1 basename)"; \
	printf "Found ASCII files:\n$$ascii_files\n"; \
	ASCII_FILES="$$ascii_files" shards --no-color -v build -s -t -p --production --release $$flags

install: $(BIN)
	$(MKDIR) $(DESTDIR)$(BINDIR)
	$(INSTALL) -m 755 $(BIN) $(DESTDIR)$(BINDIR)/exfetch
	$(MKDIR) $(DESTDIR)$(MANDIR)
	$(INSTALL) -m 644 $(MANPAGE) $(DESTDIR)$(MANDIR)/exfetch.1

uninstall:
	rm -f $(DESTDIR)$(BINDIR)/exfetch
	rm -f $(DESTDIR)$(MANDIR)/exfetch.1

clean:
	rm -rf bin

distclean: clean
	rm -f shard.lock
	rm -rf lib

.PHONY: all check install uninstall clean distclean
