# This is the migration makefile.
#
# WHAT IS NEEDED FOR THE MIGRATION:
#
# - having done the migration process with authd (migration of the user accounts)
# - $(SQLDB): a dump of the SQL database (format: login password domain)
# - $(OLDBINDDIR): directory with old Bind9 zone files
#
# HOW MIGRATION WORKS, STEP BY STEP (`migration` rule):
#
# 1. build-client         -> build bin/dnsmanagerctl
# 2. migration-file       -> generate $(MIGRATION_FILE_TARGET)
# 3. run-migration-client -> create users and attribute domains
# 4. run-client-genzones  -> generate Bind9 zone files with dnsmanagerd
#                            those files will (mostly) be replaced by the old migrated Bind9 zone files
# 5. copy-old-zones       -> copies the old Bind9 zone files where dnsmanagerd just produced its Bind9 zone files
#
# AFTER THE `migration` RULE: `powerdns-add-zones` as root
# This will run `pdns_control bind-add-zone domain zonefile` for every zone file in $(POWERDNS_ZONEDIR).
# Then the different zones should be served by powerdns.


# Migration input file, format: login password domain
SQLDB                 ?= /tmp/usrdb

# Migration final file format: nb-domains <TAB> login <TAB> domain1 <TAB> domain2 <TAB> domain3
MIGRATION_FILE_TARGET ?= /tmp/dnsmanagerd-migration

# Old Bind9 migrated files.
OLDBINDDIR            ?= /tmp/rndczones

# Directory where Bind9 zone files are generated by dnsmanagerd.
BINDDIR               ?= /tmp/DATA-dnsmanagerd/bind9-zones

# Where powerdns reads Bind9 zone files.
POWERDNS_ZONEDIR      ?= /var/powerdns

$(MIGRATION_FILE_TARGET):
	./bin/sql-to-migration-format.awk < $(SQLDB) > $(MIGRATION_FILE_TARGET)

run-migration-client:
	./bin/dnsmanagerctl admin migration-script $(MIGRATION_FILE_TARGET) $(LOGIN)

copy-old-zones:
	cd $(BINDDIR) && for i in * ; do cp -v $(OLDBINDDIR)/$$i . ; done

$(OLDBINDDIR):
	@echo "you forgot to get a copy of old bind zones here: $(OLDBINDDIR)"
	exit 1

# A nice rule for the command-line.
migration-file: $(MIGRATION_FILE_TARGET)

fix-old-zones-ns:
	@echo "fix old zones NS entries"
	sed -i "s/ns0.arn-fai.net/ns0.karchnu.fr/g"        $(OLDBINDDIR)/*
	sed -i "s/alsace.tetaneutral.net/ns1.karchnu.fr/g" $(OLDBINDDIR)/*

migration: build-client migration-file fix-old-zones-ns run-migration-client run-client-genzones copy-old-zones
	@echo "next as root: make powerdns-add-zones"

# POWERDNS RULES
powerdns-create-zonedir:
	-mkdir -p $(POWERDNS_ZONEDIR)
	cp -v $(BINDDIR)/* $(POWERDNS_ZONEDIR)

powerdns-add-zones: powerdns-create-zonedir
	cd $(POWERDNS_ZONEDIR) && for i in *; do pdns_control bind-add-zone $$i $(POWERDNS_ZONEDIR)/$$i; done