.DEFAULT_GOAL := help
SHELL := /usr/bin/env bash
COMPOSE := docker compose

.PHONY: help prep certs up down restart logs ps test test-tls reload clean

help: ## Show this help
	@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {printf "  \033[36m%-12s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST)

prep: ## Re-inject SOA records into all zones (writes zones-prepared/)
	@./scripts/prepare-zones.sh

certs: ## Generate self-signed cert for DoT/DoH (re-run with FORCE=1 to rotate)
	@./scripts/generate-certs.sh

up: prep certs ## Start CoreDNS (prepares zones + ensures certs exist first)
	$(COMPOSE) up -d
	@sleep 2 && $(COMPOSE) logs --tail=20 coredns

down: ## Stop & remove the container
	$(COMPOSE) down

restart: ## Restart CoreDNS (does not re-prep zones)
	$(COMPOSE) restart coredns

reload: prep ## Re-prep zones; CoreDNS auto-plugin will pick changes up
	@echo "Zones re-prepared. CoreDNS reloads files every 30s (auto plugin)."

logs: ## Tail CoreDNS logs
	$(COMPOSE) logs -f coredns

ps: ## Show container status
	$(COMPOSE) ps

test: ## Smoke-test plain DNS (uses DNS_PORT from .env)
	@. ./.env && echo "Querying acrazy.org @ 127.0.0.1:$$DNS_PORT (plain DNS)" && \
		dig @127.0.0.1 -p $$DNS_PORT acrazy.org SOA +short && \
		dig @127.0.0.1 -p $$DNS_PORT acrazy.org NS +short && \
		dig @127.0.0.1 -p $$DNS_PORT or.acrazy.org A +short

test-tls: ## Smoke-test DoT + DoH (pins self-signed cert via +tls-ca)
	@. ./.env && \
		echo "=== DoT @ 127.0.0.1:$$DOT_PORT ===" && \
		dig @127.0.0.1 -p $$DOT_PORT +tls +tls-ca=certs/cert.pem \
			+tls-hostname=localhost acrazy.org SOA +short && \
		echo "" && \
		echo "=== DoH @ https://localhost:$$DOH_PORT/dns-query ===" && \
		dig @localhost -p $$DOH_PORT +https +tls-ca=certs/cert.pem \
			acrazy.org A +short && \
		echo "" && \
		echo "=== DoH via curl (raw wire-format) ===" && \
		curl -sk --cacert certs/cert.pem \
			-H 'accept: application/dns-message' \
			--data-binary @<(printf '\x00\x00\x01\x20\x00\x01\x00\x00\x00\x00\x00\x00\x06acrazy\x03org\x00\x00\x01\x00\x01') \
			-H 'content-type: application/dns-message' \
			"https://localhost:$$DOH_PORT/dns-query" | xxd | head -5

clean: down ## Remove containers + prepared zones + certs
	rm -rf zones-prepared/*.zone certs/*.pem
