
ignore_file = .git/info/exclude


.PHONY: help
help: ## Print the help message
	@awk 'BEGIN {FS = ":.*?## "} /^[0-9a-zA-Z._-]+:.*?## / {printf "\033[36m%s\033[0m : %s\n", $$1, $$2}' $(MAKEFILE_LIST) | \
		sort | \
		column -s ':' -t

include wg.mk

.PHONY: check
check: ## Check you have all dependencies
	@command -v graph-easy >/dev/null || { echo "Install perl-graph-easy" && exit 1 ;}
	@command -v ansible >/dev/null || { echo "Install ansible" && exit 1 ;}
	@command -v recsel >/dev/null || { echo "Install recutils" && exit 1 ;}
	@command -v wg >/dev/null || { echo "Install wireguard" && exit 1 ;}
	@command -v lowdown >/dev/null || { echo "Install lowdown" && exit 1 ;}
	@echo "All dependencies installed"

%/:
	mkdir $@
	echo '*' > $@.gitignore

########## Network Map ##########

graph_program != type graph-easy > /dev/null && printf graph-easy || printf dot 

graph_cmd = graph-easy --boxart

queries = queries authqueries

query_formats = $(patsubst %, .dbs/%.txt, $(queries))

dotquery_formats = $(patsubst %, .dbs/%.dot, $(queries))

.dbs/: | $(ignore_file)
	mkdir $@

ignored += .dbs/

$(query_formats): .dbs/%.txt: | .dbs/
	echo "[ {{name}} ] -- $(basename $(@F)) --> [ {{$(basename $(@F))}} ]" > $@

$(dotquery_formats): .dbs/%.dot: | .dbs/
	echo '{{name}} -> {{$(basename $(@F))}} [ label="$(basename $(@F))" ];' > $@

ifeq ($(graph_program),dot)
  map_file = network.png
else
  map_file = network.txt
endif

ignored += $(map_file)

.PHONY: map
map: $(map_file) ## Generate a network map

network.txt: .dbs/network.txt
	$(graph_cmd) < $<

.dbs/network.txt: network.rec $(query_formats)
	$(RM) $@
	$(foreach relation, $(queries), \
	recsel $< -t lxc -e "$(relation) != ''" -p name,$(relation) | recfmt -f .dbs/$(relation).txt >> $@ ;\
	)

.dbs/network.dot: network.rec $(dotquery_formats)
	echo 'digraph network {' > $@
	$(foreach relation, $(queries), \
	recsel $< -t lxc -e "$(relation) != ''" -p name,$(relation) | recfmt -f .dbs/$(relation).dot >> $@ ;\
	)
	echo '}' >> $@

network.png: .dbs/network.dot $(ignore_file)
	dot -T png < $< > $@

##########

$(ignore_file): $(MAKEFILE_LIST)
	echo $(ignored) | tr ' ' '\n' > $@

clean:
	$(RM) -r $(ignored)
