#!/usr/bin/python3.4

from docker import Client
from docker.errors import APIError
from string import Template
import json
import signal
import os
from socket import getaddrinfo

def get_if_available(dict, key, defValue):
    if key in dict:
        return dict[key]
    else:
        return defValue

def analyse_proxy_data(data):
    """Extracts the data for the proxy configuration (envrionment variable
        'PROXY_DATA' and converts it to a dictionary."""
    proxy_data = {}
    for proxy_var in data['PROXY_DATA'].split(','):
        t = proxy_var.split(":",1)
        proxy_data[t[0]] = t[1]
    return proxy_data

def analyse_env_vars(inspect_data):
    """Extracts the environment variables from the given result of an 'inspect
        container' call."""
    env_data = {}
    if not 'Env' in inspect_data['Config'] or inspect_data['Config']['Env'] is None:
        return env_data
    for env_var in inspect_data['Config']['Env']:
        t = env_var.split("=")
        env_data[t[0]] = t[1]
    return env_data

def handle_container(id):
    """This function take a container's id and collects all data required
        to create a proper proxy configuration. The configuration is then
        written to the directory of temporary nginx files"""
    inspect_data = client.inspect_container(id)
    env_vars = analyse_env_vars(inspect_data)
    if 'PROXY_DATA' in env_vars:
        proxy_data = analyse_proxy_data(env_vars)
        names = get_if_available(proxy_data, 'server_names', '').split(';')
        return names
    return []

def get_resolving_domains_from_containers(docker_client):
    container_ids = client.containers(quiet=True)
    domains = []
    for container_id in container_ids:
        domains.extend(handle_container(container_id['Id']))

    resolved_domains = []
    for domain in domains:
        try:
            getaddrinfo(domain, None)
            resolved_domains.append(domain)
        except Exception:
            pass

    return resolved_domains

if __name__ == '__main__':

    client = Client(base_url='unix://var/run/docker.sock', version='1.15')

    resolved_domains = get_resolving_domains_from_containers(client)

    print(str(resolved_domains))