#!/usr/bin/python
#
# use avahi to find a _apt_proxy._tcp provider and return
# a http proxy string suitable for apt

import socket
from subprocess	import Popen, PIPE


def is_ipv6(a):
    return ':' in a

def is_linklocal(addr):
    # Link-local should start with fe80 and six null bytes
    return addr.startswith("fe80::")

def get_proxy_host_port_from_avahi():
    service = '_apt_proxy._tcp'

    # Obtain all of the services addresses from avahi, pulling the IPv6
    # addresses to the top.
    addr4 = []
    addr6 = []
    p = Popen(['avahi-browse', '-kprt', service], stdout=PIPE)
    for line in p.stdout:
        if line.startswith('='):
            tokens = line.split(';')
            addr = tokens[7]
            port = tokens[8]
            if is_ipv6(addr):
                # We need to skip ipv6 link-local addresses since 
                # APT can't use them
                if not is_linklocal(addr):
                    addr6.append((addr, port))
            else:
                addr4.append((addr, port))

    # Run through the offered addresses and see if we we have a bound local
    # address for it.
    for (ip, port) in addr6 + addr4:
        try:
            res = socket.getaddrinfo(ip, port, 0, 0, 0, socket.AI_ADDRCONFIG)
            if res:
                return (ip, port)
        except socket.gaierror:
            pass
    # nothing found
    return None


if __name__ == "__main__":
    # Dump the approved address out in an appropriate format.
    address = get_proxy_host_port_from_avahi()
    if address:
        (ip, port) = address
        if is_ipv6(ip):
            print "http://[%s]:%s/" % (ip, port)
        else:
            print "http://%s:%s/" % (ip, port)
