#!/usr/bin/python3
#
# $id$
#
# wikidns-domain.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 dns.resolver
import json
import sys

def enumerate_dns_records(domain):
    records = []

    # DNS servers to query
    dns_servers = [
        '8.8.8.8',       # Google Public DNS
        '8.8.4.4',       # Google Public DNS
        '1.1.1.1',       # Cloudflare DNS
        '9.9.9.9',       # Quad9 DNS
        '208.67.222.222' # OpenDNS
    ]

    record_types = ['A', 'AAAA', 'CNAME', 'MX', 'TXT', 'NS', 'SOA', 'SRV']

    for record_type in record_types:
        for dns_server in dns_servers:
            resolver = dns.resolver.Resolver(configure=False)
            resolver.nameservers = [dns_server]

            try:
                answers = resolver.resolve(domain, record_type)
                for rdata in answers:
                    record_info = {
                        "type": record_type,
                        "value": rdata.to_text()
                    }
                    if record_type == 'MX':
                        record_info["preference"] = rdata.preference
                        record_info["exchange"] = rdata.exchange.to_text()
                    elif record_type == 'SRV':
                        record_info["priority"] = rdata.priority
                        record_info["weight"] = rdata.weight
                        record_info["port"] = rdata.port
                        record_info["target"] = rdata.target.to_text()
                    records.append(record_info)
            except Exception as e:
                pass

    return {"domain_name": domain, "dns_records": records}

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python wikidns-domain.py <domain>")
        sys.exit(1)

    domain = sys.argv[1]
    dns_records = enumerate_dns_records(domain)

    # Write DNS records to JSON file
    json_file = "{}_dns_records.json".format(domain.replace('.', '_'))
    with open(json_file, 'w') as f:
        json.dump(dns_records, f, indent=4)

    print("DNS records for {} have been saved to {}".format(domain, json_file))
