#!/usr/bin/env python3
"""Bind each DNS listener to its reply source address; never bind wildcard UDP."""
import json
import os
from pathlib import Path
import pwd
import re
import subprocess


def build(config, links):
    interfaces = []
    template = config["inbounds"][0]
    if template["listen"] != "127.0.0.1":
        raise ValueError("Host DNS must bind the loopback reply address")
    for link in links:
        name = link["ifname"]
        if not re.fullmatch(r"(?:docker0|br-[a-zA-Z0-9_-]{1,12})", name):
            continue
        addresses = [a["local"] for a in link.get("addr_info", []) if a["family"] == "inet" and a.get("scope") == "global"]
        if addresses:
            interfaces.append(name)
            config["inbounds"].append({**template, "tag": f"dns-in-{name}", "listen": addresses[0]})
    config["route"]["rules"][0]["inbound"] = [inbound["tag"] for inbound in config["inbounds"] if inbound["tag"].startswith("dns-in")]
    return config, interfaces


if __name__ == "__main__":
    config = json.loads(Path("/etc/openai-domain-router/config.json").read_text())
    links = json.loads(subprocess.run(["ip", "-j", "addr"], capture_output=True, text=True, check=True).stdout)
    config, bridges = build(config, links)
    root = Path("/run/openai-domain-router")
    group = pwd.getpwnam("openai-router").pw_gid
    root.mkdir(exist_ok=True)
    os.chown(root, 0, group)
    root.chmod(0o750)
    for name, value in (("config.json", config), ("bridges.json", bridges)):
        path = root / name
        path.write_text(json.dumps(value, indent=2) + "\n")
        os.chown(path, 0, group)
        path.chmod(0o640)
