import requests
import json
import dns.resolver
from urllib.parse import urlparse

artifactory_url = 'https://art.lmru.tech/artifactory/api/repositories'
headers = {
    'Content-Type': 'application/json'
}

def get_remote_repositories():
    response = requests.get(artifactory_url, headers=headers)
    if response.status_code == 200:
        repositories = response.json()
        excluded_package_types = ['yum', 'deb', 'rpm', 'apt', 'alpine']
        remote_repositories = [
            repo for repo in repositories 
            if repo['type'] == 'REMOTE' and repo.get('packageType', '').lower() not in excluded_package_types
        ]
        return remote_repositories
    else:
        print("Error retrieving repository list:", response.status_code, response.text)
        return []

remote_repositories = get_remote_repositories()

def extract_hostname(url):
    parsed_url = urlparse(url)
    return parsed_url.hostname

def get_ip_addresses(hostname, iterations=20):
    ip_addresses = set()
    for _ in range(iterations):
        try:
            answers = dns.resolver.resolve(hostname, 'A')
            for rdata in answers:
                ip_addresses.add(rdata.to_text())
        except dns.resolver.NoAnswer:
            print(f"No A records found for {hostname}")
        except dns.resolver.NXDOMAIN:
            print(f"Domain {hostname} does not exist")
        except dns.exception.Timeout:
            print(f"Timeout while resolving {hostname}")
        except Exception as e:
            print(f"An error occurred while resolving {hostname}: {e}")
    return ip_addresses

# Получаем уникальные IP-адреса для каждого хоста
hostnames = {extract_hostname(repo['url']) for repo in remote_repositories}
hostnames.add('docker.io')
unique_ip_addresses = set()
for hostname in hostnames:
    unique_ip_addresses.update(get_ip_addresses(hostname))

# Сохранение уникальных IP-адресов в файл
with open('blocked_ips.txt', 'w') as file:
    for ip in sorted(unique_ip_addresses):
        file.write(f"{ip}\n")

print("Blocked IP addresses list successfully created.")
