import dns.resolver
import requests

BASE_API_URL = "https://dns.it53.nl:8443"

def fetch_zones(api_key):
    headers = {'X-API-Key': api_key}
    response = requests.get(f"{BASE_API_URL}/api/v1/servers/localhost/zones", headers=headers)

    if response.status_code != 200:
        print(f"Error fetching zones: {response.status_code}")
        return []

    try:
        return response.json()
    except ValueError:
        print("Error parsing JSON for zones")
        print(response.text)
        return []

def fetch_ns_records(zone_name):
    try:
        result = dns.resolver.resolve(zone_name, 'NS')
        return [str(ns) for ns in result]
    except dns.resolver.NXDOMAIN:
        print(f"Error: Zone {zone_name} not found.")
        return []
    except dns.resolver.NoAnswer:
        print(f"Error: No NS records found for zone {zone_name}")
        return []

def check_dns_consistency(master_dns, zones, api_key):
    for zone in zones:
        zone_name = zone['name']
        print(f"Checking DNS consistency for zone: {zone_name}")

        # Fetch NS records from the internet
        master_ns_records = fetch_ns_records(zone_name)

        if not master_ns_records:
            continue

        for ns_record in master_ns_records:
            # Check SOA record consistency for each NS
            if ns_record != master_dns:
                soa_record = fetch_ns_records(f"{zone_name}/SOA")  # Use fetch_ns_records instead
                master_soa_record = fetch_ns_records(f"{zone_name}/SOA")  # Use fetch_ns_records instead

                print(f"Debug: {zone_name} - NS: {ns_record}, Master SOA: {master_dns} - {master_soa_record}, Current SOA: {ns_record} - {soa_record}")

                if soa_record != master_soa_record:
                    print(f"❌ Inconsistency detected for NS {ns_record} in zone {zone_name}")
                    print(f"   Master SOA: {master_dns} - {master_soa_record}")
                    print(f"   Current SOA: {ns_record} - {soa_record}")
                else:
                    print(f"✅ Consistency verified for NS {ns_record} in zone {zone_name}")

        print()

if __name__ == "__main__":
    # Configure the DNS master and API key
    CONFIG = {
        "master_dns": "ns1.it53.nl",
        "api_key": "YXJkQU1VVkRoSGZyV0FP"  # Replace with your actual API key
    }

    # Fetch zones
    zones = fetch_zones(CONFIG["api_key"])
        
    # Check DNS consistency
    check_dns_consistency(CONFIG["master_dns"], zones, CONFIG["api_key"])
