#!/usr/bin/python3

#
# Copyright (C) 2022 Nethesis S.r.l.
# SPDX-License-Identifier: GPL-2.0-only
#

from nethsec import utils
import nsmigration

(u, data, nmap) = nsmigration.init("dns.json")

# Setup hostname
fqdn = f'{data["general"]["hostname"]}.{data["general"]["domain"]}'
for section in u.get("system"):
    if  u.get("system", section) == "system":
        nsmigration.vprint(f"Setting FQDN {fqdn}")
        u.set("system", section, "hostname", fqdn)
        del data["general"]["hostname"] # avoid to set an unsupported option in the next loop

dnsmasq_section = ''
# Set global options
for section in u.get("dhcp"):
    if  u.get("dhcp", section) == "dnsmasq":
        dnsmasq_section = section # for later use
        for o in data['general']:
            nsmigration.vprint(f"Setting DNS option {o}")
            u.set("dhcp", section, o, data['general'][o])

        nsmigration.vprint(f"Setting DNS forwardings")
        u.set("dhcp", section, "server", data["forwardings"])

# Create hosts entries
for host in data["hosts"]:
    hname = utils.get_id(host["name"])
    nsmigration.vprint(f'Creating host {hname}')
    u.set("dhcp", hname, "domain") # create named record
    for o in host:
        u.set("dhcp", hname, o, host[o])

# Create wildcard hosts
addresses = []
for address in data["addresses"]:
    aname = utils.get_id(address["name"])
    nsmigration.vprint(f'Creating wildcard record {aname}')
    addresses.append(f'/{address["name"]}/{address["ip"]}')
    dname = utils.get_random_id()
    u.set("dhcp", dname, "domain") # create named record
    for o in address:
        u.set("dhcp", dname, o, address[o])

u.set("dhcp", dnsmasq_section, "address", addresses)

# Save configuration
u.commit("dhcp")
u.commit("system")
