#!/usr/bin/python3 -I
"""Wombat-Email: one DNS change asked for in the panel, applied at Cloudflare as root (installed by
installer/89-sync.sh as /usr/local/sbin/wombat-email-dns, run by wombat-email-dns.path). The panel never
has the token: it leaves /var/lib/wombat-email/requests/dns, JSON with "by" and either
  op "batch", zone, changes [{op add|edit|delete, id, type, name, content, priority, proxied}]: checked again,
     the records mail depends on refused, the zone saved first, then all of them in one Cloudflare batch
     (all or none), and that zone refreshed in cloudflare.json; or
  op "batches", zones [{zone, changes}]: the same for several zones (the panel's many-at-once actions), each
     zone on its own: one refused leaves the others; or
  op "fix", zone (a mail domain): Check and fix for that domain alone (installer/dns_records.py); or
  op "fixes", zones [mail domains]: the same for several, one after the other, each one's progress shown. The result goes to dns-status.json for the panel, and a line to /var/log/wombat-email/dns.log.

After each of those, and run as `wombat-email-dns --check` (by every installer run, 89-sync.sh, and before the
daily report): Check and fix as a dry run (dns_records.py with WE_DNS_DRY=1) for every mail domain, nothing
changed. What it would correct goes to dns-needed.json, so the panel's Check and fix buttons only ask to be
pressed when there's something to fix.
"""
import fcntl, ipaddress, json, os, re, subprocess, sys, time

sys.path.insert(0, "@WE_ROOT@/installer")
import dns_rules   # what each record is to this server: the same rules as the installer's
sys.path.insert(0, "/usr/local/lib/wombat-email")
import wombat_email as we   # what the server's scripts share

REQ = "/var/lib/wombat-email/requests/dns"
STATUS = "/var/lib/wombat-email/dns-status.json"
NEEDED = "/var/lib/wombat-email/dns-needed.json"
CFJSON = "/var/lib/wombat-email/cloudflare.json"
SNAPDIR = "/var/backups/wombat-email/dns"
LOG = "/var/log/wombat-email/dns.log"
SELECTOR = "wombat"
SNAPS_KEPT = 30          # per zone
TYPES = ("A", "AAAA", "CNAME", "MX", "TXT")   # what can be added or changed here; any type can be deleted

dns_rules.ipv4_only()   # as the installer does: the token may be limited to the server's IPv4 address


write_json = we.write_json


ZONES = None   # a many-zone change's progress, one entry per zone: {zone, state wait|now|ok|bad, note}


def status(state, message, items=()):
    """For the panel: a short line, the changes (or problems) one per line, and for a many-zone change each
    zone's progress (the panel shows it live, asking every second)."""
    out = {"state": state, "message": message, "items": list(items), "finished": int(time.time())}
    if ZONES is not None:
        out["zones"] = ZONES
    write_json(STATUS, out)


def log(line):
    os.makedirs(os.path.dirname(LOG), exist_ok=True)
    with open(LOG, "a") as f:
        f.write(time.strftime("%Y-%m-%dT%H:%M:%S%z ") + line + "\n")


def cf(method, path, data=None):
    return dns_rules.cf_call(method, path, data)


class Refused(Exception):
    pass


settings = we.settings


def mail_domains():
    """The enabled mail domains, "name:prepare" for one being prepared (as the installer passes them)."""
    return we.psql("SELECT name || CASE WHEN mail_here THEN '' ELSE ':prepare' END FROM domains WHERE enabled").split()


def check_value(rtype, content, priority, zone):
    if rtype == "A":
        try:
            ip = ipaddress.IPv4Address(content)
        except ValueError:
            raise Refused(f"{content!r} isn't an IPv4 address")
        if not ip.is_global:
            raise Refused(f"{content} is a private or reserved address")
    elif rtype == "AAAA":
        try:
            ip = ipaddress.IPv6Address(content)
        except ValueError:
            raise Refused(f"{content!r} isn't an IPv6 address")
        if not ip.is_global:
            raise Refused(f"{content} is a private or reserved address")
    elif rtype in ("CNAME", "MX"):
        if not (rtype == "MX" and content == ".") and not re.fullmatch(r"(?=.{1,253}$)([a-z0-9_]([a-z0-9_-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}", content):
            raise Refused(f"{content!r} isn't a host name")
        if rtype == "MX" and not (isinstance(priority, int) and 0 <= priority <= 65535):
            raise Refused("an MX record needs a priority from 0 to 65535")
    elif rtype == "TXT":
        if not content or len(content) > 2048 or not content.isprintable():
            raise Refused("a TXT record is printable text, up to 2048 characters")


def snapshot(zid, zname, now):
    os.makedirs(SNAPDIR, mode=0o700, exist_ok=True)
    path = os.path.join(SNAPDIR, f"{zname}-{time.strftime('%Y%m%d-%H%M%S', time.gmtime(now))}.json")
    with open(path, "w") as f:
        json.dump(cf("GET", f"zones/{zid}/dns_records?per_page=5000"), f, indent=1)
    os.chmod(path, 0o600)
    old = sorted(p for p in os.listdir(SNAPDIR) if re.fullmatch(re.escape(zname) + r"-\d{8}-\d{6}\.json", p))
    for p in old[:-SNAPS_KEPT]:
        os.remove(os.path.join(SNAPDIR, p))
    return path


def refresh(zid, zname, rules):
    """That zone's records, as Cloudflare holds them now, into cloudflare.json (the rest is left as it was)."""
    recs = [dns_rules.for_panel(rules, r) for r in cf("GET", f"zones/{zid}/dns_records?per_page=5000")]
    with open("/run/wombat-email-cloudflare.lock", "w") as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        try:
            data = json.load(open(CFJSON))
        except Exception:
            data = {"zones": []}
        for z in data.get("zones", []):
            if z.get("name") == zname:
                z["records"] = recs
        write_json(CFJSON, data)


def check_change(c, zid, zname, rules):
    """One change from the panel, checked: (kind, body, text) for Cloudflare's batch, or Refused."""
    op = c.get("op")
    if op not in ("add", "edit", "delete"):
        raise Refused("unknown change")
    old = None
    if op in ("edit", "delete"):
        rid = str(c.get("id", ""))
        if not re.fullmatch(r"[0-9a-f]{32}", rid):
            raise Refused("a change names no record")
        try:
            old = cf("GET", f"zones/{zid}/dns_records/{rid}")
        except RuntimeError:
            raise Refused("a record to change is no longer there (changed in Cloudflare meanwhile?)")
        why = rules.kept(old["type"], old["name"], old.get("content", ""))
        if why:
            raise Refused(f"{old['type']} {old['name']} is kept by this server ({why}); Check and fix keeps it right")
    if op == "delete":
        return "deletes", {"id": old["id"]}, f"{old['type']} {old['name']} {old.get('content', '')} deleted"
    rtype = old["type"] if old else str(c.get("type", ""))
    if rtype not in TYPES:
        raise Refused(f"{rtype or 'that type'} can be deleted here, not added or changed (Cloudflare can)")
    name = str(c.get("name", "")).lower().rstrip(".")
    if not (name == zname or name.endswith("." + zname)) or not re.fullmatch(r"(\*\.)?([a-z0-9_]([a-z0-9_-]{0,61}[a-z0-9])?\.)*[a-z0-9-]+\.[a-z]{2,63}", name):
        raise Refused(f"{name!r} isn't a name in {zname}")
    content = str(c.get("content", "")).strip()
    if rtype in ("CNAME", "MX"):
        content = content.lower().rstrip(".") or "."
    priority = c.get("priority")
    priority = int(priority) if rtype == "MX" and str(priority).isdigit() else None
    check_value(rtype, content, priority, zname)
    if rtype == "TXT":
        content = dns_rules.txt_text(content) if content.startswith('"') else content
    why = rules.kept(rtype, name, content)
    if why:
        raise Refused(f"{rtype} {name} is kept by this server ({why}); Check and fix keeps it right")
    problem = dns_rules.edit_problem(rules, rtype, name, content)
    if problem:
        raise Refused(problem)
    body = {"type": rtype, "name": name, "content": dns_rules.txt_content(content) if rtype == "TXT" else content, "ttl": 1,
            "proxied": bool(c.get("proxied")) if rtype in ("A", "AAAA", "CNAME") else False}
    if priority is not None:
        body["priority"] = priority
    if old:
        body["id"] = old["id"]
        before = dns_rules.txt_text(old.get("content")) if rtype == "TXT" else old.get("content", "")
        text = f"{rtype} {name}: {before} → {content}"
        if old.get("proxied") != body["proxied"] and rtype in ("A", "AAAA", "CNAME"):
            text += ", proxied" if body["proxied"] else ", DNS only"
        return "patches", body, text
    return "posts", body, f"{rtype} {name} added: {content}" + (" (proxied)" if body["proxied"] else "")


def zone_id(zname):
    if not re.fullmatch(r"[a-z0-9.-]+\.[a-z]{2,63}", zname):
        raise Refused("no zone named")
    found = cf("GET", f"zones?name={zname}")
    if not found:
        raise Refused(f"the Cloudflare token can't see {zname}")
    return found[0]["id"]


def read_zones(req, rules):
    """Zones the owner added on the DNS page: their records and DNSSEC into cloudflare.json (read only)."""
    names = req.get("zones")
    if not isinstance(names, list) or not names or len(names) > 500:
        raise Refused("no zones, or more than 500")
    got = []
    for zname in sorted({str(n).lower() for n in names}):
        zid = zone_id(zname)
        state = cf("GET", f"zones/{zid}/dnssec")
        got.append({"name": zname, "role": [], "dnssec": state.get("status", "?"), "ds": (state.get("ds") or "").strip(),
                    "records": [dns_rules.for_panel(rules, r) for r in cf("GET", f"zones/{zid}/dns_records?per_page=5000")]})
    with open("/run/wombat-email-cloudflare.lock", "w") as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        try:
            data = json.load(open(CFJSON))
        except Exception:
            data = {"zones": []}
        mine = {z["name"] for z in got}
        data["zones"] = sorted([z for z in data.get("zones", []) if z.get("name") not in mine] + got, key=lambda z: z["name"])
        write_json(CFJSON, data)
    return (f"{len(got)} domain{'s' if len(got) != 1 else ''} added from Cloudflare", []), "nothing changed"


def protect_zones(req, rules):
    """The "sends no mail" set at each zone's own name, where missing: a null MX, v=spf1 -all and a DMARC
    reject policy. Never on this server's mail domains, nor on a name with mail of its own (an MX to a server,
    an SPF that lets someone send, a CNAME). Each zone saved first, then one batch per zone."""
    names = req.get("zones")
    if not isinstance(names, list) or not names or len(names) > 500:
        raise Refused("no zones, or more than 500")
    mine = {d.split(":")[0] for d in rules.domains} | {rules.hostname} | {rules.hostname.split(".", 1)[1]}   # the hostname may be a bare domain
    done, snaps = [], 0
    for zname in sorted({str(n).lower() for n in names} - mine):
        zid = zone_id(zname)
        recs = cf("GET", f"zones/{zid}/dns_records?per_page=5000")
        at = [r for r in recs if r["name"].lower() == zname]
        text = lambda r: dns_rules.txt_text(r.get("content")).strip()
        if any(r["type"] == "CNAME" or (r["type"] == "MX" and (r.get("content") or "").rstrip(".") not in ("", "."))
               or (r["type"] == "TXT" and re.match(r"(?i)v=spf1\b", text(r)) and not re.fullmatch(r"(?i)v=spf1\s+-all", text(r))) for r in at):
            done.append(f"{zname}: has mail of its own, left as it is")
            continue
        posts = []
        if not any(r["type"] == "MX" for r in at):
            posts.append({"type": "MX", "name": zname, "content": ".", "priority": 0, "ttl": 1})
        if not any(r["type"] == "TXT" and re.match(r"(?i)v=spf1\b", text(r)) for r in at):
            posts.append({"type": "TXT", "name": zname, "content": dns_rules.txt_content("v=spf1 -all"), "ttl": 1})
        if not any(r["type"] == "TXT" and r["name"].lower() == f"_dmarc.{zname}" for r in recs):
            posts.append({"type": "TXT", "name": f"_dmarc.{zname}", "content": dns_rules.txt_content("v=DMARC1; p=reject;"), "ttl": 1})
        if not posts:
            continue
        snapshot(zid, zname, time.time())
        snaps += 1
        cf("POST", f"zones/{zid}/dns_records/batch", {"posts": posts})
        refresh(zid, zname, rules)
        done.append(f"{zname}: added " + ", ".join("MX ." if p["type"] == "MX" else ("SPF" if p["name"] == zname else "DMARC") for p in posts))
    added = sum(1 for d in done if ": added " in d)
    return (f"{added} domain{'s' if added != 1 else ''} now say{'s' if added == 1 else ''} they send no mail", done), f"{snaps} zones saved first"


def apply_batch(req, rules):
    """The changes for one zone, all at once: Cloudflare runs them in one transaction (deletes, then changes,
    then additions), so either all of them happen or none do."""
    zname = str(req.get("zone", "")).lower()
    zid = zone_id(zname)
    changes = req.get("changes")
    if not isinstance(changes, list) or not changes or len(changes) > 100:
        raise Refused("no changes, or more than 100 at once")
    batch, done = {"deletes": [], "patches": [], "posts": []}, []
    for c in changes:
        kind, body, text = check_change(c if isinstance(c, dict) else {}, zid, zname, rules)
        batch[kind].append(body)
        done.append(text)
    snap = snapshot(zid, zname, time.time())
    cf("POST", f"zones/{zid}/dns_records/batch", {k: v for k, v in batch.items() if v})
    refresh(zid, zname, rules)
    return (f"{len(done)} change{'s' if len(done) != 1 else ''} made in {zname}", done), snap


def apply_batches(req, rules):
    """Several zones' changes (a many-at-once action, like DMARC for several domains): each zone checked, saved
    first and changed in its own batch, all or none for that zone. A zone refused doesn't stop the others; it's
    listed first, with why."""
    zones = req.get("zones")
    if not isinstance(zones, list) or not zones or len(zones) > 500:
        raise Refused("no zones, or more than 500")
    global ZONES
    ZONES = [{"zone": str(z.get("zone", "")).lower() if isinstance(z, dict) else "?", "state": "wait", "note": ""} for z in zones]
    status("running", "")
    done, bad, made = [], [], 0
    for z, prog in zip(zones, ZONES):
        zname = prog["zone"]
        prog["state"] = "now"
        status("running", "")
        try:
            (_, items), _ = apply_batch({"zone": zname, "changes": z.get("changes") if isinstance(z, dict) else None}, rules)
            done += items
            made += 1
            prog.update(state="ok", note=f"{len(items)} change{'s' if len(items) != 1 else ''}")
        except Refused as e:
            bad.append(f"{zname}: not changed: {e}")
            prog.update(state="bad", note=str(e))
        except Exception as e:
            bad.append(f"{zname}: not changed: Cloudflare: {e}")
            prog.update(state="bad", note=f"Cloudflare: {e}")
        status("running", "")
    if not made:
        raise Refused("; ".join(bad))
    head = f"{made} zone{'s' if made != 1 else ''} changed" + (f", {len(bad)} not (below)" if bad else "")
    return (head, bad + done), f"{made} zones saved first"


def fix_domain(req, hostname):
    """Check and fix for one mail domain: installer/dns_records.py for it alone (and the mail hostname,
    which it always looks at), its zone merged into cloudflare.json."""
    dom = str(req.get("zone", "")).lower()
    out = mail_domains()
    arg = next((d for d in out if d.split(":")[0] == dom), None)
    if arg is None and not hostname.endswith("." + dom):
        raise Refused(f"{dom} isn't a mail domain on this server")
    ip = we.server_ip()
    sts = we.mta_sts_id(hostname)
    backup = os.path.join(SNAPDIR, f"fix-{time.strftime('%Y%m%d-%H%M%S', time.gmtime())}")
    run = subprocess.run(["python3", "-I", "@WE_ROOT@/installer/dns_records.py", hostname, ip, backup, "/var/lib/rspamd/dkim",
                          SELECTOR, sts] + ([arg] if arg else []),
                         capture_output=True, text=True, env={**os.environ, "WE_DNS_MERGE": "1", "WE_DNS_ALL": " ".join(out)}, timeout=600)
    lines = run.stdout.splitlines()
    changed = [l[8:] for l in lines if l.startswith("CHANGED ")]
    waiting = [l[5:] for l in lines if l.startswith("WAIT ")]
    if run.returncode != 0:
        raise RuntimeError((run.stderr.strip().splitlines() or ["dns_records.py failed"])[-1])
    head = f"{dom}: {len(changed)} record{'s' if len(changed) != 1 else ''} corrected" if changed else f"{dom}: every record mail needs is right"
    return (head, changed + ["waiting: " + w for w in waiting]), backup if changed else "nothing changed"


def fix_domains(req, hostname):
    """Check and fix for several mail domains (the DNS page's ticked zones), one at a time: each its own run of
    fix_domain, its progress in ZONES. One that fails doesn't stop the others; it's listed first, with why."""
    names = req.get("zones")
    if not isinstance(names, list) or not names or len(names) > 500:
        raise Refused("no domains, or more than 500")
    global ZONES
    ZONES = [{"zone": str(n).lower(), "state": "wait", "note": ""} for n in dict.fromkeys(names)]
    status("running", "")
    done, bad, fixed, ok = [], [], 0, 0
    for prog in ZONES:
        prog["state"] = "now"
        status("running", "")
        try:
            (head, items), _ = fix_domain({"zone": prog["zone"]}, hostname)
            changed = [i for i in items if not i.startswith("waiting: ")]
            done += items
            ok += 1
            fixed += 1 if changed else 0
            prog.update(state="ok", note=f"{len(changed)} corrected" if changed else "all right")
        except Refused as e:
            bad.append(f"{prog['zone']}: not changed: {e}")
            prog.update(state="bad", note=str(e))
        except Exception as e:
            bad.append(f"{prog['zone']}: not changed: {e}")
            prog.update(state="bad", note=str(e))
        status("running", "")
    if not ok:
        raise Refused("; ".join(bad))
    head = f"{ok} domain{'s' if ok != 1 else ''} checked, {fixed} corrected" + (f", {len(bad)} not (below)" if bad else "")
    return (head, bad + done), f"{fixed} domains saved first" if fixed else "nothing changed"


def check():
    """Would Check and fix change anything? The installer's own rules, as a dry run for the mail hostname and
    every enabled mail domain; the answer, per zone, in dns-needed.json ("items": [{zone, text}]). On a failure
    the file says so ("failed"), and the panel treats it as not known."""
    try:
        hostname = settings().get("HOSTNAME", "").lower()
        doms = mail_domains()
        host_zone = next((z["name"] for z in json.load(open(CFJSON)).get("zones", []) if "the mail hostname" in z.get("role", [])), "")
        args = list(dict.fromkeys(([host_zone] if host_zone and host_zone not in [d.split(":")[0] for d in doms] else []) + doms))
        sts = we.mta_sts_id(hostname)
        run = subprocess.run(["python3", "-I", "@WE_ROOT@/installer/dns_records.py", hostname, we.server_ip(), "/nonexistent", "/var/lib/rspamd/dkim",
                              SELECTOR, sts] + args, capture_output=True, text=True, env={**os.environ, "WE_DNS_DRY": "1"}, timeout=600)
        if run.returncode != 0:
            raise RuntimeError((run.stderr.strip().splitlines() or ["dns_records.py failed"])[-1])
        items = [dict(zip(("zone", "text"), l[6:].split("\t", 1))) for l in run.stdout.splitlines() if l.startswith("WOULD ") and "\t" in l]
        write_json(NEEDED, {"checked": int(time.time()), "state": "ok", "items": items})
    except Exception as e:
        write_json(NEEDED, {"checked": int(time.time()), "state": "failed", "message": str(e)[:300], "items": []})


def main():
    if not os.path.isfile(REQ) or os.path.islink(REQ):
        return
    try:
        raw = open(REQ).read(1000000)   # a many-at-once action can be long
    finally:
        os.remove(REQ)
    try:
        req = json.loads(raw)
        if not isinstance(req, dict):
            raise ValueError
    except ValueError:
        status("failed", "the panel's request couldn't be read")
        return
    by = str(req.get("by", ""))[:200]
    status("running", "")
    try:
        hostname = settings().get("HOSTNAME", "").lower()
        rules = dns_rules.Rules(hostname, mail_domains(), SELECTOR, we.server_ip(), dns_rules.web_addresses())
        if req.get("op") == "batch":
            done, snap = apply_batch(req, rules)
        elif req.get("op") == "batches":
            done, snap = apply_batches(req, rules)
        elif req.get("op") == "fix":
            done, snap = fix_domain(req, hostname)
        elif req.get("op") == "fixes":
            done, snap = fix_domains(req, hostname)
        elif req.get("op") == "protect":
            done, snap = protect_zones(req, rules)
        elif req.get("op") == "read":
            done, snap = read_zones(req, rules)
        else:
            raise Refused("unknown request")
    except Refused as e:
        status("failed", str(e))
        log(f"{by}: refused: {e}")
        return
    except Exception as e:
        status("failed", f"Cloudflare: {e}")
        log(f"{by}: failed: {e}")
        return
    head, items = done
    status("ok", head, items)
    log(f"{by}: {head}: {'; '.join(items)} (zone saved first: {snap})")
    if req.get("op") != "read":
        check()   # after a change: does Check and fix still have anything to do?


if sys.argv[1:] == ["--check"]:
    check()
else:
    main()
