KEYFLAGS=257
HASHALG=2 # For dnssec-dsfromkey

all: root-anchors.txt root-anchors.dnskey root-anchors.mkey

root-anchors.xml:
	-wget -nc -O root-anchors.xml https://data.iana.org/root-anchors/root-anchors.xml && touch root-anchors.xml
	-wget -nc -O root-anchors.asc https://data.iana.org/root-anchors/root-anchors.asc && touch root-anchors.asc
	gpg --verify root-anchors.asc root-anchors.xml || \
		sh -c 'echo "Invalid root-anchors.xml"; rm -f root-anchors.xml root-anchors.asc; exit 1;'
	@echo "OK, root-anchors.xml is correct"

root-anchors.txt: root-anchors.xml
	xsltproc -o root-anchors.txt anchors2ds.xsl root-anchors.xml
	dig DNSKEY . | grep -w ${KEYFLAGS} > untrusted.key
	# Verify the key
	# Thanks to Kazunori Fujiwara for the idea
	dnssec-dsfromkey -${HASHALG} untrusted.key > untrusted.ds
	cut -d' ' -f1-6 untrusted.ds | tr '\n' ' ' > root-anchors.tmp
	cut -d' ' -f7- untrusted.ds | sed 's/ //g' | tr '\n' ' ' >> root-anchors.tmp
	echo >> root-anchors.tmp
	@diff root-anchors.txt root-anchors.tmp || \
		sh -c 'echo "Invalid DNSKEY, deleting temporary files"; rm -f root-anchors.txt root-anchors.tmp untrusted.key untrusted.ds; exit 1;'
	@echo "OK, root-anchors.txt is correct"

root-anchors.dnskey: root-anchors.txt
	awk  '{ORS=""; print  $$1 " " $$5 " " $$6 " " $$7 " " "\""; for (i = 8; i <= NF-1; i++) printf $$i " \n\t\t"; print $$NF "\";\n"  }' untrusted.key >root-anchors.dnskey;

root-anchors.mkey: root-anchors.txt
	awk  '{ORS=""; print "managed-keys {\n\t" $$1 " initial-key " $$5 " " $$6 " " $$7 " " "\""; for (i = 8; i <= NF-1; i++) printf $$i " \n\t\t"; print $$NF "\";\n};\n"  }' untrusted.key >root-anchors.mkey

clean:
	rm -f root-anchors.txt untrusted.key untrusted.ds root-anchors.tmp

realclean: clean
	rm -f root-anchors.xml root-anchors.asc root-anchors.dnskey root-anchors.mkey
