#!/usr/bin/python3
#
# find _apt-proxy._tcp or legacy _apt_proxy._tcp providers via avahi
# and return a http proxy string suitable for apt to fetch the URI
# given as argument

import asyncio
import sys
from urllib.parse import urlsplit

TIMEOUT_SEC = 2
SERVICES = ("_apt-proxy._tcp", "_apt_proxy._tcp")
VERBOSE = "--debug" in sys.argv


def debug(msg):
    if VERBOSE:
        sys.stderr.write(msg + "\n")


async def discover(uri, timeout):
    """Return a proxy URL, DIRECT on discovery failure, or '' if URI is unsupported."""
    url = urlsplit(uri)

    # Refuse to probe for non http-URIs, and for URIs with credentials.
    if url.scheme != "http" or url.username is not None:
        return ""

    found = asyncio.get_running_loop().create_future()
    probes = {}

    # Prepare probe request. With only-if-cached, a proxy allowing access
    # answers from its cache or with 504, without contacting the origin
    # server. Squid denies access with 403.
    request = (
        f"HEAD {uri} HTTP/1.1\r\n"
        f"Host: {url.netloc}\r\n"
        "Cache-Control: only-if-cached\r\n"
        "Connection: close\r\n"
        "\r\n"
    ).encode()

    async def probe(address):
        reader, writer = await asyncio.open_connection(*address)
        try:
            writer.write(request)
            status = await reader.readline()
        finally:
            writer.close()
        debug(f"{address}: {status!r}")
        fields = status.split()
        if len(fields) < 2 or not fields[0].startswith(b"HTTP/"):
            return
        if fields[1] not in (b"403", b"407") and not found.done():
            found.set_result(address)

    async def browse(service):
        # Stale announcements can delay avahi-browse until its resolver times
        # out, so probe each address as soon as it is resolved.
        process = await asyncio.create_subprocess_exec(
            "avahi-browse",
            "--no-db-lookup",
            "--parsable",
            "--resolve",
            "--terminate",
            service,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.DEVNULL,
        )
        try:
            async for line in process.stdout:
                line = line.decode()
                debug(f" {line.rstrip()}")
                fields = line.split(";")
                if fields[0] != "=":
                    continue
                address = (fields[7], int(fields[8]))
                # Skip link-local addresses: we don't retain the interface name.
                if address in probes or address[0].startswith("fe80:"):
                    continue
                probes[address] = asyncio.create_task(probe(address))
        finally:
            if process.returncode is None:
                process.kill()
            await process.wait()

    async def exhaust():
        await asyncio.gather(*(browse(service) for service in SERVICES))
        await asyncio.gather(*probes.values(), return_exceptions=True)

    task = asyncio.create_task(exhaust())
    await asyncio.wait(
        {found, task}, timeout=timeout, return_when=asyncio.FIRST_COMPLETED
    )
    tasks = [task, *probes.values()]
    for pending in tasks:
        pending.cancel()
    await asyncio.gather(*tasks, return_exceptions=True)
    if found.done():
        ip, port = found.result()
        if ":" in ip:
            ip = f"[{ip}]"
        debug(f"selected {ip}:{port}")
        return f"http://{ip}:{port}/"
    # APT remembers DIRECT for this host until it exits, so it doesn't run
    # discovery again for each download from the host.
    return "DIRECT"


def main():
    args = [arg for arg in sys.argv[1:] if arg != "--debug"]
    if not args:
        debug("no URI given")
        return
    uri = args[0]
    print(asyncio.run(discover(uri, TIMEOUT_SEC)), end="")


if __name__ == "__main__":
    main()
