# Environment vars
DIST_DIR := dist
DIR_OF_PROJECTS := src/projets

# Computed vars
SRC_HTMLS := $(shell find src -name '*.src.html')
SRC_MDS := $(shell find src -name '*.src.md')
SRC_TEMPLATES := $(shell find src/templates -name '*.html')
SRC_LIST_YML := $(shell echo $(DIR_OF_PROJECTS)/*/*.meta.yml)

GEN_HTMLS := $(SRC_HTMLS:%.src.html=%.gen.html)
GEN_MDS := $(SRC_MDS:%.src.md=%.gen.html)
GEN_LIST_YML := $(DIR_OF_PROJECTS)/list.gen.yml
GEN_CONTENT_FILES := $(GEN_HTMLS) $(GEN_MDS)
GEN_FILES := $(GEN_CONTENT_FILES) $(GEN_LIST_YML)

INCLUDED_FILES := $(shell find src/include -type f)
EMBEDDED_FILES := $(shell find src -name '*.png' -or -name '*.svg' -or -name '*.pdf' -or -name '*.ico')

DIST_GEN_FILES := $(GEN_CONTENT_FILES:src/%.gen.html=$(DIST_DIR)/%.html)
DIST_INC_FILES := $(INCLUDED_FILES:src/%=$(DIST_DIR)/%)
DIST_EMB_FILES := $(EMBEDDED_FILES:src/%=$(DIST_DIR)/%)
DIST_FILES := $(DIST_GEN_FILES) $(DIST_INC_FILES) $(DIST_EMB_FILES)

BUILD_VERSION := $(shell git describe)
BUILD_DATE := $(shell date "+%F")

PANDOC_GEN := pandoc --template src/templates/main.html --metadata-file src/meta.yml --metadata=build-date:$(BUILD_DATE) --metadata=build-version:$(BUILD_VERSION) --wrap=none --metadata-file $(GEN_LIST_YML)
LIST_GEN := yq eval-all '{"data": ., "target": {"content": filename | sub("meta.yml", "html") | sub(".*/", ""), "dir": filename | sub("$(DIR_OF_PROJECTS)/", "") | sub("/[^/]*.yml", "")}} as $$item ireduce ([]; . + $$item) | {"list": .}'

# Functions
extract_category = $(word 2, $(subst /, ,$(1)))
extract_update_date = $(shell git log -1 --pretty="format:%cs" $(1))

# Build
.PHONY: build
build: $(GEN_CONTENT_FILES)
	$(info HTML generated)

%.gen.html: %.src.html %.meta.yml $(SRC_TEMPLATES) $(GEN_LIST_YML)
	$(PANDOC_GEN) --metadata-file $*.meta.yml --metadata=category-$(call extract_category,$*) --metadata=update-date:$(call extract_update_date,$<) --output $@ $<

%.gen.html: %.src.md %.meta.yml $(SRC_TEMPLATES) $(GEN_LIST_YML)
	$(PANDOC_GEN) --metadata-file $*.meta.yml --metadata=category-$(call extract_category,$*) --metadata=update-date:$(call extract_update_date,$<) --output $@ $<

# Build lists
$(GEN_LIST_YML): $(SRC_LIST_YML)
	$(LIST_GEN) $(SRC_LIST_YML) > $@

# Distribution
.PHONY: install
install: $(DIST_DIR)
	$(info Distributed folder generated)

$(DIST_DIR): $(DIST_FILES)

$(DIST_DIR)/%.html: src/%.gen.html
	mkdir --parents $(dir $@)
	cp $< $@

$(DIST_DIR)/%: src/%
	mkdir --parents $(dir $@)
	cp $< $@

# Cleaning
.PHONY: clean
clean:
	rm -f $(GEN_FILES)

.PHONY: clean-dist
clean-dist:
	rm -rf $(DIST_DIR)/*

.PHONY: clean-all
clean-all: clean clean-dist

.PHONY: debug
debug:
	$(info SRC_HTMLS $(SRC_HTMLS))
	$(info SRC_MDS $(SRC_MDS))
	$(info SRC_TEMPLATES $(SRC_TEMPLATES))
	$(info GEN_HTMLS $(GEN_HTMLS))
	$(info GEN_MDS $(GEN_MDS))
	$(info GEN_FILES $(GEN_FILES))
	$(info GEN_CONTENT_FILES $(GEN_CONTENT_FILES))
	$(info INCLUDED_FILES $(INCLUDED_FILES))
	$(info EMBEDDED_FILES $(EMBEDDED_FILES))
	$(info DIST_FILES $(DIST_FILES))
