"""PHP's IMAP and SMTP sockets don't use HTTPS_PROXY, and the sandbox reaches nothing but the proxy.

Usage: tunnel.py <local port>=<host>:<port> ...
"""

import asyncio
import base64
import os
import sys
from urllib.parse import unquote, urlsplit


def proxy():
    url = urlsplit(os.environ["HTTPS_PROXY"])
    credentials = f"{unquote(url.username or '')}:{unquote(url.password or '')}"
    return url.hostname, url.port or 3128, base64.b64encode(credentials.encode()).decode()


async def pipe(reader, writer):
    try:
        while data := await reader.read(65536):
            writer.write(data)
            await writer.drain()
    finally:
        writer.close()


async def carry(target, client_reader, client_writer):
    try:
        host, port, credentials = proxy()
        upstream_reader, upstream_writer = await asyncio.open_connection(host, port)
        upstream_writer.write(
            f"CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n"
            f"Proxy-Authorization: Basic {credentials}\r\n\r\n".encode()
        )
        head = await upstream_reader.readuntil(b"\r\n\r\n")
    except (KeyError, ValueError, OSError, asyncio.IncompleteReadError, asyncio.LimitOverrunError) as e:
        print(f"tunnel to {target}: {e}", file=sys.stderr, flush=True)
        client_writer.close()
        return
    status = head.split(b"\r\n", 1)[0].decode(errors="replace")
    if " 200 " not in f"{status} ":
        print(f"tunnel to {target}: the proxy answered {status}", file=sys.stderr, flush=True)
        upstream_writer.close()
        client_writer.close()
        return
    await asyncio.gather(
        pipe(client_reader, upstream_writer),
        pipe(upstream_reader, client_writer),
        return_exceptions=True,
    )


async def main(routes):
    servers = []
    for route in routes:
        local, target = route.split("=", 1)
        servers.append(
            await asyncio.start_server(
                lambda r, w, target=target: carry(target, r, w), "127.0.0.1", int(local)
            )
        )
    await asyncio.gather(*(s.serve_forever() for s in servers))


if __name__ == "__main__":
    asyncio.run(main(sys.argv[1:]))
