#!/usr/bin/python3
#
# $id$
#
# wikidns-zonetool.py
#
# Copyright (C) 2024  Aamot Engineering <ole@aamot.engineering>
# Copyright (C) 2024  Ole Aamot <ole@gnu.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import json
import dns.resolver
import sys
import os

import json
import dns.resolver
import sys
import os

def resolve_dns(json_input):
    # Parse the JSON input
    data = json.loads(json_input)

    domain_name = data['domain_name']
    dns_records = []

    # For each record type specified in the JSON input, perform a DNS query
    for record in data.get('dns_records', []):
        record_type = record['type']

        # Try to resolve the DNS query based on the record type
        try:
            result = dns.resolver.resolve(domain_name, record_type)
            for ipval in result:
                dns_records.append({
                    "type": record_type,
                    "value": ipval.to_text()
                })
        except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN) as e:
            print(f"No answer or NXDOMAIN for {domain_name} with record type {record_type}: {e}")
        except Exception as e:
            print(f"Error resolving {record_type} record for {domain_name}: {e}")

    # Return the domain name and resolved DNS records
    return domain_name, dns_records

def bind9_zone_format(domain_name, dns_records):
    """
    Convert DNS records to BIND9 zone file format.
    """
    zone_file_lines = []

    # Start the zone file
    zone_file_lines.append(f"$TTL 86400")  # Default TTL: 24 hours
    zone_file_lines.append(f"@    IN    SOA   {domain_name}. root.{domain_name}. (1 86400 3600 1209600 86400)")

    # Loop through the DNS records and format each one for the zone file
    for record in dns_records:
        record_type = record["type"]
        value = record["value"]

        if record_type == "A":
            zone_file_lines.append(f"@    IN    A    {value}")
        elif record_type == "MX":
            priority = 10  # Default priority for MX records
            zone_file_lines.append(f"@    IN    MX   {priority} {value}")
        elif record_type == "CNAME":
            zone_file_lines.append(f"@    IN    CNAME   {value}")
        elif record_type == "TXT":
            zone_file_lines.append(f"@    IN    TXT   \"{value}\"")
        # Add more record types as needed

    # End the zone file
    zone_file_lines.append(f"@    IN    NS   {domain_name}.")

    # Join and return the zone file content
    return "\n".join(zone_file_lines)

def save_to_zone_file(domain_name, zone_content, output_filename):
    """
    Save the BIND9 zone content to a file.
    """
    with open(output_filename, 'w') as file:
        file.write(zone_content)
    print(f"Zone file for {domain_name} saved as {output_filename}")

def main():
    if len(sys.argv) != 3:
        print("Usage: python wikidns-mapper.py <input_json_file> <output_zone_file>")
        sys.exit(1)

    input_file = sys.argv[1]
    output_file = sys.argv[2]

    # Read JSON from file
    with open(input_file, 'r') as file:
        json_input = file.read()

    # Call the function to resolve DNS and get domain_name and dns_records
    domain_name, dns_records = resolve_dns(json_input)

    # Convert the records to BIND9 zone file format
    zone_content = bind9_zone_format(domain_name, dns_records)

    # Save the content to a zone file
    save_to_zone_file(domain_name, zone_content, output_file)

if __name__ == '__main__':
    main()
