.POSIX:

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

STATIC ?= off
DEBUG ?= 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

# enumerate build options
BUILD_FLAGS = \
	flags=""; \
	if [ "$(STATIC)" = "on" ]; then flags="$$flags --static"; fi; \
	if [ "$(HARDENING)" = "on" ]; then flags="$$flags --link-flags -Wl,-zrelro,-znow"; fi; \
	if [ "$(DEBUG)" = "on" ]; then flags="$$flags --debug"; fi;

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; }

lint:
	shards --no-color -v build -s -t -p --production --release ameba -Dpreview_mt
	bin/ameba --no-color

test:
	crystal spec --no-color -v -s -t -p --release

# find ascii files to build with
ASCII_FILES = \
	ascii_files="$$(find src/exfetch/ascii -type f -name '*.ascii' -exec basename {} \;)"; \
	printf "Found ASCII files:\n$$ascii_files\n"; \
	ASCII_FILES="$$ascii_files"

$(BIN):
	@$(BUILD_FLAGS) \
	$(ASCII_FILES) \
	shards --no-color -v build exfetch -s -t -p --production --release $$flags

run:
	@$(BUILD_FLAGS) \
	$(ASCII_FILES) \
	shards --no-color -v run exfetch -s -t -p --production --release $$flags

install: all
	$(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

.PHONY: all check lint test install uninstall clean
