SHELL := /bin/bash

TAGS ?= all

include .env
export

PWD := $(shell pwd)

.FORCE:

./inventory/group_vars/all/all_services.yml: .FORCE
	tofu output --json \
		| yq -y '{all_services: with_entries(.value |= .value).services | to_entries | map(.value)}' \
		> ./inventory/group_vars/all/all_services.yml

./inventory/group_vars/all/opentofu.yml: .FORCE
	tofu output --json \
		| yq -y '{opentofu: with_entries(.value |= .value)}' \
		> ./inventory/group_vars/all/opentofu.yml

./dns/hosts.json: .FORCE
	tofu output --json \
		| jq 'with_entries(.value |= .value).hosts' \
		> ./dns/hosts.json

./dns/services.json: ./inventory/group_vars/all/all_services.yml
	ansible-playbook \
		-e services_json_file=$(PWD)/dns/services.json \
		playbooks/create_services_for_dnscontrol.yml


output: ./dns/hosts.json ./dns/services.json ./inventory/group_vars/all/opentofu.yml


./types-dnscontrol.d.ts:
	dnscontrol write-types

tofu:
	tofu apply
	@printf "\n=====\n\n"
	$(MAKE) output

dns: ./types-dnscontrol.d.ts ./dns/hosts.json ./dns/services.json
	dnscontrol push

dns-check: ./types-dnscontrol.d.ts ./dns/hosts.json ./dns/services.json
	dnscontrol check-creds ovh

all:
	$(MAKE) tofu
	$(MAKE) dns
	@printf "\n=====\n\n"
	ansible-playbook ./playbooks/serguzim.net.yml -t $(TAGS)

visualize:
	tofu output --json \
		| jq 'with_entries(.value |= .value)' \
		| ./visualize.py \
		| d2 - infrastructure.svg