#!/usr/bin/python3 -I
"""NOQ Purser: the page on the phone. Runs only while the maintenance switch is on
(purser-maint starts and stops it), over HTTPS with a certificate the box made for itself.

It reads the box's own state files and the hardware; it never reads backup data. Every action
asks for the 12-digit operation code, which the core checks (shared attempt counter and lock).
Distribution Python only: http.server + ssl, no framework, no external resources.
"""
import glob, http.server, json, os, re, shlex, socket, ssl, subprocess, sys, threading, time

LIB = os.environ.get("PURSER_LIB", "/usr/local/lib/purser")
CONF = os.environ.get("PURSER_CONF", "/etc/purser/purser.conf")
STATE = os.environ.get("STATE", "/var/lib/purser")
RUN_DIR = os.environ.get("RUN_DIR", "/run/purser")
UI_DIR = os.environ.get("PURSER_UI_DIR", "/etc/purser/ui")
PAGE = os.environ.get("PURSER_UI_PAGE", os.path.join(LIB, "ui", "index.html"))
PURSER = os.environ.get("PURSER_BIN", "/usr/local/sbin/purser")
PORT = int(os.environ.get("PURSER_UI_PORT", "443"))
NET_ROUTE = os.environ.get("PURSER_NET_ROUTE", "/proc/net/route")
NET_DIR = os.environ.get("PURSER_NET_DIR", "/sys/class/net")
ID_RE = re.compile(r"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}-[0-9]{2}Z$")
LIGHTS = {"ready", "unpaired", "pulling", "checking", "done", "warning", "fault", "suspect", "locked", "maint", "test", "fault-disk", "fault-server", "fault-verify", "warning-clock"}


def read(path, default=""):
    try:
        with open(path, encoding="utf-8", errors="replace") as f:
            return f.read().strip()
    except OSError:
        return default


def kv(path):
    """key=value files: state files and the sourced purser.conf (quotes, trailing # comments)."""
    out = {}
    for line in read(path).splitlines():
        line = line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        k, v = line.split("=", 1)
        try:
            parts = shlex.split(v, comments=True)
        except ValueError:
            parts = [v]
        out[k.strip()] = parts[0] if parts else ""
    return out


def conf():
    c = kv(CONF)
    c.setdefault("LANG_UI", "en")
    return c


def run(*cmd, data=None, timeout=60):
    try:
        r = subprocess.run(list(cmd), input=data, capture_output=True, text=True, timeout=timeout)
        return r.returncode, (r.stdout + r.stderr).strip()
    except (OSError, subprocess.TimeoutExpired) as e:
        return 99, str(e)


def box_id():
    return read("/etc/purser/id", "") or "····"


def version():
    return read(os.path.join(LIB, "version"), "") or "1.0.0"


_hw = {"t": 0.0, "v": {}}


def hardware():
    if time.time() - _hw["t"] < 20:
        return _hw["v"]
    d = {"model": None, "size": None, "temp": None, "health": None, "link": None}
    rc, out = run("smartctl", "-d", "sat", "-i", "-H", "-A", "/dev/sda", timeout=15)
    for line in out.splitlines():
        if line.startswith("Device Model:"):
            v = line.split(":", 1)[1].strip()
            d["model"] = None if v.startswith("[") else v   # a bridge that cannot pass ATA IDENTIFY says "[No Information Found]"
        elif line.startswith("User Capacity:") and "[" in line:
            d["size"] = line.split("[")[1].rstrip("]").strip()
        elif "overall-health" in line:
            d["health"] = "PASSED" in line
        elif "Temperature_Celsius" in line:
            try:
                d["temp"] = int(line.split()[9])
            except (IndexError, ValueError):
                pass
    rc, out = run("lsusb", "-t", timeout=5)
    for line in out.splitlines():
        if "Mass Storage" in line:
            d["link"] = line.rsplit(",", 1)[-1].strip()
    # the disk is there even when SMART cannot read it; size from the kernel
    d["present"] = os.path.exists("/sys/class/block/sda")
    try:
        d["size_b"] = int(read("/sys/class/block/sda/size", "0")) * 512 or None
    except ValueError:
        d["size_b"] = None
    # kernel log since boot: drops off USB, and a device that is plugged in but does not answer (enumeration fails)
    rc, out = run("journalctl", "-k", "-b", "0", "-o", "cat", "--no-pager", timeout=10)
    lines = out.splitlines() if rc == 0 else []
    d["drops"] = sum(1 for line in lines if "USB disconnect" in line)
    last_new = max((i for i, line in enumerate(lines) if " new " in line and "USB device" in line), default=-1)
    d["no_answer"] = any("unable to enumerate" in line or "not accepting address" in line for line in lines[last_new + 1:])
    try:
        board = round(int(read("/sys/class/thermal/thermal_zone0/temp", "0")) / 1000)
    except ValueError:
        board = None
    _hw.update(t=time.time(), v={"disk": d, "board_temp": board})
    return _hw["v"]


NUM_RE = re.compile(r"^[0-9]{1,18}$")
SIGNED_RE = re.compile(r"^-?[0-9]{1,18}$")
REASON_RE = re.compile(r"^[a-z_]{1,40}(/[A-Za-z0-9._+-]{1,64}){0,2}$")
STALE_RE = re.compile(r"^([A-Za-z0-9._+-]{1,64})/([0-9]{1,6})$")
# key in the state file -> (key on the page, check)
FIELDS = {
    "toplam": ("total", NUM_RE), "toplam_dosya": ("files", NUM_RE), "eklenen": ("added", NUM_RE),
    "silinen": ("deleted", NUM_RE), "degisen": ("changed", NUM_RE), "fark": ("delta", SIGNED_RE),
    "geri": ("read_files", NUM_RE), "sure": ("seconds", NUM_RE),
}
ENUMS = {"hukum": ("verdict", {"tamam": "ok", "uyari": "warning", "supheli": "suspect"}),
         "taze": ("fresh", {"yes": True, "no": False}),
         "sunucu": ("server_check", {"yes": "yes", "no": "no", "unknown": "unknown"}),
         "kaynak": ("summary", {"gece": "night", "sonradan": "later"})}
FLAGS = {"temiz": "cleared", "pin": "pinned", "aylik": "monthly"}
GOOD_HOW = {"tatbikat": "drill", "elle": "hand"}
GOOD_RES_RE = re.compile(r"^([A-Za-z0-9._+-]{1,64}):([a-z_]{1,20})$")


def acks():
    """Acks the server took (state file "onaylar": "<id> <verdict> <epoch>") and the one still waiting."""
    sent = {}
    for line in read(os.path.join(STATE, "onaylar")).splitlines():
        p = line.split()
        if len(p) == 3 and ID_RE.match(p[0]) and p[2].isdigit():
            sent[p[0]] = int(p[2])
    p = read(os.path.join(STATE, "bekleyen-ack")).split()
    pending = p[0] if p and ID_RE.match(p[0]) else None
    return sent, pending


def generations():
    """Published generations (state file "nesiller", written by the core while the disk is open),
    oldest first. A daily generation that also has a long-retention copy is listed once, with long=True.
    Only counts, codes and source names reach the page; every value is checked against a fixed form."""
    rows = {}
    for line in read(os.path.join(STATE, "nesiller")).splitlines():
        p = line.split()
        if len(p) < 3 or not ID_RE.match(p[0]) or not p[2].isdigit() or p[1] not in ("gunluk", "uzun"):
            continue
        r = rows.setdefault(p[0], {"id": p[0], "bytes": int(p[2]), "warn": [], "suspect": [], "stale": []})
        r["long" if p[1] == "uzun" else "daily"] = True
        for kv_ in p[3:200]:
            k, _, v = kv_.partition("=")
            if k in FIELDS and FIELDS[k][1].match(v):
                r[FIELDS[k][0]] = int(v)
            elif k in ENUMS and v in ENUMS[k][1]:
                r[ENUMS[k][0]] = ENUMS[k][1][v]
            elif k in FLAGS and v == "1":
                r[FLAGS[k]] = True
            elif k == "onceki" and ID_RE.match(v):
                r["prev"] = v
            elif k in ("uyari", "suphe") and REASON_RE.match(v):
                lst = r["warn" if k == "uyari" else "suspect"]
                if v not in lst and len(lst) < 20:
                    lst.append(v)
            elif k == "iyi" and v in GOOD_HOW:
                r.setdefault("good", {})["how"] = GOOD_HOW[v]
            elif k == "iyi_at" and NUM_RE.match(v):
                r.setdefault("good", {})["at"] = int(v)
            elif k == "iyi_sabit" and v == "1":
                r.setdefault("good", {})["kept"] = True
            elif k == "iyi_kaynak":
                res = [GOOD_RES_RE.match(x) for x in v.split(",")[:16]]
                if all(res):
                    r.setdefault("good", {})["sources"] = [{"name": m.group(1), "result": m.group(2)} for m in res]
            elif k == "bayat":
                m = STALE_RE.match(v)
                if m and len(r["stale"]) < 20:
                    r["stale"].append({"name": m.group(1), "h": int(m.group(2))})
    for r in rows.values():                     # a mark without its kind is not shown
        if "good" in r and "how" not in r["good"]:
            del r["good"]
    sent, pending = acks()
    first = min(sent) if sent else None
    for i, r in rows.items():
        if i in sent:
            r["ack"] = {"state": "sent", "at": sent[i]}
        elif i == pending:
            r["ack"] = {"state": "pending"}
        elif first and i >= first:              # published after acks were first recorded, never taken
            r["ack"] = {"state": "missing"}
    return [rows[k] for k in sorted(rows)][-200:]


def drill(c):
    """The newest restore drill (state file "tatbikat", written while the disk is open) and the reminder:
    due once DRILL_MAX_DAYS passed since it, or since the first generation when there was none."""
    d = kv(os.path.join(STATE, "tatbikat"))
    at = int(d["at"]) if NUM_RE.match(d.get("at", "")) else None
    first = int(d["ilk"]) if NUM_RE.match(d.get("ilk", "")) else None
    gid = d.get("id") if ID_RE.match(d.get("id", "")) else None
    try:
        max_days = int(c.get("DRILL_MAX_DAYS", "90") or 90)
    except ValueError:
        max_days = 90
    ref = at if at and gid else first
    days = max(0, int((time.time() - ref) // 86400)) if ref else None
    return {"at": at if gid else None, "id": gid, "days": days, "max_days": max_days,
            "due": days is not None and days >= max_days, "never": not (at and gid)}


def disk_usage(c):
    """Used / total bytes of the backup disk. While the disk is open and mounted: measured now
    (statvfs, the same numbers as df); otherwise the last value the core recorded (disk.usage)."""
    mnt = c.get("MNT") or "/srv/purser"
    try:
        if os.path.ismount(mnt):          # not mounted: statvfs would measure the SD card
            st = os.statvfs(mnt)
            if st.f_blocks > 0:
                return {"used": (st.f_blocks - st.f_bfree) * st.f_frsize, "total": st.f_blocks * st.f_frsize,
                        "live": True, "at": int(time.time())}
    except OSError:
        pass
    rec = kv(os.path.join(STATE, "disk.usage"))
    if not (rec.get("total", "").isdigit() and rec.get("used", "").isdigit()):
        return None
    return {"used": int(rec["used"]), "total": int(rec["total"]), "live": False,
            "at": int(rec["at"]) if rec.get("at", "").isdigit() else None}


# The transfer card. Sampled only when the page asks (no thread): with the page closed nothing is
# measured. Per sample: /proc/net/route (default-route interface) and one rx_bytes counter.
WINDOW_S, AVG_S, MIN_STEP_S, GAP_S = 120, 10, 1.0, 30
IFACE_RE = re.compile(r"^[A-Za-z0-9_.:@-]{1,15}$")
_tr = {"lock": threading.Lock(), "job": None, "base": None, "base_at": None, "last": None, "samples": []}


def default_iface():
    """Interface of the default route (lowest metric); None without one."""
    best = None
    for line in read(NET_ROUTE).splitlines()[1:]:
        p = line.split()
        try:
            if len(p) >= 7 and p[1] == "00000000" and int(p[3], 16) & 1 and IFACE_RE.match(p[0]):
                if best is None or int(p[6]) < best[1]:
                    best = (p[0], int(p[6]))
        except ValueError:
            continue
    return best[0] if best else None


def rx_bytes(iface):
    v = read(os.path.join(NET_DIR, iface, "statistics", "rx_bytes")) if iface else ""
    return int(v) if v.isdigit() else None


def transfer(light, usage, mono=None, wall=None):
    """While the nightly job pulls or checks: phase, speed (default-route rx), bytes added to the
    disk since the transfer began, elapsed time. No percentage: the list carries no sizes.
    Only once the transfer has begun (work/t0; the job wipes work/ as it starts): the first-boot disk
    preparation also shows "checking" and has nothing to report here."""
    if light not in ("pulling", "checking"):
        return None
    work = os.path.join(RUN_DIR, "work")
    try:
        t0 = os.stat(os.path.join(work, "t0")).st_mtime
    except OSError:
        return None
    mono = time.monotonic() if mono is None else mono
    wall = time.time() if wall is None else wall
    used0 = read(os.path.join(work, "used0"))
    live = usage if usage and usage.get("live") else None
    with _tr["lock"]:
        if t0 != _tr["job"]:                       # a new job: forget the last one's baseline and speed
            _tr.update(job=t0, base=None, base_at=None, last=None, samples=[])
        if used0.isdigit():
            base, since = int(used0), "start"
        else:                                      # an older core: the first value this page saw
            if _tr["base"] is None and live:
                _tr.update(base=live["used"], base_at=int(wall))
            base, since = _tr["base"], "seen" if _tr["base"] is not None else None
        iface = default_iface()
        rx = rx_bytes(iface)
        last, samples = _tr["last"], _tr["samples"]
        if rx is not None and (last is None or mono - last[0] >= MIN_STEP_S):
            if last and last[2] == iface and rx >= last[1] and mono - last[0] <= GAP_S:
                samples.append((mono, (rx - last[1]) / (mono - last[0]), mono - last[0]))
            elif last:                             # a long gap, another interface or a reset counter
                samples.clear()
            _tr["last"] = (mono, rx, iface)
        samples[:] = [x for x in samples if mono - x[0] <= WINDOW_S]     # monotonic: a clock step does not bend the line
        recent = [x for x in samples if mono - x[0] <= AVG_S]
        span = sum(x[2] for x in recent)
        return {
            "phase": light,
            "elapsed_s": max(0, int(wall - t0)),
            "received": max(0, live["used"] - base) if live and base is not None else None,
            "since": since, "since_at": _tr["base_at"] if since == "seen" else None,
            "rate": int(samples[-1][1]) if samples else None,
            "rate_avg": int(sum(x[1] * x[2] for x in recent) / span) if span else None,
            "samples": [[round(mono - x[0], 1), int(x[1])] for x in samples],
            "window_s": WINDOW_S,
        }


def status():
    c = conf()
    last_run = kv(os.path.join(STATE, "last-run"))
    lock = kv(os.path.join(STATE, "code.lock"))
    until = int(lock.get("until", "0") or 0)
    light = (read(os.path.join(RUN_DIR, "light"), "unpaired").split() or ["unpaired"])
    try:
        up = int(float(read("/proc/uptime", "0").split()[0]))
    except ValueError:
        up = 0
    s = {
        "id": box_id(), "version": version(), "lang": c.get("LANG_UI", "en"),
        "paired": bool(c.get("SERVER")), "maint": os.path.exists(os.path.join(RUN_DIR, "maint")),
        "light": light[0], "light_arg": light[1] if len(light) > 1 else "", "light_kind": c.get("LIGHT_KIND", "rgb"),
        "last_sound": read(os.path.join(STATE, "son-saglam")) or None,
        "last_run": {k: last_run.get(k) for k in ("result", "id", "at")} if last_run else None,
        "suspect": read(os.path.join(STATE, "supheli-var")) or None,
        "code_set": bool(kv(os.path.join(STATE, "code.hash")).get("hash")),
        "code_locked_s": max(0, until - int(time.time())),
        "usage": disk_usage(c),
        "generations": generations(), "uptime_s": up, "drill": drill(c),
    }
    s["transfer"] = transfer(light[0], s["usage"])
    s.update(hardware())
    # what the box page shows under "Check the disk": missing, a slow link (USB 1.1), drops, or the last run could not reach it
    d = s["disk"]
    try:
        mbit = int(re.sub(r"\D", "", d.get("link") or "") or 0)
    except ValueError:
        mbit = 0
    # (drops are not shown on their own: reseating the disk is a drop too; a drop during a run ends as disk_error)
    kind = (("no_answer" if d.get("no_answer") else "missing") if not d.get("present") else "slow" if mbit and mbit < 480
            else "error" if (last_run or {}).get("result") == "disk_error" else None)
    s["disk_issue"] = {"kind": kind, "drops": d.get("drops", 0), "mbit": mbit} if kind else None
    s["clock"] = dict(clock_info(), now=int(time.time()), tz=(read("/etc/timezone").strip() or "UTC"))
    return s


_clk = {"t": 0, "v": None}


def clock_info():
    if time.time() - _clk["t"] < 20:
        return _clk["v"]
    rc, out = run(PURSER, "clock-source", timeout=15)
    src = out.strip().splitlines()[-1] if rc == 0 and out.strip() else "none"
    rtc = False
    for n in glob.glob("/sys/class/rtc/rtc*/name"):
        if "ds1307" in read(n) or "ds3231" in read(n):
            rtc = True
    _clk.update(t=time.time(), v={"source": src if src in ("ntp", "rtc", "none") else "none", "rtc": rtc})
    return _clk["v"]


def check_code(code):
    """0 ok, 1 wrong, 2 typo, 3 locked, 4 no code set (the core decides and counts)."""
    rc, _ = run(PURSER, "check-code", data=re.sub(r"[^0-9]", "", code or "")[:12] + "\n", timeout=30)
    return rc


ACTIONS = {
    "run": lambda: run("systemctl", "start", "--no-block", "purser.service"),
    "selftest": lambda: run(PURSER, "selftest-nocode", timeout=180),
    "disk-on": lambda: run(PURSER, "disk-on-nocode", timeout=180),
    "shutdown": lambda: (run(PURSER, "disk-off", timeout=60), run("systemctl", "--no-block", "poweroff"))[1],
}


class Page(http.server.BaseHTTPRequestHandler):
    server_version = "purser"
    sys_version = ""

    def log_message(self, fmt, *args):
        pass

    def send(self, code, body, kind="application/json; charset=utf-8"):
        if isinstance(body, (dict, list)):
            body = json.dumps(body, ensure_ascii=False).encode()
        self.send_response(code)
        self.send_header("Content-Type", kind)
        self.send_header("Content-Length", str(len(body)))
        self.send_header("Cache-Control", "no-store")
        self.send_header("X-Content-Type-Options", "nosniff")
        self.send_header("Referrer-Policy", "no-referrer")
        self.send_header("X-Frame-Options", "DENY")
        self.send_header("Strict-Transport-Security", "max-age=0")
        self.send_header("Permissions-Policy", "camera=(self), microphone=(), geolocation=()")
        self.send_header("Content-Security-Policy",
                         "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; "
                         "script-src 'self' 'unsafe-inline'; media-src 'self' blob:; frame-ancestors 'none'; base-uri 'none'; form-action 'none'")
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        if self.path == "/api/status":
            return self.send(200, status())
        if self.path == "/jsqr.js":                         # QR decoder (Apache-2.0, see jsqr.LICENSE); loaded only for scanning
            js = os.path.join(os.path.dirname(PAGE), "jsqr.min.js")
            try:
                return self.send(200, open(js, "rb").read(), "text/javascript; charset=utf-8")
            except OSError:
                return self.send(404, {"error": "not_found"})
        if self.path in ("/", "/index.html") or self.path.startswith("/?"):
            lang = conf().get("LANG_UI", "en")
            lang = lang if lang in ("tr", "en") else "en"
            page = read(PAGE).replace('<html lang="tr">', '<html lang="%s" data-dil="%s">' % (lang, lang), 1)
            return self.send(200, page.encode(), "text/html; charset=utf-8")
        self.send(404, {"error": "not_found"})

    def body(self):
        # same-origin JSON only: a cross-site form cannot set this header or content type
        if self.headers.get("X-Purser") != "1" or not (self.headers.get("Content-Type", "").startswith("application/json")):
            return None
        n = int(self.headers.get("Content-Length", "0") or 0)
        if n <= 0 or n > 8192:
            return None
        try:
            return json.loads(self.rfile.read(n))
        except ValueError:
            return None

    def do_POST(self):
        data = self.body()
        if not isinstance(data, dict):
            return self.send(400, {"error": "bad_request"})
        if self.path == "/api/light":                       # preview a state on the real stick for 10 s
            st = str(data.get("state", ""))
            if st not in LIGHTS:
                return self.send(400, {"error": "bad_state"})
            os.makedirs(RUN_DIR, exist_ok=True)
            with open(os.path.join(RUN_DIR, "light-preview"), "w") as f:
                f.write("%s %d\n" % (st, int(time.time()) + 10))
            return self.send(200, {"ok": True})
        if self.path == "/api/pair":
            token = str(data.get("token", "")).strip()
            if not re.fullmatch(r"purser-pair:[A-Za-z0-9_-]{40,4000}", token):
                return self.send(400, {"error": "bad_token"})
            rc, out = run(PURSER, "pair", token, "--later", timeout=90)
            ms = data.get("now")
            if rc == 0 and isinstance(ms, (int, float)) and ms > 0:     # the phone's clock, once, if a battery clock waits for it
                run(PURSER, "rtc-set", str(int(ms) // 1000), "--if-unset", timeout=30)
            return self.send(200 if rc == 0 else 409, {"ok": rc == 0, "code": rc, "detail": out[-300:]})
        if self.path == "/api/action":
            name = str(data.get("action", ""))
            if name not in ACTIONS and name not in ("settime", "clear"):
                return self.send(400, {"error": "bad_action"})
            gid = str(data.get("id", ""))
            if name == "clear" and not (ID_RE.match(gid) and str(data.get("confirm", "")) == gid):
                # checked before the code: a mistyped id costs no code attempt
                return self.send(400, {"error": "bad_id"})
            rc = check_code(str(data.get("code", "")))
            if rc != 0:
                return self.send(403, {"ok": False, "code": {1: "wrong", 2: "typo", 3: "locked", 4: "no_code"}.get(rc, "error"),
                                       "locked_s": status()["code_locked_s"]})
            if name == "settime":
                ms = data.get("now")
                if not isinstance(ms, (int, float)) or ms <= 0:
                    return self.send(400, {"error": "bad_time"})
                arc, out = run(PURSER, "rtc-set", str(int(ms) // 1000), timeout=30)
                return self.send(200 if arc == 0 else 409, {"ok": arc == 0, "detail": out[-300:]})
            if name == "clear":                                # the suspicion of one generation, id typed back
                arc, out = run(PURSER, "clear-nocode", gid, timeout=180)
                return self.send(200 if arc == 0 else (409 if arc == 3 else 500), {"ok": arc == 0, "detail": out[-300:]})
            arc, out = ACTIONS[name]()
            return self.send(200 if arc == 0 else 500, {"ok": arc == 0, "detail": out[-300:]})
        self.send(404, {"error": "not_found"})


def certificate():
    cert, key = os.path.join(UI_DIR, "cert.pem"), os.path.join(UI_DIR, "key.pem")
    if not (os.path.exists(cert) and os.path.exists(key)):
        os.makedirs(UI_DIR, mode=0o700, exist_ok=True)
        name = "%s.local" % box_id().lower()
        run("openssl", "req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-nodes", "-days", "3650",
            "-subj", "/CN=%s" % name, "-addext", "subjectAltName=DNS:%s" % name, "-keyout", key, "-out", cert, timeout=60)
        os.chmod(key, 0o600)
    return cert, key


class Server(http.server.ThreadingHTTPServer):
    daemon_threads = True
    address_family = socket.AF_INET


def main():
    cert, key = certificate()
    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    ctx.minimum_version = ssl.TLSVersion.TLSv1_2
    ctx.load_cert_chain(cert, key)
    srv = Server(("0.0.0.0", PORT), Page)
    srv.socket = ctx.wrap_socket(srv.socket, server_side=True)
    srv.serve_forever()


if __name__ == "__main__":
    sys.exit(main())
