#!/usr/bin/env python3
import sys
from pathlib import Path

import toml

from rfc2317 import gen_reverse_pointers, ZONE as RFC2317_ZONE
from roa import export_dnssec_dnskey

ZONE_FILE_MAP = {
    'neo.': Path("dns", "neonetwork"),
    '127.10.in-addr.arpa.': Path("dns", "db.10.127"),
    '7.2.1.0.0.1.d.f.ip6.arpa.': Path("dns", "db.fd10.127")
}
RFC2317_FILE = Path("dns", "rfc2317.toml")
NAMED_TURST_ANCHORS_FILE = Path("dns", "named_trust_anchors.conf")


def iter_rfc2317_entry():
    entries = toml.loads(RFC2317_FILE.read_text())
    for (route, attributes) in entries.items():
        ns = attributes.get("NS")
        ds = attributes.get("DS", list())
        ttl = attributes.get("TTL", -1)
        yield (route, ns, ds, ttl)

def write_named_trust_anchors():
    header = 'trust-anchors {\n'
    footer = '\n}\n'
    contents = []
    dnskeys_exported = export_dnssec_dnskey(include_zsk=False)
    maxzonelen = max(len(entry['zone']) for entry in dnskeys_exported)
    for entry in dnskeys_exported:
        zone, records = entry['zone'], [r['dnskey'] for r in entry['records']]
        for record in records:
            a1, a2, a3, a4 = record.split(maxsplit=3)
            contents.append(f"    {zone:>{maxzonelen}s} static-key {a1} {a2} {a3} \"{a4}\";")
    NAMED_TURST_ANCHORS_FILE.write_text(header + '\n'.join(contents) + footer)

def main():
    DNSKEYS = {entry['zone']: entry['records'] for entry in export_dnssec_dnskey(include_zsk=True)}
    for zone, zone_file in ZONE_FILE_MAP.items():
        orignal = zone_file.read_text()
        records = [orignal, "; AUTOGENERATED"]
        if zone.strip('.') == RFC2317_ZONE.strip('.'):
            records.extend(("", "; rfc2317"))
            for route, ns, ds, ttl in iter_rfc2317_entry():
                records.extend(gen_reverse_pointers(route, ns, ds, ttl))
                records.append("")
        records.extend(("", "; dnskey"))
        for dnskey in DNSKEYS[zone]:
            records.append(f"@ IN DNSKEY {dnskey['dnskey']}")
        records.append("")
        zone_file.write_text("\n".join(records))


if __name__ == "__main__":
    main()
    write_named_trust_anchors()
