# Generated by Django 4.0.8 on 2022-10-26 18:55

from netaddr import IPNetwork, AddrFormatError

from django.db import migrations
import netbox_dns.fields.network


def update_zone_arpa_network(apps, schema_editor):
    Zone = apps.get_model("netbox_dns", "Zone")

    for zone in Zone.objects.filter(name__endswith=".arpa"):
        name = zone.name

        if name.endswith(".in-addr.arpa"):
            address = ".".join(reversed(name.replace(".in-addr.arpa", "").split(".")))
            mask = len(address.split(".")) * 8

            try:
                zone.arpa_network = IPNetwork(f"{address}/{mask}")
            except AddrFormatError:
                zone.arpa_network = None

        elif name.endswith("ip6.arpa"):
            address = "".join(reversed(name.replace(".ip6.arpa", "").split(".")))
            mask = len(address)
            address = address + "0" * (32 - mask)

            try:
                zone.arpa_network = IPNetwork(
                    f"{':'.join([(address[i:i+4]) for i in range(0, mask, 4)])}::/{mask*4}"
                )
            except AddrFormatError:
                zone.arpa_network = None

        zone.save()


class Migration(migrations.Migration):

    dependencies = [
        ("netbox_dns", "0017_alter_record_ttl"),
    ]

    operations = [
        migrations.AddField(
            model_name="zone",
            name="arpa_network",
            field=netbox_dns.fields.network.NetworkField(blank=True, null=True),
        ),
        migrations.RunPython(update_zone_arpa_network),
    ]
