#!/usr/bin/env python3
"""Manage only the additive OpenAI router's own nftables tables/IPv6 route."""
import argparse
import ipaddress
import json
from pathlib import Path
import pwd
import re
import socket
import struct
import subprocess
import time

DNS_TABLE = "openai_domain_dns"
TRAFFIC_TABLE = "openai_domain_traffic"
TABLES = (DNS_TABLE, TRAFFIC_TABLE)
MARKER = "Managed by openai-domain-router"
RESOLVER = "192.168.35.1"
FAKE4 = "198.19.0.0/16"
FAKE6 = "fd74:6f70:656e::/48"
ROUTE_PROTO = 186
ROUTE_METRIC = 42760


def run(*args, **kwargs):
    return subprocess.run(args, check=True, capture_output=True, text=True, **kwargs)


def table_exists(table):
    result = subprocess.run(["nft", "list", "table", "inet", table], capture_output=True, text=True)
    if result.returncode:
        if "No such file or directory" in result.stderr:
            return False
        raise RuntimeError("Cannot inspect the managed nftables table")
    # nft 1.0.6 omits table comments in JSON, but retains them in native output.
    if f'comment "{MARKER}"' not in result.stdout.split("chain ", 1)[0]:
        raise RuntimeError("Table name is already owned by another configuration; unchanged")
    return True


def render(uid, bridges=()):
    if not isinstance(uid, int) or uid <= 0:
        raise ValueError("A dedicated non-root service UID is required")
    if any(not re.fullmatch(r"(?:docker0|br-[a-zA-Z0-9_-]{1,12})", interface) for interface in bridges):
        raise ValueError("Unexpected bridge interface name")
    dns_bridges = "\n".join(
        f'  iifname "{interface}" ip daddr {RESOLVER} {protocol} dport 53 counter redirect to :15353'
        for interface in bridges for protocol in ("tcp", "udp"))
    return f'''
table inet {DNS_TABLE} {{
 comment "{MARKER}"
 chain output {{
  type nat hook output priority -110; policy accept;
  meta skuid != {uid} ip daddr {RESOLVER} udp dport 53 counter redirect to :15353
  meta skuid != {uid} ip daddr {RESOLVER} tcp dport 53 counter redirect to :15353
 }}
 chain prerouting {{
  type nat hook prerouting priority -110; policy accept;
{dns_bridges}
 }}
}}
table inet {TRAFFIC_TABLE} {{
 comment "{MARKER}"
 chain output {{
  type nat hook output priority -110; policy accept;
  ip daddr {FAKE4} meta l4proto tcp counter redirect to :18083
  ip6 daddr {FAKE6} meta l4proto tcp counter redirect to :18084
 }}
 chain prerouting {{
  type nat hook prerouting priority -110; policy accept;
  iifname "docker0" ip daddr {FAKE4} meta l4proto tcp counter redirect to :18083
  iifname "br-*" ip daddr {FAKE4} meta l4proto tcp counter redirect to :18083
  iifname "docker0" ip6 daddr {FAKE6} meta l4proto tcp counter redirect to :18084
  iifname "br-*" ip6 daddr {FAKE6} meta l4proto tcp counter redirect to :18084
 }}
 chain output_udp {{
  type filter hook output priority -10; policy accept;
  ip daddr {FAKE4} meta l4proto udp counter reject with icmpx type port-unreachable
  ip6 daddr {FAKE6} meta l4proto udp counter reject with icmpx type port-unreachable
 }}
 chain forward_udp {{
  type filter hook forward priority -10; policy accept;
  ip daddr {FAKE4} meta l4proto udp counter reject with icmpx type port-unreachable
  ip6 daddr {FAKE6} meta l4proto udp counter reject with icmpx type port-unreachable
 }}
 chain input_guard {{
  type filter hook input priority -10; policy accept;
  iifname "lo" tcp dport {{ 15353, 18083, 18084 }} accept
  iifname "lo" udp dport 15353 accept
  iifname "docker0" tcp dport {{ 15353, 18083, 18084 }} accept
  iifname "docker0" udp dport 15353 accept
  iifname "br-*" tcp dport {{ 15353, 18083, 18084 }} accept
  iifname "br-*" udp dport 15353 accept
  tcp dport {{ 15353, 18083, 18084 }} counter drop
  udp dport 15353 counter drop
 }}
}}
'''


def ipv6_routes():
    return json.loads(run("ip", "-N", "-j", "-6", "route", "show", "exact", FAKE6).stdout)


def owned_route(route):
    return (route.get("dev") == "lo" and str(route.get("protocol")) == str(ROUTE_PROTO)
            and route.get("metric") == ROUTE_METRIC)


def probe():
    # Check an actual synthetic DNS reply before installing any interception.
    wire = struct.pack("!HHHHHH", 7361, 256, 1, 0, 0, 0) + b"\x07chatgpt\x03com\0\0\1\0\1"
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as client:
        client.settimeout(3)
        client.sendto(wire, ("127.0.0.1", 15353))
        reply, _ = client.recvfrom(4096)
    if reply[:2] != wire[:2] or struct.unpack("!H", reply[6:8])[0] != 1:
        raise RuntimeError("Dedicated DNS probe failed; network unchanged")
    if ipaddress.ip_address(reply[-4:]) not in ipaddress.ip_network(FAKE4):
        raise RuntimeError("DNS did not return the reserved synthetic address")
    # Connecting directly to a redirect listener has no original NAT target
    # and produces a spurious service error. Inspect its listening socket.
    for port in (18083, 18084):
        if not run("ss", "-H", "-lnt", f"sport = :{port}").stdout.strip():
            raise RuntimeError("Transparent listener is not ready")
    with socket.create_connection(("127.0.0.1", 1081), timeout=3):
        pass


def apply():
    uid = pwd.getpwnam("openai-router").pw_uid
    deadline = time.monotonic() + 8
    while True:
        try:
            probe()
            break
        except (OSError, RuntimeError):
            if time.monotonic() >= deadline:
                raise
            time.sleep(0.1)
    routes = ipv6_routes()
    if any(not owned_route(route) for route in routes):
        raise RuntimeError("IPv6 range already in use; network unchanged")
    previous = [table for table in TABLES if table_exists(table)]
    bridges = json.loads(Path("/run/openai-domain-router/bridges.json").read_text())
    body = "".join(f"delete table inet {table}\n" for table in previous) + render(uid, bridges)
    run("nft", "--check", "-f", "-", input=body)
    created_route = not routes
    if created_route:
        run("ip", "-6", "route", "add", FAKE6, "dev", "lo", "proto", str(ROUTE_PROTO),
            "metric", str(ROUTE_METRIC))
    try:
        run("nft", "-f", "-", input=body)
    except BaseException:
        if created_route:
            remove_route()
        raise


def remove_route():
    routes = ipv6_routes()
    for route in routes:
        if owned_route(route):
            run("ip", "-6", "route", "del", FAKE6, "dev", "lo", "proto", str(ROUTE_PROTO),
                "metric", str(ROUTE_METRIC))


def remove(dns_only=False):
    names = (DNS_TABLE,) if dns_only else TABLES
    # Preflight all ownership checks before deleting anything. Never flush a
    # global ruleset, restore an old firewall snapshot, or touch Docker tables.
    present = [name for name in names if table_exists(name)]
    if present:
        run("nft", "-f", "-", input="".join(f"delete table inet {name}\n" for name in present))
    if not dns_only:
        remove_route()


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("action", choices=("apply", "remove", "dns-off", "render", "probe"))
    parser.add_argument("--uid", type=int)
    args = parser.parse_args()
    if args.action == "render":
        print(render(args.uid or pwd.getpwnam("openai-router").pw_uid))
    elif args.action == "apply":
        apply()
    elif args.action == "probe":
        probe()
    else:
        remove(dns_only=args.action == "dns-off")


if __name__ == "__main__":
    main()
