#!/usr/bin/env python3
# SPDX-FileCopyrightText: Copyright (c) 2026 misc-de
# SPDX-License-Identifier: MIT
"""Contributes Wi-Fi observations to beaconDB - carefully, or not at all.

This is what is left of this repository since 27.9.2026: the location filter
it started with is retired, because geoclue now refuses IP-derived positions
itself. What remains is the other direction - handing beaconDB the
observations that would let it answer properly next time, for this area.

It is off unless somebody turns it on. Everything below exists to make sure
that what is sent is worth having and that the server is left alone as much as
possible - a contributor that floods a volunteer-run service with noise is
worse than no contributor.

The rules, and where they come from
-----------------------------------
beaconDB states them at https://beacondb.net and refers to ichnaea's API:

  * submissions go to https://api.beacondb.net/v2/geosubmit as
    {"items": [{timestamp, position, wifiAccessPoints}]}
  * "Hidden Wifi networks must not be collected."
  * "Wifi networks with a SSID ending in _nomap must not be collected."
    beaconDB honours _optout as well, so both are dropped here.
  * clients must identify themselves with a user agent.

Nothing states a rate limit. That is not permission to hammer it: the
intervals below are deliberately slow, submissions are batched, and a failure
backs off rather than retries.

What counts as a measurement worth sending
------------------------------------------
The position has to come from GNSS. This matters more than anything else
here: geoclue can answer from a Wi-Fi lookup, and a Wi-Fi lookup is answered
by beaconDB itself. Submitting one of those would feed the database its own
estimate back as though it were an observation - a feedback loop that makes
the data worse and looks, from the server's side, exactly like poisoning.

Two things separate a GNSS fix from a network-derived one, and both are
required here:

  * an altitude. Wi-Fi and IP lookups return none; GNSS does.
  * an accuracy at or below ACCURACY_MAX metres. A GNSS fix on this device
    is a handful of metres; a Wi-Fi answer is tens to hundreds.

The altitude is the stronger of the two, because it is a fact about the fix
rather than a threshold somebody picked.
"""
import json
import os
import re
import subprocess
import sys
import time
import urllib.error
import urllib.request

import gi
from gi.repository import Gio, GLib  # noqa: E402

VERSION = "0.1.0"
ENDPOINT = os.environ.get("CONTRIB_ENDPOINT",
                          "https://api.beacondb.net/v2/geosubmit")
# beaconDB asks clients to identify themselves. A contact address belongs in
# here so that somebody with a complaint has somewhere to send it.
USER_AGENT = f"furios_gps/{VERSION} (+https://github.com/misc-de/furios_gps)"

STATE_DIR = os.environ.get(
    "CONTRIB_STATE",
    os.path.join(os.environ.get("XDG_CONFIG_HOME",
                                os.path.expanduser("~/.config")), "furios-gps"))
MARKER = os.path.join(STATE_DIR, "contribute")     # exists = switched on
# The user unit "on" and "off" start and stop. Overridable for the same reason
# as the state directory: the tests switch this on and off, and on the phone
# they run on, the real unit is installed - starting and stopping it from a
# test run would be the suite reaching into the live system it is testing.
UNIT = os.environ.get("CONTRIB_UNIT", "furios-gps-contribute.service")
# Whether the unit was enabled before the first "on" - written then, before
# anything changes, and read by "off" to put exactly that back. See
# unit_before_on().
UNIT_RECORD = os.path.join(STATE_DIR, "unit-before-on")
QUEUE = os.path.join(STATE_DIR, "queue.jsonl")
STATS = os.path.join(STATE_DIR, "contribute-stats.json")

# Deliberately unhurried. A phone in a pocket does not need to be measured
# more often than this, and a measurement every few minutes still maps a walk.
INTERVAL_S = int(os.environ.get("CONTRIB_INTERVAL", "180"))
ACCURACY_MAX = float(os.environ.get("CONTRIB_ACCURACY", "25"))
# Two observations of the same spot teach the database nothing the first did
# not, so a new one has to be a real distance away or a long time later.
MIN_MOVE_M = float(os.environ.get("CONTRIB_MIN_MOVE", "40"))
MIN_AGE_S = int(os.environ.get("CONTRIB_MIN_AGE", "900"))
# One request per batch, and never more than a handful of batches an hour.
BATCH = int(os.environ.get("CONTRIB_BATCH", "12"))
QUEUE_MAX = int(os.environ.get("CONTRIB_QUEUE_MAX", "500"))
# ichnaea wants at least two access points in a wifi-only report.
MIN_APS = 2
# The networks are paired with the fix, so they have to be scanned where the
# fix was taken: after it, and soon after. At walking pace 20 s is a few tens
# of metres; in a car it is not, which is why it is not longer.
SCAN_AFTER_FIX_S = float(os.environ.get("CONTRIB_SCAN_AFTER_FIX", "20"))
# Backoff after a refused or failed submission, in seconds. It gives up for
# this run rather than walking the list again - the queue keeps.
BACKOFF_S = [60, 300, 1800]
# How long the receiver may look for a fix. Between attempts it is off for
# minutes, so nearly every attempt is a cold start, and a cold start takes
# about a minute under open sky (67 s measured on a Volla Phone Quintus).
FIX_WAIT_S = int(os.environ.get("CONTRIB_FIX_WAIT", "120"))
# Failed attempts stretch the pause before the next one (see measure()), but
# not beyond this: an hour lets a whole walk pass without a single attempt.
MISS_PAUSE_MAX_S = int(os.environ.get("CONTRIB_MISS_PAUSE_MAX", "1200"))
# Below this overlap with the networks of the last failed attempt the phone
# has gone somewhere else, and the pause is cut short. Looser than
# same_surroundings(): a flickering network at home must not read as a move,
# or the receiver would run every few minutes indoors.
MOVED_OVERLAP = 0.5


class GeolocationOff(Exception):
    """geoclue refused us: location is switched off system-wide."""

NOMAP = re.compile(r"(_nomap|_optout)$", re.IGNORECASE)


def log(*a):
    print(*a, flush=True)


def load_stats():
    try:
        with open(STATS) as fh:
            return json.load(fh)
    except (OSError, ValueError):
        return {}


def save_stats(s):
    os.makedirs(STATE_DIR, exist_ok=True)
    tmp = STATS + ".tmp"
    with open(tmp, "w") as fh:
        json.dump(s, fh)
    os.replace(tmp, STATS)


# ---------------------------------------------------------------- wifi

def locally_administered(mac):
    """True for a MAC address its owner made up rather than bought."""
    return bool(int(mac[:2], 16) & 0x02)


def scan_wifi():
    """Access points in range, as beaconDB may receive them.

    nmcli, because it needs no root and NetworkManager is scanning anyway -
    a scan of our own would cost power and interrupt the connection.
    """
    try:
        out = subprocess.run(
            ["nmcli", "-t", "-f", "BSSID,SSID,FREQ,SIGNAL", "device", "wifi", "list"],
            capture_output=True, text=True, timeout=30, env=NMCLI_ENV).stdout
    except (OSError, subprocess.SubprocessError):
        return []

    aps, seen = [], set()
    for line in out.splitlines():
        # nmcli escapes the colons inside a BSSID as "\:" - unescaping first
        # and splitting after would tear the MAC apart.
        fields = re.split(r"(?<!\\):", line)
        if len(fields) < 4:
            continue
        mac = fields[0].replace("\\:", ":").strip().upper()
        ssid = fields[1].replace("\\:", ":")
        if not re.fullmatch(r"(?:[0-9A-F]{2}:){5}[0-9A-F]{2}", mac):
            continue

        # Hidden networks must not be collected - nmcli reports them with an
        # empty SSID. Neither must anything that opted out.
        if not ssid.strip() or NOMAP.search(ssid.strip()):
            continue
        # A router that moves takes its observations with it and poisons the
        # area it left. These names are what phones call their hotspots.
        if re.search(r"(iphone|android.?ap|mobile.?hotspot|galaxy.*hotspot)",
                     ssid, re.IGNORECASE):
            continue
        # The name is whatever the owner typed; the address is not. Phones
        # and travel routers make up a random, locally administered BSSID
        # for their hotspot - the second-lowest bit of the first octet set -
        # where a fixed access point carries its maker's address. Some
        # fixed ones use such addresses for extra SSIDs too; losing those is
        # cheap, a moving one in the database is not.
        if locally_administered(mac):
            continue
        if mac in seen:
            continue
        seen.add(mac)

        ap = {"macAddress": mac}
        try:
            ap["frequency"] = int(fields[2].split()[0])
        except (ValueError, IndexError):
            pass
        try:
            # nmcli reports 0-100; ichnaea wants dBm. The usual mapping.
            ap["signalStrength"] = int(round(int(fields[3]) / 2.0 - 100))
        except (ValueError, IndexError):
            pass
        aps.append(ap)
    return aps


# ---------------------------------------------------------------- position

def gnss_fix(not_before, wait_s=FIX_WAIT_S):
    """One position from geoclue, but only if it is a fresh GNSS one.

    Returns (position, fix time) or None rather than a doubtful fix. Sending a
    Wi-Fi-derived position would hand beaconDB its own answer back as an
    observation; sending a stale one pairs today's networks with yesterday's
    place.
    """
    bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None)

    def proxy(path, iface):
        return Gio.DBusProxy.new_sync(bus, Gio.DBusProxyFlags.NONE, None,
                                      "org.freedesktop.GeoClue2", path, iface, None)

    mgr = proxy("/org/freedesktop/GeoClue2/Manager",
                "org.freedesktop.GeoClue2.Manager")
    client_path = mgr.call_sync("GetClient", None, Gio.DBusCallFlags.NONE, -1, None).unpack()[0]
    props = proxy(client_path, "org.freedesktop.DBus.Properties")

    def set_prop(name, variant):
        props.call_sync("Set", GLib.Variant("(ssv)",
                        ("org.freedesktop.GeoClue2.Client", name, variant)),
                        Gio.DBusCallFlags.NONE, -1, None)

    set_prop("DesktopId", GLib.Variant("s", "furios-gps-contribute"))
    set_prop("RequestedAccuracyLevel", GLib.Variant("u", 8))   # EXACT

    client = proxy(client_path, "org.freedesktop.GeoClue2.Client")
    loop = GLib.MainLoop()
    result = {}

    def on_signal(_p, _s, signal, params):
        if signal != "LocationUpdated":
            return
        location_path = params.unpack()[1]
        lp = proxy(location_path, "org.freedesktop.DBus.Properties")
        values = lp.call_sync("GetAll", GLib.Variant("(s)",
                             ("org.freedesktop.GeoClue2.Location",)),
                             Gio.DBusCallFlags.NONE, -1, None).unpack()[0]
        result.clear()
        result.update(values)
        # geoclue answers a new client with its last known location first
        # while it still has one (an app kept it running), and the fresh fix
        # follows a second later. Stopping at the first answer would end
        # every attempt on that cached one, which judge_fix() refuses - so
        # wait on for a fix taken after the request, up to wait_s.
        # A fresh fix that judge_fix() would still refuse (the first ones of
        # a cold start are often tens of metres off) is kept, and the wait
        # goes on for a better one.
        if not fix_is_older(values, not_before) and fix_is_good(values):
            loop.quit()

    client.connect("g-signal", on_signal)
    try:
        client.call_sync("Start", None, Gio.DBusCallFlags.NONE, 15000, None)
    except GLib.Error as e:
        log("geoclue would not start:", e.message)
        # Location switched off is not a failed fix: the receiver never ran.
        if "AccessDenied" in (e.message or ""):
            raise GeolocationOff() from e
        return None
    GLib.timeout_add_seconds(wait_s, lambda: (loop.quit(), False)[1])
    loop.run()
    try:
        client.call_sync("Stop", None, Gio.DBusCallFlags.NONE, 5000, None)
    except GLib.Error:
        pass

    if not result:
        return None
    return judge_fix(result, not_before)


def fix_is_older(result, not_before):
    """True for a fix with a timestamp from before not_before. Without a
    readable timestamp it is not "older" here; judge_fix() refuses it."""
    try:
        stamp = result["Timestamp"]
        return float(stamp[0]) + float(stamp[1]) / 1e6 < not_before
    except (KeyError, TypeError, ValueError, IndexError):
        return False


def fix_is_good(result):
    """True for a fix judge_fix() would accept on accuracy and altitude."""
    altitude = result.get("Altitude")
    return (altitude is not None and altitude > -1e300
            and float(result.get("Accuracy", 1e9)) <= ACCURACY_MAX)


def judge_fix(result, not_before):
    """(position, fix time in seconds) from geoclue's Location properties,
    or None for a fix that must not be paired with a scan.

    geoclue answers a new client from its last known location when it has one,
    and that answer can be minutes old - from before the bus, before the
    building, before the walk. Its Timestamp says when it was taken; a fix
    from before not_before (the moment it was asked for) is somebody else's
    position as far as the networks scanned now are concerned.
    """
    stamp = result.get("Timestamp")
    try:
        taken = float(stamp[0]) + float(stamp[1]) / 1e6
    except (TypeError, ValueError, IndexError):
        log("skipped: the fix carries no timestamp - its age is unknown")
        return None
    if taken < not_before:
        log(f"skipped: the fix is {not_before - taken:.0f} s older than the "
            "request - a cached position, not this one")
        return None

    accuracy = float(result.get("Accuracy", 1e9))
    altitude = result.get("Altitude")
    # geoclue reports a missing altitude as -1.8e308, not as absent.
    has_altitude = altitude is not None and altitude > -1e300
    if not has_altitude:
        log("skipped: no altitude - that is a network fix, not GNSS")
        return None
    if accuracy > ACCURACY_MAX:
        log(f"skipped: accuracy {accuracy:.0f} m is over {ACCURACY_MAX:.0f} m")
        return None

    pos = {
        "latitude": float(result["Latitude"]),
        "longitude": float(result["Longitude"]),
        "accuracy": accuracy,
        "altitude": float(altitude),
        "source": "gps",
    }
    for key, name in (("Speed", "speed"), ("Heading", "heading")):
        value = result.get(key)
        if value is not None and value >= 0:
            pos[name] = float(value)
    return pos, taken


def distance_m(a, b):
    """Rough great-circle distance. Good to a few metres over short spans,
    which is all this is used for."""
    import math
    r = 6371000.0
    p1, p2 = math.radians(a[0]), math.radians(b[0])
    dp = p2 - p1
    dl = math.radians(b[1] - a[1])
    h = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
    return 2 * r * math.asin(min(1.0, math.sqrt(h)))


# ---------------------------------------------------------------- queue

def queue_append(item):
    os.makedirs(STATE_DIR, exist_ok=True)
    # A queue that grows without end on a phone that is never online is a bug,
    # not patience. The oldest go first - newer observations are worth more.
    lines = queue_read()
    lines.append(item)
    if len(lines) > QUEUE_MAX:
        lines = lines[-QUEUE_MAX:]
    queue_write(lines)


def queue_read():
    try:
        with open(QUEUE) as fh:
            return [json.loads(z) for z in fh if z.strip()]
    except (OSError, ValueError):
        return []


def queue_write(lines):
    os.makedirs(STATE_DIR, exist_ok=True)
    tmp = QUEUE + ".tmp"
    with open(tmp, "w") as fh:
        for z in lines:
            fh.write(json.dumps(z) + "\n")
    os.replace(tmp, QUEUE)


# ---------------------------------------------------------------- submit

# nmcli translates its values even with -t: on a system with NetworkManager's
# German catalogue the state is "verbunden", "wifi:connected" never matches
# and nothing is ever submitted. FuriOS ships without that catalogue today;
# pactl's is there and broke audioctl exactly this way (4.10.2026).
NMCLI_ENV = dict(os.environ, LC_ALL="C.UTF-8")


def on_wifi():
    """Only submit over Wi-Fi. Somebody who turned this on did not agree to
    spend their mobile data allowance on it."""
    try:
        out = subprocess.run(["nmcli", "-t", "-f", "TYPE,STATE", "device", "status"],
                             capture_output=True, text=True, timeout=15,
                             env=NMCLI_ENV).stdout
    except (OSError, subprocess.SubprocessError):
        return False
    return any(z.startswith("wifi:connected") for z in out.splitlines())


def submit(items):
    """One request, one batch. Returns True when beaconDB took it."""
    body = json.dumps({"items": items}).encode()
    req = urllib.request.Request(ENDPOINT, data=body, method="POST")
    req.add_header("Content-Type", "application/json")
    req.add_header("User-Agent", USER_AGENT)
    try:
        with urllib.request.urlopen(req, timeout=60) as resp:
            return 200 <= resp.status < 300
    except urllib.error.HTTPError as e:
        # 4xx is us: a malformed report, or being asked to stop. Retrying it
        # unchanged would be exactly the behaviour that earns a block, so the
        # batch is dropped and the reason is said out loud.
        # Not "e.code < 500 and None or False": None is falsy, so that
        # expression was False for every code, and a refused batch went round
        # the backoff and was resent unchanged on every pass, for ever.
        if e.code < 500:
            log(f"refused with HTTP {e.code} - dropping this batch")
            return None
        log(f"server error HTTP {e.code} - keeping this batch")
        return False
    except (urllib.error.URLError, OSError, ValueError) as e:
        log("could not submit:", e)
        return False


def flush(everything=False):
    # "off" means nothing further is sent, and that has to hold here, where
    # sending happens: "off" stops the unit, and the unit's ExecStop is
    # "send" - without this check, switching off handed over the whole queue.
    if not os.path.exists(MARKER):
        log("switched off - the queue is not sent")
        return 0
    lines = queue_read()
    if not lines:
        return 0
    if not on_wifi():
        log("not on Wi-Fi - the queue keeps")
        return 0

    sent = 0
    attempt = 0
    while lines and (everything or sent < BATCH):
        batch, rest = lines[:BATCH], lines[BATCH:]
        result = submit(batch)
        if result is None:              # refused, our fault - drop it
            lines = rest
            queue_write(lines)
            continue
        if not result:
            delay = BACKOFF_S[min(attempt, len(BACKOFF_S) - 1)]
            attempt += 1
            if attempt > len(BACKOFF_S):
                log("giving up for now - the queue keeps")
                break
            log(f"backing off {delay}s")
            time.sleep(delay)
            continue
        sent += len(batch)
        lines = rest
        queue_write(lines)
        attempt = 0
        s = load_stats()
        s["submitted"] = s.get("submitted", 0) + len(batch)
        s["last_submit"] = int(time.time())
        save_stats(s)
        if not everything:
            break
    return sent


# ---------------------------------------------------------------- measure

def overlap(aps, before):
    """Share of networks two scans have in common, 0 to 1."""
    now = {a["macAddress"] for a in aps}
    before = set(before or [])
    return len(now & before) / max(1, len(now | before))


def same_surroundings(aps, s):
    """Do these access points look like the ones from last time?

    A cheap stand-in for "has this phone moved". It exists because the honest
    test - compare the positions - needs a GNSS fix first, and a GNSS fix is
    the expensive thing here: the receiver is switched on for up to two minutes
    and draws tens of milliamps while it looks. Doing that on a phone lying on
    a table, every few minutes, only to throw the result away because it is
    two metres from the last one, is the kind of cost nobody notices until the
    battery is flat.

    The networks in range are already scanned by NetworkManager and cost
    nothing extra. When they are the same set, the phone is in the same place.
    """
    if not s.get("last_aps"):
        return False
    # Overlap rather than equality, so that a neighbour switching their router
    # off does not read as a move. It stays deliberately strict: at 0.8 a set
    # of six survives one network disappearing, but not one disappearing and
    # another appearing, which is already as likely to be a few steps as a
    # flickering signal. Measuring once too often costs a little power;
    # missing a move costs an observation, which is the point of all this.
    return overlap(aps, s["last_aps"]) >= 0.8


def measure(dry=False):
    """One observation, or a reason why there is none.

    The order is deliberate and is about power: everything that can rule a
    measurement out is asked before the GNSS receiver is switched on.
    """
    aps = scan_wifi()
    if len(aps) < MIN_APS:
        log(f"skipped: {len(aps)} usable access points, need {MIN_APS}")
        return None

    s = load_stats()
    last = s.get("last_position")
    # Cheap first: same networks and not long ago means the same place, and
    # there is nothing here a GNSS fix could add.
    if last and not dry:
        age = time.time() - last[2]
        if age < MIN_AGE_S and same_surroundings(aps, s):
            log(f"skipped: same networks as {age/60:.0f} min ago - "
                "not switching the receiver on")
            return None

    # Indoors there is never a fix, and looking for one every few minutes is
    # the worst case for the battery: the receiver runs and finds nothing. So
    # a run of failures stretches the wait between attempts - unless the
    # networks around have changed since the last failed one: then the phone
    # has moved, perhaps out of the building, and the next try is worth it.
    misses = s.get("gnss_misses", 0)
    if misses and not dry:
        next_try = s.get("gnss_next_try", 0)
        moved = (s.get("miss_aps") is not None
                 and overlap(aps, s["miss_aps"]) < MOVED_OVERLAP)
        if moved:
            log("other networks than at the last failed fix - trying now")
        elif time.time() < next_try:
            log(f"skipped: {misses} fixes in a row came to nothing, "
                f"waiting {int((next_try - time.time())/60)} min")
            return None

    # The scan above only decides whether the receiver is worth switching on.
    # The networks sent are scanned again after the fix: the fix can take up
    # to FIX_WAIT_S, and pairing it with networks from before it would put
    # them wherever the phone had got to by then.
    try:
        fix = gnss_fix(not_before=time.time())
    except GeolocationOff:
        return None
    if fix is None:
        s["gnss_misses"] = misses + 1
        # 3, 6, 12 ... minutes between attempts, up to MISS_PAUSE_MAX_S.
        delay = min(MISS_PAUSE_MAX_S, INTERVAL_S * (2 ** min(misses, 5)))
        s["gnss_next_try"] = time.time() + delay
        s["miss_aps"] = [a["macAddress"] for a in aps]
        save_stats(s)
        return None
    s["gnss_misses"] = 0
    s.pop("gnss_next_try", None)
    s.pop("miss_aps", None)
    pos, taken = fix

    aps = scan_wifi()
    late = time.time() - taken
    if late > SCAN_AFTER_FIX_S:
        log(f"skipped: the scan finished {late:.0f} s after the fix")
        save_stats(s)
        return None
    if len(aps) < MIN_APS:
        log(f"skipped: {len(aps)} usable access points at the fix, need {MIN_APS}")
        save_stats(s)
        return None

    if last:
        moved = distance_m((last[0], last[1]), (pos["latitude"], pos["longitude"]))
        age = time.time() - last[2]
        if moved < MIN_MOVE_M and age < MIN_AGE_S:
            log(f"skipped: {moved:.0f} m from the last one, {age/60:.0f} min ago")
            return None

    item = {"timestamp": int(taken * 1000),
            "position": pos, "wifiAccessPoints": aps}
    if dry:
        log(json.dumps(item, indent=2))
        return item

    queue_append(item)
    s["last_position"] = [pos["latitude"], pos["longitude"], time.time()]
    s["last_aps"] = [a["macAddress"] for a in aps]
    s["collected"] = s.get("collected", 0) + 1
    save_stats(s)
    log(f"queued: {len(aps)} access points, accuracy {pos['accuracy']:.0f} m")
    return item


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

def unit_ctl(action):
    """Switch our own user service on or off, if there is one.

    Never fatal: run from a checkout, or on a system where the unit was not
    installed, the marker is still the thing that decides - and "run" can be
    started by hand.
    """
    try:
        subprocess.run(["systemctl", "--user", action]
                       + (["--now"] if action in ("enable", "disable") else [])
                       + [UNIT],
                       capture_output=True, timeout=30)
    except (OSError, subprocess.SubprocessError):
        pass


def unit_state():
    """"enabled", "disabled", or None when systemd cannot be asked."""
    try:
        out = subprocess.run(["systemctl", "--user", "is-enabled", UNIT],
                             capture_output=True, text=True, timeout=30)
    except (OSError, subprocess.SubprocessError):
        return None
    word = out.stdout.strip()
    if word in ("enabled", "enabled-runtime", "linked", "linked-runtime",
                "alias"):
        return "enabled"
    if word in ("disabled", "static", "indirect", "masked", "not-found"):
        return "disabled"
    if not word and not out.stderr.strip():
        return "enabled" if out.returncode == 0 else "disabled"
    return None


def unit_before_on():
    """Write down the unit's state before the first "on" - once.

    Only from a phone that is switched off: a second "on" would otherwise
    write down our own "enable" as the original. And nothing is written when
    systemd cannot be asked (an ssh login without a user manager): a guess
    written down would look like a fact to "off" later.
    """
    if os.path.exists(UNIT_RECORD) or os.path.exists(MARKER):
        return
    state = unit_state()
    if state is None:
        return
    os.makedirs(STATE_DIR, exist_ok=True)
    with open(UNIT_RECORD, "w") as fh:
        fh.write(state + "\n")


def unit_back():
    """"off": the unit as "on" found it. Enabled before - by somebody, for a
    reason of their own - it stays enabled and is only stopped (without the
    marker it would exit at once anyway). Without a record, the old way:
    disabled, and said."""
    try:
        with open(UNIT_RECORD) as fh:
            before = fh.read().strip()
    except OSError:
        before = None
    if before == "enabled":
        unit_ctl("stop")
    else:
        unit_ctl("disable")
        if before is None:
            print("no record of the unit before \"on\" (switched on before "
                  "30.9.2026) - disabled it, as always")
    try:
        os.remove(UNIT_RECORD)
    except OSError:
        pass


def cmd_status():
    on = os.path.exists(MARKER)
    s = load_stats()
    queued = len(queue_read())
    print(f"contributing={'yes' if on else 'no'}")
    # Two different facts, and the app shows the difference: the marker says
    # what was asked for, the service says whether anything is happening.
    try:
        running = subprocess.run(["systemctl", "--user", "is-active", UNIT],
                                 capture_output=True, text=True,
                                 timeout=15).stdout.strip() == "active"
    except (OSError, subprocess.SubprocessError):
        running = False
    print(f"running={'yes' if running else 'no'}")
    print(f"queued={queued}")
    print(f"collected={s.get('collected', 0)}")
    print(f"submitted={s.get('submitted', 0)}")
    last = s.get("last_submit")
    print("last_submit=" + (time.strftime("%Y-%m-%d %H:%M", time.localtime(last))
                            if last else "never"))
    print(f"endpoint={ENDPOINT}")
    print()
    print("Sent only over Wi-Fi, only from a GNSS fix, and never networks that")
    print("are hidden or whose name ends in _nomap or _optout.")
    return 0


def cmd_run():
    if not os.path.exists(MARKER):
        log("not switched on - nothing to do")
        return 0
    log(f"contributing to {ENDPOINT} every {INTERVAL_S}s")
    while True:
        if not os.path.exists(MARKER):
            log("switched off - stopping")
            return 0
        try:
            measure()
            flush()
        except Exception as e:              # noqa: BLE001 - a loop that dies is worse
            log("pass failed:", e)
        time.sleep(INTERVAL_S)


def main():
    cmd = sys.argv[1] if len(sys.argv) > 1 else "status"
    if cmd == "status":
        return cmd_status()
    if cmd == "on":
        os.makedirs(STATE_DIR, exist_ok=True)
        unit_before_on()                # before anything changes
        open(MARKER, "w").close()
        # The marker alone changes nothing: after an installation the service
        # is neither enabled nor running - everything is off until somebody
        # switches it on. enable --now starts it and keeps it across logins.
        unit_ctl("enable")
        print("on - collecting")
        return 0
    if cmd == "off":
        try:
            os.remove(MARKER)
        except OSError:
            pass
        # The loop notices the marker is gone and stops by itself within an
        # interval; stopping it now means "off" is true when it says so.
        unit_back()
        print("off - nothing further is collected or sent")
        return 0
    if cmd == "once":
        return 0 if measure(dry="--dry-run" in sys.argv) else 1
    if cmd == "send":
        n = flush(everything=True)
        print(f"submitted {n}")
        return 0
    if cmd == "run":
        return cmd_run()
    print("usage: furios-gps-contribute [status|on|off|once [--dry-run]|send|run]",
          file=sys.stderr)
    return 1


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