from ipaddress import ip_address, IPv4Address 
from kubernetes import client, config
import boto3
import time
import os

HOSTED_ZONE=os.environ['HOSTED_ZONE'] 
COTURN_DOMAIN_NAME=os.environ['COTURN_DOMAIN_NAME'] 

config.load_incluster_config()
v1 = client.CoreV1Api()

  
def validIPAddress(IP: str) -> str: 
    try: 
        return "IPv4" if type(ip_address(IP)) is IPv4Address else "IPv6"
    except ValueError: 
        return "Invalid"

while(True):
    ips_set = set()

    pods = v1.list_namespaced_pod(namespace="coturn", label_selector="app=coturn")

    for i in pods.items:
        if not i.spec.node_name:
            continue
        node_status = v1.read_node(name=i.spec.node_name)
        for adr in node_status.status.addresses:
            # only collect IPv4 addresses, because we are only updating A records here
            if adr.type=="ExternalIP" and validIPAddress(adr.address) == "IPv4":
                ips_set.add(adr.address)

    ips = [{'Value': ip} for ip in sorted(list(ips_set))]
    print("Node IPs: "+str(ips))

    if not ips:
        print("No IPs found to update. Sleeping.")
        time.sleep(60)
        continue

    client = boto3.client('route53')
    try:
        response = client.change_resource_record_sets(
                HostedZoneId=HOSTED_ZONE,
                ChangeBatch= {
                                'Comment': 'COTURN NODES',
                                'Changes': [
                                    {
                                    'Action': 'UPSERT',
                                    'ResourceRecordSet': {
                                        'Name': COTURN_DOMAIN_NAME,
                                        'Type': 'A',
                                        'TTL': 300,
                                        'ResourceRecords': ips
                                    }
                                }]
                })
        print("Successfully updated Route53: " + str(response['ChangeInfo']['Id']))
    except Exception as e:
        print(f"Error updating Route53: {e}")

    time.sleep(60)