#!/usr/bin/env python3
"""ottervpn sync agent: keeps wg0 peers in step with the dashboard and reports connection stats."""
import json, os, subprocess, sys, time, urllib.request, urllib.error

API = os.environ["OTTER_API"].rstrip("/")
TOKEN = os.environ["OTTER_TOKEN"]
NODE = os.environ["OTTER_NODE"]
IFACE = os.environ.get("OTTER_IFACE", "wg0")
INTERVAL = int(os.environ.get("OTTER_INTERVAL", "10"))


def call(method, path, body=None):
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(API + path, data=data, method=method, headers={
        "Authorization": "Bearer " + TOKEN, "content-type": "application/json", "user-agent": "ottervpn-agent/1"})
    with urllib.request.urlopen(req, timeout=15) as r:
        return json.loads(r.read() or b"{}")


def current_peers():
    out = subprocess.run(["wg", "show", IFACE, "dump"], capture_output=True, text=True, check=True).stdout
    peers = {}
    for line in out.strip().splitlines()[1:]:
        f = line.split("\t")
        if len(f) < 8:
            continue
        peers[f[0]] = {"allowed": f[3], "handshake": int(f[4]), "rx": int(f[5]), "tx": int(f[6])}
    return peers


def wg(*args):
    subprocess.run(["wg", "set", IFACE, *args], check=True)


def tc(*args):
    subprocess.run(["tc", *args], capture_output=True)


_limits = None


def apply_limits(limits):
    """Each device's top speed from its plan (Mbps; 0 = no limit). Download is shaped smoothly on the way
    out of wg0; upload is capped at the same rate on the way in. Rebuilt only when the limits change."""
    global _limits
    if limits == _limits:
        return
    _limits = dict(limits)
    tc("qdisc", "del", "dev", IFACE, "root")
    tc("qdisc", "del", "dev", IFACE, "ingress")
    capped = sorted((ip, r) for ip, r in limits.items() if r and r > 0)
    if not capped:
        return
    tc("qdisc", "add", "dev", IFACE, "root", "handle", "1:", "htb", "default", "9999")
    tc("class", "add", "dev", IFACE, "parent", "1:", "classid", "1:9999", "htb", "rate", "10gbit")
    tc("qdisc", "add", "dev", IFACE, "ingress")
    for i, (ip, r) in enumerate(capped):
        cid = f"1:{i + 10:x}"
        tc("class", "add", "dev", IFACE, "parent", "1:", "classid", cid, "htb", "rate", f"{r}mbit", "ceil", f"{r}mbit", "burst", "256k")
        tc("qdisc", "add", "dev", IFACE, "parent", cid, "fq_codel")
        tc("filter", "add", "dev", IFACE, "parent", "1:", "protocol", "ip", "prio", "1", "u32", "match", "ip", "dst", f"{ip}/32", "flowid", cid)
        tc("filter", "add", "dev", IFACE, "parent", "ffff:", "protocol", "ip", "prio", "1", "u32", "match", "ip", "src", f"{ip}/32",
           "police", "rate", f"{r}mbit", "burst", f"{max(64, r * 32)}k", "drop", "flowid", ":1")


def sync():
    peers = [p for p in call("GET", "/api/node/peers?id=" + NODE)["peers"] if p.get("ip")]
    desired = {p["pubkey"]: p["ip"] + "/32" for p in peers}
    try:
        apply_limits({p["ip"]: int(p.get("r") or 0) for p in peers})
    except Exception as e:  # speed limits must never stop peers syncing
        print(f"speed limits failed: {e}", file=sys.stderr, flush=True)
    have = current_peers()
    for pk in have:
        if pk not in desired:
            wg("peer", pk, "remove")
    for pk, allowed in desired.items():
        if have.get(pk, {}).get("allowed") != allowed:
            wg("peer", pk, "allowed-ips", allowed)
    have = current_peers()
    call("POST", "/api/node/report", {"id": NODE, "peers": [
        {"pubkey": k, "handshake": v["handshake"], "rx": v["rx"], "tx": v["tx"]} for k, v in have.items()]})
    return len(desired)


def main():
    last = None
    while True:
        try:
            n = sync()
            if n != last:
                print(f"in sync: {n} peers", flush=True)
                last = n
        except urllib.error.HTTPError as e:
            print(f"API error {e.code}: {e.read()[:200]!r}", file=sys.stderr, flush=True)
        except Exception as e:  # keep running through network blips
            print(f"sync failed: {e}", file=sys.stderr, flush=True)
        time.sleep(INTERVAL)


if __name__ == "__main__":
    main()
