#!/usr/bin/python3 -I
"""chandra-face: face unlock for Chandra, in the style of Howdy (docs/face-unlock.md).

    chandra-face status [--user U]          what is set up (anyone)
    chandra-face list [--user U]            enrolled faces: id, label, date (anyone)
    chandra-face enroll [--user U] [--label L]   add a face from the camera (root)
    chandra-face remove ID [--user U]       forget one face (root)
    chandra-face clear [--user U]           forget every face (root)
    chandra-face test [--user U]            look for the face now and print the scores (root)
    chandra-face compare --user U           what the PAM module runs: exit 0 match, 1 no match,
                                            2 face unlock can't be used (root)
    chandra-face pam [status|enable|disable] [SERVICE...]   put pam_chandra_face.so into
                                            /etc/pam.d/SERVICE (root; default polkit-1 sudo)
    chandra-face fetch-models               download the face models (root)
    chandra-face camera [--label L]         the "Add a face" window's camera, run as you: streams
                                            a small live picture with the face box, keeps snaps
                                            (their embeddings) in memory, and on "apply" saves
                                            the snaps and removals in one root step (one password)
    chandra-face apply [--user U]           add and remove faces in one go, from JSON on stdin:
                                            {"add": [{"label", "vectors"}], "remove": [ids]} (root)

Root commands started by another user re-run themselves through run0 or pkexec, so polkit asks
for an administrator's password first (in Chandra's own dialog).

Options: --config PATH (default /etc/chandra/face.conf), --machine (output as "kind text" lines
for the compositor and the PAM module: info, error, progress, face, done).

Safety: the camera images never leave this process and are never written anywhere; only face
embeddings (feature vectors) are stored, in /var/lib/chandra-face/USER/faces.json, owned by root,
mode 0600. compare refuses a store that someone else could have written. 2D face recognition can
be fooled by a good photo, more easily with an RGB webcam than an IR camera; see the docs.
"""

import configparser
import hashlib
import json
import math
import os
import pwd
import re
import shutil
import stat
import sys
import select
import subprocess
import tempfile
import time

DEFAULT_CONFIG = "/etc/chandra/face.conf"
MARK = "# added by chandra-face"
PAM_LINE = "-auth      sufficient   pam_chandra_face.so " + MARK
DEFAULT_SERVICES = ["polkit-1", "sudo"]
MODELS = {
    "face_detection_yunet_2023mar.onnx": (
        "https://media.githubusercontent.com/media/opencv/opencv_zoo/main/models/"
        "face_detection_yunet/face_detection_yunet_2023mar.onnx",
        "8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4",
    ),
    "face_recognition_sface_2021dec.onnx": (
        "https://media.githubusercontent.com/media/opencv/opencv_zoo/main/models/"
        "face_recognition_sface/face_recognition_sface_2021dec.onnx",
        "0ba9fbfa01b5270c96627c4ef784da859931e02f04419c829e83484087c34e79",
    ),
}
USER_RE = re.compile(r"^[a-z_][a-z0-9_.-]{0,31}\$?$", re.I)


class Fail(Exception):
    """A user-facing error; `code` is the exit status."""

    def __init__(self, msg, code=1):
        super().__init__(msg)
        self.code = code


# ---------------------------------------------------------------- configuration


class Config:
    def __init__(self, path=DEFAULT_CONFIG):
        cp = configparser.ConfigParser(inline_comment_prefixes=("#", ";"))
        self.path = path
        self.exists = False
        if path and os.path.exists(path):
            check_trusted(path, "config")
            cp.read(path)
            self.exists = True
        s = cp["face"] if cp.has_section("face") else {}

        def get(k, d):
            return s.get(k, d) if s else d

        self.enabled = get("enabled", "yes").lower() in ("yes", "true", "1", "on")
        self.backend = get("backend", "opencv")
        self.device = get("device", "/dev/video0")
        self.timeout = float(get("timeout", "4"))
        self.threshold = float(get("threshold", "0.42"))
        self.matches = max(1, int(get("matches", "2")))
        self.dark = float(get("dark", "25"))
        self.min_face = int(get("min_face", "80"))
        self.require_ir = get("require_ir", "no").lower() in ("yes", "true", "1", "on")
        self.store = get("store", "/var/lib/chandra-face")
        self.models = get("models", "/usr/local/share/chandra/face")
        self.enroll_frames = max(1, int(get("enroll_frames", "5")))
        self.pam_dir = get("pam_dir", "/etc/pam.d")
        self.frame_delay = float(get("frame_delay", "0"))


def check_trusted(path, what):
    """Refuse files and dirs that someone other than root (or us) could have changed."""
    st = os.lstat(path)
    if stat.S_ISLNK(st.st_mode):
        raise Fail("%s %s is a symlink" % (what, path), 2)
    if st.st_uid not in (0, os.geteuid()):
        raise Fail("%s %s is not owned by root" % (what, path), 2)
    if st.st_mode & 0o002 or (st.st_mode & 0o020 and st.st_gid != 0):
        raise Fail("%s %s can be written by others" % (what, path), 2)


# ---------------------------------------------------------------- output


class Out:
    """Machine lines ("info text") for the compositor and the PAM module, plain text otherwise."""

    def __init__(self, machine):
        self.machine = machine

    def emit(self, kind, text):
        if self.machine:
            sys.stdout.write("%s %s\n" % (kind, text.replace("\n", " ")))
        elif kind == "error":
            sys.stderr.write("chandra-face: %s\n" % text)
        elif kind in ("info", "done", "progress"):
            sys.stdout.write(text + "\n")
        else:
            sys.stdout.write("%s %s\n" % (kind, text))
        (sys.stdout if self.machine or kind != "error" else sys.stderr).flush()

    def info(self, t):
        self.emit("info", t)

    def error(self, t):
        self.emit("error", t)


# ---------------------------------------------------------------- store


def check_user(user):
    if not user or not USER_RE.match(user):
        raise Fail("bad user name %r" % user, 2)
    try:
        return pwd.getpwnam(user)
    except KeyError:
        raise Fail("no such user %r" % user, 2)


def user_dir(cfg, user):
    return os.path.join(cfg.store, user)


def load_faces(cfg, user, trusted=True):
    """The user's enrolled faces: [{id, label, created, vectors}]."""
    d = user_dir(cfg, user)
    f = os.path.join(d, "faces.json")
    if not os.path.exists(f):
        return []
    if trusted:
        check_trusted(cfg.store, "store")
        check_trusted(d, "store")
        check_trusted(f, "face data")
    fd = os.open(f, os.O_RDONLY | os.O_NOFOLLOW)
    with os.fdopen(fd) as fh:
        data = json.load(fh)
    return data.get("faces", [])


def list_labels(cfg, user):
    """[(id, label, created)] from the readable list (no biometric data), else faces.json."""
    p = os.path.join(user_dir(cfg, user), "faces.list")
    out = []
    if os.path.exists(p):
        with open(p) as fh:
            for line in fh:
                parts = line.rstrip("\n").split("\t")
                if len(parts) == 3:
                    out.append((int(parts[0]), parts[1], parts[2]))
        return out
    try:
        return [(f["id"], f["label"], f["created"]) for f in load_faces(cfg, user)]
    except (OSError, ValueError, Fail):
        return []


def write_atomic(path, text, mode):
    d = os.path.dirname(path)
    fd, tmp = tempfile.mkstemp(dir=d, prefix=".tmp-")
    try:
        os.fchmod(fd, mode)
        with os.fdopen(fd, "w") as fh:
            fh.write(text)
            fh.flush()
            os.fsync(fh.fileno())
        os.replace(tmp, path)
    except BaseException:
        if os.path.exists(tmp):
            os.unlink(tmp)
        raise


def save_faces(cfg, user, faces):
    old = os.umask(0o022)
    try:
        if not os.path.isdir(cfg.store):
            os.makedirs(cfg.store, 0o755)
        d = user_dir(cfg, user)
        if not os.path.isdir(d):
            os.mkdir(d, 0o755)
        check_trusted(cfg.store, "store")
        check_trusted(d, "store")
        if not faces:
            for n in ("faces.json", "faces.list"):
                p = os.path.join(d, n)
                if os.path.exists(p):
                    os.unlink(p)
            os.rmdir(d)
            return
        write_atomic(os.path.join(d, "faces.json"), json.dumps({"version": 1, "faces": faces}), 0o600)
        lines = "".join("%d\t%s\t%s\n" % (f["id"], f["label"], f["created"]) for f in faces)
        write_atomic(os.path.join(d, "faces.list"), lines, 0o644)
    finally:
        os.umask(old)


# ---------------------------------------------------------------- recognition


def cosine(a, b):
    num = sum(x * y for x, y in zip(a, b))
    na = math.sqrt(sum(x * x for x in a))
    nb = math.sqrt(sum(y * y for y in b))
    return num / (na * nb) if na > 0 and nb > 0 else -1.0


class Face:
    def __init__(self, x, y, w, h, raw=None):
        self.x, self.y, self.w, self.h, self.raw = x, y, w, h, raw


class OpenCVRecognizer:
    """YuNet finds faces, SFace turns an aligned face into a 128-number embedding."""

    def __init__(self, cfg):
        try:
            import cv2  # noqa
            import numpy  # noqa
        except ImportError:
            raise Fail("OpenCV is missing: run just install", 2)
        import cv2
        import numpy as np

        self.cv2, self.np = cv2, np
        try:
            cv2.utils.logging.setLogLevel(cv2.utils.logging.LOG_LEVEL_ERROR)
        except AttributeError:
            pass
        if not hasattr(cv2, "FaceDetectorYN"):
            raise Fail("OpenCV %s is too old (4.5.4+ needed)" % cv2.__version__, 2)
        det = os.path.join(cfg.models, "face_detection_yunet_2023mar.onnx")
        rec = os.path.join(cfg.models, "face_recognition_sface_2021dec.onnx")
        for p in (det, rec):
            if not os.path.exists(p):
                raise Fail("face models missing: run chandra-face fetch-models", 2)
            check_trusted(p, "model")
        self.det = cv2.FaceDetectorYN.create(det, "", (320, 320), 0.8, 0.3, 5)
        self.rec = cv2.FaceRecognizerSF.create(rec, "")

    def gray(self, frame):
        if frame.ndim == 2:
            return True
        b, g, r = frame[:, :, 0], frame[:, :, 1], frame[:, :, 2]
        return bool((abs(b.astype(int) - g).mean() < 2) and (abs(g.astype(int) - r).mean() < 2))

    def brightness(self, frame):
        return float(frame.mean())

    def detect(self, frame):
        if frame.ndim == 2:
            frame = self.cv2.cvtColor(frame, self.cv2.COLOR_GRAY2BGR)
        h, w = frame.shape[:2]
        self.det.setInputSize((w, h))
        _, faces = self.det.detect(frame)
        if faces is None:
            return []
        return [Face(int(f[0]), int(f[1]), int(f[2]), int(f[3]), f) for f in faces]

    def embed(self, frame, face):
        if frame.ndim == 2:
            frame = self.cv2.cvtColor(frame, self.cv2.COLOR_GRAY2BGR)
        crop = self.rec.alignCrop(frame, face.raw)
        v = self.rec.feature(crop).flatten()
        return [float(x) for x in v]


class FakeRecognizer:
    """For tests without a camera or OpenCV: frames are grayscale PGM images; a frame shows a
    "face" when it has contrast, and its embedding is the 4x4 block means around the average."""

    def __init__(self, cfg):
        pass

    def gray(self, frame):
        return True

    def brightness(self, frame):
        n = sum(len(r) for r in frame)
        return sum(sum(r) for r in frame) / n if n else 0.0

    def detect(self, frame):
        flat = [v for r in frame for v in r]
        if not flat or max(flat) - min(flat) < 40:
            return []
        return [Face(0, 0, len(frame[0]), len(frame))]

    def embed(self, frame, face):
        h, w = len(frame), len(frame[0])
        out = []
        for by in range(4):
            for bx in range(4):
                vals = [frame[y][x] for y in range(by * h // 4, (by + 1) * h // 4)
                        for x in range(bx * w // 4, (bx + 1) * w // 4)]
                out.append(sum(vals) / max(1, len(vals)))
        m = sum(out) / len(out)
        return [v - m for v in out]


def make_recognizer(cfg):
    if cfg.backend == "fake":
        return FakeRecognizer(cfg)
    if cfg.backend == "opencv":
        return OpenCVRecognizer(cfg)
    raise Fail("unknown backend %r" % cfg.backend, 2)


def read_pnm(path):
    """A binary PGM (P5) or PPM (P6) as rows of gray values."""
    with open(path, "rb") as fh:
        data = fh.read()
    toks, i = [], 0
    while len(toks) < 4:
        while data[i:i + 1].isspace():
            i += 1
        if data[i:i + 1] == b"#":
            while data[i:i + 1] not in (b"\n", b""):
                i += 1
            continue
        j = i
        while not data[j:j + 1].isspace():
            j += 1
        toks.append(data[i:j])
        i = j
    i += 1
    kind, w, h = toks[0], int(toks[1]), int(toks[2])
    px = data[i:]
    if kind == b"P5":
        return [list(px[y * w:(y + 1) * w]) for y in range(h)]
    if kind == b"P6":
        return [[(px[(y * w + x) * 3] + px[(y * w + x) * 3 + 1] + px[(y * w + x) * 3 + 2]) // 3
                 for x in range(w)] for y in range(h)]
    raise Fail("%s: not a binary PGM/PPM" % path, 2)


class ImageCamera:
    """`images:DIR`: the image files in DIR, in name order, as camera frames (for tests)."""

    def __init__(self, spec, cfg, loop=False):
        d = spec[len("images:"):]
        self.files = sorted(os.path.join(d, f) for f in os.listdir(d) if not f.startswith("."))
        self.i = 0
        self.cfg = cfg
        self.loop = loop

    def read(self):
        if self.loop and self.files:
            self.i %= len(self.files)
        if self.i >= len(self.files):
            return None
        f = self.files[self.i]
        self.i += 1
        if self.cfg.frame_delay:
            time.sleep(self.cfg.frame_delay)
        if f.endswith((".pgm", ".ppm")):
            frame = read_pnm(f)
            if self.cfg.backend != "fake":
                import numpy as np
                frame = np.array(frame, dtype=np.uint8)
            return frame
        import cv2
        return cv2.imread(f)

    def close(self):
        pass


class V4L2Camera:
    def __init__(self, device):
        import cv2
        self.cv2 = cv2
        dev = int(device) if device.isdigit() else device
        self.cap = cv2.VideoCapture(dev, cv2.CAP_V4L2)
        if not self.cap.isOpened():
            raise Fail("camera %s not available" % device, 2)

    def read(self):
        ok, frame = self.cap.read()
        return frame if ok else None

    def close(self):
        self.cap.release()


def open_camera(cfg, loop=False):
    if cfg.device.startswith("images:"):
        return ImageCamera(cfg.device, cfg, loop)
    if not cfg.device.isdigit() and not os.path.exists(cfg.device):
        raise Fail("no camera at %s" % cfg.device, 2)
    return V4L2Camera(cfg.device)


def frames(cam, seconds):
    """Frames until `seconds` pass or the camera ends."""
    end = time.monotonic() + seconds
    while time.monotonic() < end:
        f = cam.read()
        if f is None:
            return
        yield f


def largest(dets):
    return max(dets, key=lambda d: d.w * d.h)


# ---------------------------------------------------------------- commands


def cmd_compare(cfg, user, out, verbose=False):
    """Look for `user`'s face. 0: recognized, 1: not, 2: face unlock can't be used here."""
    check_user(user)
    if not cfg.enabled:
        return 2
    faces = load_faces(cfg, user)
    vectors = [v for f in faces for v in f.get("vectors", [])]
    if not vectors:
        return 2  # nothing enrolled: stay quiet, PAM goes on to the password
    try:
        rec = make_recognizer(cfg)
        cam = open_camera(cfg)
    except Fail as e:
        out.error("Face unlock: %s" % e)
        return 2
    out.info("Face unlock: looking for %s…" % user)
    hits = seen = dark = total = 0
    best = -1.0
    try:
        for frame in frames(cam, cfg.timeout):
            total += 1
            if rec.brightness(frame) < cfg.dark:
                dark += 1
                continue
            dets = rec.detect(frame)
            if not dets:
                continue
            face = largest(dets)
            if face.w < cfg.min_face and face.h < cfg.min_face and cfg.backend != "fake":
                continue
            if cfg.require_ir and not rec.gray(frame):
                out.error("Face unlock: needs an infrared camera (require_ir)")
                return 2
            seen += 1
            v = rec.embed(frame, face)
            score = max(cosine(v, s) for s in vectors)
            best = max(best, score)
            if verbose:
                out.emit("score", "%.3f" % score)
            if score >= cfg.threshold:
                hits += 1
                if hits >= cfg.matches:
                    out.info("Face unlock: recognized %s" % user)
                    return 0
    finally:
        cam.close()
    if verbose:
        out.emit("best", "%.3f" % best)
    if total == 0:
        out.error("Face unlock: the camera gave no picture")
    elif seen == 0 and dark == total:
        out.error("Face unlock: the camera picture is too dark")
    elif seen == 0:
        out.error("Face unlock: no face in view")
    else:
        out.error("Face unlock: face not recognized")
    return 1


def cmd_enroll(cfg, user, label, out):
    check_user(user)
    rec = make_recognizer(cfg)
    cam = open_camera(cfg)
    out.info("Look at the camera…")
    vecs = []
    many = 0
    try:
        for frame in frames(cam, max(cfg.timeout * 3, 10)):
            if rec.brightness(frame) < cfg.dark:
                continue
            dets = rec.detect(frame)
            if len(dets) > 1:
                many += 1
                continue
            if not dets:
                continue
            face = dets[0]
            if face.w < cfg.min_face and face.h < cfg.min_face and cfg.backend != "fake":
                continue
            vecs.append(rec.embed(frame, face))
            out.emit("progress", "%d/%d" % (len(vecs), cfg.enroll_frames))
            if len(vecs) >= cfg.enroll_frames:
                break
    finally:
        cam.close()
    if len(vecs) < cfg.enroll_frames:
        if many:
            raise Fail("more than one face in view: be alone in front of the camera")
        raise Fail("couldn't see a face clearly: look at the camera in good light and try again")
    faces = load_faces(cfg, user)
    nid = max([f["id"] for f in faces] + [0]) + 1
    label = clean_label(label, nid)
    faces.append({"id": nid, "label": label, "created": time.strftime("%Y-%m-%d"),
                  "vectors": [[round(x, 6) for x in v] for v in vecs]})
    save_faces(cfg, user, faces)
    out.emit("done", "Added %s" % label)
    return 0


def clean_label(label, nid):
    return (label or "Face %d" % nid).replace("\t", " ").replace("\n", " ").strip()[:60] or "Face %d" % nid


MAX_APPLY = 1 << 20


def cmd_apply(cfg, user, out, data=None):
    """Add and remove faces in one step (what the "Add a face" window's Apply runs as root).

    The embeddings come from the user's own camera process: anyone who can type the admin
    password could enroll any face anyway, so the password is the check, as for enroll."""
    check_user(user)
    if data is None:
        data = sys.stdin.buffer.read(MAX_APPLY + 1)
    if len(data) > MAX_APPLY:
        raise Fail("too much data")
    try:
        req = json.loads(data.decode("utf-8") or "{}")
    except ValueError:
        raise Fail("bad request")
    if not isinstance(req, dict):
        raise Fail("bad request")
    adds = req.get("add") or []
    removes = [str(r) for r in (req.get("remove") or [])]
    if not isinstance(adds, list) or len(adds) > 8:
        raise Fail("bad request")
    faces = load_faces(cfg, user)
    dims = {len(v) for f in faces for v in f.get("vectors", [])}
    new = []
    for a in adds:
        vecs = a.get("vectors") if isinstance(a, dict) else None
        if not isinstance(vecs, list) or not 1 <= len(vecs) <= 32:
            raise Fail("bad face data")
        for v in vecs:
            if not isinstance(v, list) or not 4 <= len(v) <= 1024 or \
                    not all(isinstance(x, (int, float)) and math.isfinite(x) for x in v):
                raise Fail("bad face data")
            dims.add(len(v))
        if len(dims) > 1:
            raise Fail("face data from another recognizer")
        label = a.get("label") if isinstance(a.get("label"), str) else ""
        new.append((label, vecs))
    known = {str(f["id"]) for f in faces}
    missing = [r for r in removes if r not in known]
    if missing:
        raise Fail("no face %s for %s" % (", ".join(missing), user))
    nid = max([f["id"] for f in faces] + [0])  # ids aren't reused
    faces = [f for f in faces if str(f["id"]) not in removes]
    for label, vecs in new:
        nid += 1
        faces.append({"id": nid, "label": clean_label(label, nid), "created": time.strftime("%Y-%m-%d"),
                      "vectors": [[round(float(x), 6) for x in v] for v in vecs]})
    save_faces(cfg, user, faces)
    parts = []
    if new:
        parts.append("added %s" % ", ".join(f["label"] for f in faces[-len(new):]))
    if removes:
        parts.append("removed %d face%s" % (len(removes), "" if len(removes) == 1 else "s"))
    msg = " and ".join(parts) or "nothing to change"
    out.emit("done", msg[:1].upper() + msg[1:])
    return 0


PREVIEW_W = 320
THUMB = 96


def resize_rows(rows, w, h):
    """Nearest-pixel resize of rows of gray values (the fake camera's frames)."""
    sh, sw = len(rows), len(rows[0])
    return [[rows[y * sh // h][x * sw // w] for x in range(w)] for y in range(h)]


def rgb_bytes(frame, rec, box=None, size=None):
    """`frame` (or its `box` = (x, y, w, h)) as RGB bytes at `size` = (w, h)."""
    if isinstance(frame, list):
        if box:
            x, y, w, h = box
            frame = [r[x:x + w] for r in frame[y:y + h]]
        g = resize_rows(frame, *size)
        return bytes(v for r in g for v in r for _ in range(3))
    cv2 = rec.cv2 if hasattr(rec, "cv2") else __import__("cv2")
    if box:
        x, y, w, h = box
        frame = frame[y:y + h, x:x + w]
    if frame.ndim == 2:
        frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR)
    frame = cv2.resize(frame, size, interpolation=cv2.INTER_AREA)
    return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB).tobytes()


def frame_size(frame):
    if isinstance(frame, list):
        return len(frame[0]), len(frame)
    return frame.shape[1], frame.shape[0]


def send_blob(header, data):
    """A binary message: `header LEN` on a line, then LEN bytes."""
    sys.stdout.flush()
    sys.stdout.buffer.write(("%s %d\n" % (header, len(data))).encode())
    sys.stdout.buffer.write(data)
    sys.stdout.buffer.flush()


def elevated(args):
    """argv running chandra-face `args` as root through run0 or pkexec (polkit asks first)."""
    me = os.path.realpath(sys.argv[0])
    run0 = shutil.which("run0")
    if run0 and os.path.isdir("/run/systemd/system"):
        return [run0, "--background=", "--", sys.executable, "-I", me] + args
    pk = shutil.which("pkexec")
    if pk:
        return [pk, sys.executable, "-I", me] + args
    raise Fail("needs root, and neither run0 nor pkexec is installed")


def cmd_camera(cfg, user, label, out, cfg_path, no_elevate):
    """The "Add a face" window's camera, run as the session user (no root, no password).

    Out ("--machine" lines): `frame W H BX BY BW BH LEN` + LEN bytes of RGB (the live picture,
    about 12 a second; the box is -1s without one face), `snap ID W H LEN` + RGB (a kept snap,
    cropped to the face), `info` / `error` / `done` lines, `applied CODE` at the end of an apply.
    In (stdin lines): `snap`, `drop ID`, `apply REMOVE-IDS` (comma-separated, may be empty), `quit`.
    The pictures stay in this process's memory: nothing is written to disk; only the embeddings
    of the snaps kept go to the root `apply`, through a pipe."""
    check_user(user)
    rec = make_recognizer(cfg)
    cam = open_camera(cfg, loop=True)
    snaps = {}  # id -> embedding
    next_id = 1
    last = None
    last_sent = 0.0
    pending = b""
    out.info("Look at the camera and press Snap")
    try:
        while True:
            frame = cam.read()
            if frame is None:
                out.error("The camera gave no picture")
                return 2
            if isinstance(cam, ImageCamera):
                time.sleep(max(cfg.frame_delay, 0.03))
            last = frame
            now = time.monotonic()
            if now - last_sent >= 0.08:
                last_sent = now
                w, h = frame_size(frame)
                pw = min(PREVIEW_W, w)
                ph = max(1, h * pw // w)
                dets = rec.detect(frame) if rec.brightness(frame) >= cfg.dark else []
                bx = (-1, -1, -1, -1)
                if len(dets) == 1:
                    d = dets[0]
                    bx = (d.x * pw // w, d.y * ph // h, d.w * pw // w, d.h * ph // h)
                send_blob("frame %d %d %d %d %d %d" % ((pw, ph) + bx), rgb_bytes(frame, rec, size=(pw, ph)))
            r, _, _ = select.select([0], [], [], 0)
            if not r:
                continue
            got = os.read(0, 4096)
            if not got:
                return 0
            pending += got
            while b"\n" in pending:
                line, pending = pending.split(b"\n", 1)
                words = line.decode("utf-8", "replace").strip().split(" ", 1)
                cmd, arg = words[0], (words[1] if len(words) > 1 else "")
                if cmd == "quit":
                    return 0
                if cmd == "drop":
                    snaps.pop(arg, None)
                elif cmd == "snap":
                    v, why, box = snap_face(cfg, rec, last)
                    if v is None:
                        out.error(why)
                        continue
                    sid = str(next_id)
                    next_id += 1
                    snaps[sid] = v
                    send_blob("snap %s %d %d" % (sid, THUMB, THUMB), rgb_bytes(last, rec, box, (THUMB, THUMB)))
                elif cmd == "apply":
                    cam.close()
                    cam = None
                    removes = [r for r in arg.split(",") if r.strip()]
                    req = {"add": [{"label": label or "", "vectors": list(snaps.values())}] if snaps else [],
                           "remove": removes}
                    code = run_apply(cfg, user, out, req, cfg_path, no_elevate)
                    out.emit("applied", str(code))
                    return code
    finally:
        if cam is not None:
            cam.close()


def snap_face(cfg, rec, frame):
    """(embedding, "", square face box) for the one face in `frame`, or (None, why, None)."""
    if frame is None:
        return None, "No picture yet", None
    if rec.brightness(frame) < cfg.dark:
        return None, "The picture is too dark", None
    dets = rec.detect(frame)
    if not dets:
        return None, "No face in view", None
    if len(dets) > 1:
        return None, "More than one face in view", None
    d = dets[0]
    if d.w < cfg.min_face and d.h < cfg.min_face and cfg.backend != "fake":
        return None, "Come closer to the camera", None
    if cfg.require_ir and not rec.gray(frame):
        return None, "Needs an infrared camera (require_ir)", None
    v = [round(x, 6) for x in rec.embed(frame, d)]
    w, h = frame_size(frame)
    side = min(int(max(d.w, d.h) * 1.4), w, h)
    x = min(max(0, d.x + d.w // 2 - side // 2), w - side)
    y = min(max(0, d.y + d.h // 2 - side // 2), h - side)
    return v, "", (x, y, side, side)


def run_apply(cfg, user, out, req, cfg_path, no_elevate):
    """Run `apply` as root with `req` on its stdin, passing on what it says."""
    data = json.dumps(req).encode()
    if os.geteuid() == 0 or no_elevate:
        try:
            return cmd_apply(cfg, user, out, data)
        except Fail as e:
            out.error(str(e))
            return e.code
    args = ["apply", "--machine", "--user", user]
    if cfg_path != DEFAULT_CONFIG:
        args += ["--config", cfg_path]
    out.info("Waiting for the password…")
    p = subprocess.Popen(elevated(args), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                         stderr=subprocess.DEVNULL)
    try:
        p.stdin.write(data)
        p.stdin.close()
    except BrokenPipeError:
        pass
    said = False
    for raw in p.stdout:
        line = raw.decode("utf-8", "replace").rstrip("\n")
        kind = line.split(" ", 1)[0]
        if kind in ("info", "error", "done"):
            said = said or kind != "info"
            sys.stdout.write(line + "\n")
            sys.stdout.flush()
    code = p.wait()
    if not said:
        out.error("Nothing changed")
        return code or 1
    return code


def cmd_remove(cfg, user, ident, out):
    check_user(user)
    faces = load_faces(cfg, user)
    keep = [f for f in faces if str(f["id"]) != str(ident)]
    if len(keep) == len(faces):
        raise Fail("no face %s for %s" % (ident, user))
    save_faces(cfg, user, keep)
    out.emit("done", "Removed face %s" % ident)
    return 0


def cmd_clear(cfg, user, out):
    check_user(user)
    save_faces(cfg, user, [])
    out.emit("done", "Removed every face of %s" % user)
    return 0


def pam_services(cfg, module):
    """The PAM services whose file uses `module` on an auth line."""
    out = []
    try:
        names = sorted(os.listdir(cfg.pam_dir))
    except OSError:
        return out
    for n in names:
        p = os.path.join(cfg.pam_dir, n)
        try:
            with open(p) as fh:
                for line in fh:
                    t = line.split("#", 1)[0].split()
                    if len(t) >= 3 and t[0].lstrip("-") == "auth" and any(module in w for w in t[1:]):
                        out.append(n)
                        break
        except (OSError, UnicodeDecodeError):
            pass
    return out


def pam_enable(cfg, service, out):
    if not re.match(r"^[a-z0-9_.-]+$", service):
        raise Fail("bad service name %r" % service)
    p = os.path.join(cfg.pam_dir, service)
    if not os.path.exists(p):
        vendor = os.path.join("/usr/lib/pam.d", service)
        if not os.path.exists(vendor):
            raise Fail("no PAM service %s" % service)
        shutil.copyfile(vendor, p)
    with open(p) as fh:
        lines = fh.read().split("\n")
    if any("pam_chandra_face.so" in l and not l.lstrip().startswith("#") for l in lines):
        out.emit("done", "%s already uses face unlock" % service)
        return 0
    bak = p + ".chandra-face.bak"
    if not os.path.exists(bak):
        shutil.copy2(p, bak)
    # Before the first auth line, so the face is tried first and the password after it.
    # Debian's sudo has no auth line of its own, only "@include common-auth": go before that.
    at = next((i for i, l in enumerate(lines)
               if l.split() and l.split()[0].lstrip("-") in ("auth", "@include")), None)
    if at is None:
        at = next((i for i, l in enumerate(lines) if l.strip() and not l.startswith("#")), len(lines))
    lines.insert(at, PAM_LINE)
    write_atomic(p, "\n".join(lines), stat.S_IMODE(os.stat(p).st_mode))
    out.emit("done", "%s: face unlock first, then the password" % service)
    return 0


def pam_disable(cfg, service, out):
    if not re.match(r"^[a-z0-9_.-]+$", service):
        raise Fail("bad service name %r" % service)
    p = os.path.join(cfg.pam_dir, service)
    if not os.path.exists(p):
        return 0
    with open(p) as fh:
        lines = fh.read().split("\n")
    keep = [l for l in lines if "pam_chandra_face.so" not in l or l.lstrip().startswith("#")]
    if len(keep) != len(lines):
        write_atomic(p, "\n".join(keep), stat.S_IMODE(os.stat(p).st_mode))
        out.emit("done", "%s: password only" % service)
    return 0


def cmd_status(cfg, user, out):
    """Lines: backend, problem (why it can't work, if so), pam (services), howdy, face rows."""
    problem = ""
    backend = cfg.backend
    if not cfg.enabled:
        problem = "turned off in %s" % cfg.path
    elif backend == "opencv":
        try:
            import cv2  # noqa
        except ImportError:
            problem = "OpenCV is missing: run just install"
        if not problem:
            for m in MODELS:
                if not os.path.exists(os.path.join(cfg.models, m)):
                    problem = "face models missing: run chandra-face fetch-models"
                    break
    if not problem and not cfg.device.startswith("images:") and not cfg.device.isdigit() \
            and not os.path.exists(cfg.device):
        problem = "no camera at %s" % cfg.device
    out.emit("backend", backend)
    out.emit("device", cfg.device)
    if problem:
        out.emit("problem", problem)
    out.emit("pam", ",".join(pam_services(cfg, "pam_chandra_face.so")))
    howdy = pam_services(cfg, "pam_howdy.so")
    if howdy:
        out.emit("howdy", ",".join(howdy))
    for i, label, created in list_labels(cfg, user):
        out.emit("face", "%d\t%s\t%s" % (i, label, created))
    return 0


def cmd_fetch_models(cfg, out):
    import urllib.request

    os.makedirs(cfg.models, 0o755, exist_ok=True)
    for name, (url, sha) in MODELS.items():
        dst = os.path.join(cfg.models, name)
        if os.path.exists(dst) and hashlib.sha256(open(dst, "rb").read()).hexdigest() == sha:
            out.info("%s is there" % name)
            continue
        out.info("downloading %s" % name)
        data = urllib.request.urlopen(url, timeout=60).read()
        got = hashlib.sha256(data).hexdigest()
        if got != sha:
            raise Fail("%s: checksum mismatch (%s)" % (name, got))
        fd, tmp = tempfile.mkstemp(dir=cfg.models)
        with os.fdopen(fd, "wb") as fh:
            fh.write(data)
        os.chmod(tmp, 0o644)
        os.replace(tmp, dst)
    out.emit("done", "models in %s" % cfg.models)
    return 0


# ---------------------------------------------------------------- main


ROOT_CMDS = ("enroll", "remove", "clear", "test", "compare", "fetch-models", "apply")


def elevate(argv, user):
    """Run this command again as root through run0 (systemd) or pkexec: polkit asks first."""
    args = list(argv)
    if "--user" not in argv:
        args += ["--user", user]
    cmd = elevated(args)
    os.execv(cmd[0], cmd)


def main(argv):
    args = list(argv)
    machine = "--machine" in args
    if machine:
        args.remove("--machine")
    out = Out(machine)
    cfg_path = DEFAULT_CONFIG
    user = None
    label = None
    no_elevate = False
    rest = []
    i = 0
    while i < len(args):
        a = args[i]
        if a in ("--config", "--user", "--label") and i + 1 < len(args):
            if a == "--config":
                cfg_path = args[i + 1]
            elif a == "--user":
                user = args[i + 1]
            else:
                label = args[i + 1]
            i += 2
            continue
        if a == "--no-elevate":
            no_elevate = True
        elif a in ("-h", "--help"):
            print(__doc__)
            return 0
        else:
            rest.append(a)
        i += 1
    if not rest:
        print(__doc__)
        return 2
    cmd, params = rest[0], rest[1:]
    if user is None:
        user = pwd.getpwuid(os.getuid()).pw_name
    pam_change = cmd == "pam" and params[:1] in (["enable"], ["disable"])
    try:
        if (cmd in ROOT_CMDS or pam_change) and os.geteuid() != 0 and not no_elevate:
            # compare must never elevate: the PAM module already runs it as root.
            if cmd == "compare":
                raise Fail("compare runs as root (from the PAM module)", 2)
            elevate(argv, user)
        cfg = Config(cfg_path)
        if cmd == "status":
            return cmd_status(cfg, user, out)
        if cmd == "list":
            for i2, l, c in list_labels(cfg, user):
                out.emit("face", "%d\t%s\t%s" % (i2, l, c))
            return 0
        if cmd == "compare":
            return cmd_compare(cfg, user, out)
        if cmd == "test":
            return cmd_compare(cfg, user, out, verbose=True)
        if cmd == "enroll":
            return cmd_enroll(cfg, user, label, out)
        if cmd == "apply":
            return cmd_apply(cfg, user, out)
        if cmd == "camera":
            return cmd_camera(cfg, user, label, out, cfg_path, no_elevate)
        if cmd == "remove":
            if not params:
                raise Fail("remove ID")
            return cmd_remove(cfg, user, params[0], out)
        if cmd == "clear":
            return cmd_clear(cfg, user, out)
        if cmd == "fetch-models":
            return cmd_fetch_models(cfg, out)
        if cmd == "pam":
            what = params[0] if params else "status"
            services = params[1:] or DEFAULT_SERVICES
            if what == "status":
                out.emit("pam", ",".join(pam_services(cfg, "pam_chandra_face.so")))
                return 0
            for s in services:
                (pam_enable if what == "enable" else pam_disable)(cfg, s, out)
            return 0
        raise Fail("unknown command %r" % cmd, 2)
    except Fail as e:
        out.error(str(e))
        return e.code
    except KeyboardInterrupt:
        return 1
    except BrokenPipeError:
        return 0  # the window that read us went away


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
