#!/usr/bin/python3
# SPDX-License-Identifier: MIT
"""plinius-android-image: Android's image for Waydroid, updated with the phone's system updates.

Our LineageOS build for Waydroid (system.img, vendor.img) is published next to the packages of
[plinius] (tools/publish-android.sh): android.json describes it, the signed stamp of the channel
names android.json by its SHA-256 (plinius-repo-stamp android), and android.json names each
image's file, size and SHA-256 and the SHA-256 of the image itself. So an image is taken only
from the configured channel, signed with the repo key, no older than one seen before, and
exactly as published. Android itself never chooses an image (its root would decide what the
phone mounts). A stamp older than plinius-repo-stamp allows ("stale") vouches for nothing here:
a server that keeps handing out an old, genuine stamp would hold the phone on an old image
with known holes. check and available report it as "stale_stamp" (with "days"), and nothing is
installed until the channel's stamp is current again.

  check [--json]  as any user (Settings' Updates page, the update timer): whether the channel
                  has an image other than the one Waydroid has; prints JSON with --json
  available [--json]
                  as any user (Settings' Android page): what the channel has, also before
                  Android is set up: versions, the size of the download and of the images
  upgrade [--progress]
                  as root (plinius-pkg upgrade): downloads the images, checks each against
                  android.json, and puts them in place of Waydroid's images. A running Android
                  keeps the old ones (they stay open until it stops) and starts with the new
                  ones the next time.
  install [--progress]
                  as root (waydroid-plinius-manage setup), only before Android is set up: the
                  same for the first image, into /etc/waydroid-extra/images, where waydroid init
                  takes it from.

All downloads come first, then each image is unpacked and checked. --progress prints "step
download", "bytes DONE TOTAL" and "step unpack" on stdout for Settings' progress page.

check and upgrade work only where Android is set up (Waydroid's images_path with system.img and
vendor.img); nothing else changes here. Which image Waydroid has is known by the SHA-256 of its
images, kept in STATE (written by upgrade and install) and, for a check, worked out once and
cached where no STATE says it.

Exit: 0 an update (check), an image (available) or updated (upgrade, install), 6 nothing to do
(no Android, no image in the channel, the same image, Android set up already for install), 1 an
error (a stale stamp too), 4 the update server did not hand out the description.
"""

import configparser
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.request

STAMP = "/usr/lib/plinius-software/plinius-repo-stamp"
WAYDROID_CFG = "/var/lib/waydroid/waydroid.cfg"
# Which image Waydroid has, written by upgrade: per image its SHA-256, size and mtime
STATE = "/var/lib/waydroid/plinius-android.json"
CACHE = "/var/cache/plinius-android"
# Where waydroid init looks for images first (Waydroid's preinstalled_images_paths)
PREINSTALLED = "/etc/waydroid-extra/images"
IMAGES = ("system", "vendor")
USER_AGENT = "Plinius Arch Linux"
TIMEOUT = 60
# A description that does not match its stamp may be an upload switching them over
RETRY_DELAY = 5
# Room left over besides the images, so that Android's data and the system keep some
SPARE = 512 * 1024 * 1024
MAX_IMAGE = 8 * 1024 ** 3
HEX64 = re.compile(r"^[0-9a-f]{64}$")
CHUNK = 1 << 20
# Seconds between two progress lines of a download
PROGRESS_INTERVAL = 0.25

EXIT_UPDATE = 0
EXIT_NOTHING = 6
EXIT_ERROR = 1
EXIT_UNREACHABLE = 4
# The verdict of plinius-repo-stamp on a genuine stamp that is too old, and what check and
# available report for it: Settings' Android page takes "stale" for up to date, and shows
# "cannot be checked" for a result it does not know
STALE = "stale"
STALE_STAMP = "stale_stamp"


def log(text):
    print("plinius-android-image: " + text, file=sys.stderr, flush=True)


def images_dir():
    """Waydroid's images directory when Android is set up there, else None."""
    cfg = configparser.ConfigParser()
    try:
        cfg.read(WAYDROID_CFG)
        path = cfg.get("waydroid", "images_path")
    except (configparser.Error, OSError):
        return None
    if all(os.path.isfile(os.path.join(path, name + ".img")) for name in IMAGES):
        return path
    return None


def sha256(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for block in iter(lambda: f.read(CHUNK), b""):
            h.update(block)
    return h.hexdigest()


def read_json(path):
    try:
        with open(path, encoding="utf-8") as f:
            data = json.load(f)
    except (OSError, ValueError):
        return {}
    return data if isinstance(data, dict) else {}


def write_json(path, data):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    fd, tmp = tempfile.mkstemp(prefix=".plinius-android.", dir=os.path.dirname(path))
    with os.fdopen(fd, "w", encoding="utf-8") as f:
        json.dump(data, f, indent=1, sort_keys=True)
        f.write("\n")
    os.chmod(tmp, 0o644)
    os.replace(tmp, path)


def user_cache():
    base = os.environ.get("XDG_CACHE_HOME") or os.path.join(os.path.expanduser("~"), ".cache")
    return os.path.join(base, "plinius-software", "android-installed.json")


def installed(images):
    """{name: SHA-256} of Waydroid's images, from STATE (or the user's cache) while size and
    mtime still match, else worked out (and kept where this user may write)."""
    known = {}
    for path in (STATE, user_cache()):
        for name, entry in read_json(path).get("images", {}).items():
            if isinstance(entry, dict) and name not in known:
                known[name] = entry
    result, entries, worked_out = {}, {}, False
    for name in IMAGES:
        st = os.stat(os.path.join(images, name + ".img"))
        entry = known.get(name, {})
        if entry.get("size") == st.st_size and entry.get("mtime") == st.st_mtime_ns and HEX64.match(str(entry.get("sha256"))):
            result[name] = entry["sha256"]
        else:
            result[name] = sha256(os.path.join(images, name + ".img"))
            worked_out = True
        entries[name] = {"sha256": result[name], "size": st.st_size, "mtime": st.st_mtime_ns}
    if worked_out:
        try:
            write_json(STATE if os.geteuid() == 0 else user_cache(), dict(read_json(STATE), images=entries))
        except OSError as e:
            log(f"cannot keep the hashes of the images: {e}")
    return result


def valid(manifest):
    """The description as published (tools/publish-android.sh), or None."""
    try:
        if manifest.get("format") != 1 or not isinstance(manifest.get("built"), int):
            return None
        for key in ("version", "lineage", "android", "security_patch"):
            if not re.fullmatch(r"[0-9A-Za-z._-]{1,40}", str(manifest.get(key, ""))):
                return None
        for name in IMAGES:
            image = manifest["images"][name]
            if not re.fullmatch(r"android/[0-9A-Za-z._-]+", image["file"]) or ".." in image["file"]:
                return None
            if not (HEX64.match(image["sha256"]) and HEX64.match(image["image_sha256"])):
                return None
            for size in ("size", "image_size"):
                if not isinstance(image[size], int) or not 0 < image[size] <= MAX_IMAGE:
                    return None
    except (KeyError, TypeError, AttributeError):
        return None
    return manifest


def description(out, user_state=None):
    """(verdict of plinius-repo-stamp android, description or None); a description that does
    not match its stamp is fetched once more. Only a current stamp ("ok") gives a description:
    a stale one could be a server frozen on an old image."""
    command = [STAMP, "android", "--out", out]
    if user_state:
        command += ["--user-state", user_state]
    verdict = {}
    for attempt in range(2):
        try:
            r = subprocess.run(command, capture_output=True, text=True, timeout=180)
            verdict = json.loads(r.stdout)
        except (OSError, ValueError, subprocess.TimeoutExpired) as e:
            verdict = {"result": "failed", "message": str(e)}
        if not isinstance(verdict, dict):
            verdict = {"result": "failed", "message": "no verdict"}
        if verdict.get("result") != "android_mismatch" or attempt:
            break
        time.sleep(RETRY_DELAY)
    if verdict.get("result") != "ok":
        return verdict, None
    return verdict, valid(read_json(out))


def reported(verdict, manifest):
    """The result check and available report for a verdict: "malformed" for a current stamp
    without a usable description, STALE_STAMP for a stale one."""
    result = verdict.get("result", "failed")
    if result == "ok" and manifest is None:
        return "malformed"
    return STALE_STAMP if result == STALE else result


def stale_days(verdict):
    days = verdict.get("days")
    return days if isinstance(days, int) and not isinstance(days, bool) and days >= 0 else None


def summary(manifest):
    return {k: manifest[k] for k in ("version", "lineage", "android", "security_patch", "built")}


def check(as_json):
    images = images_dir()
    result = {"update": False, "installed": None, "available": None}
    if images is None:
        result["result"] = "noandroid"
    else:
        runtime = os.environ.get("XDG_RUNTIME_DIR") or tempfile.gettempdir()
        out = os.path.join(CACHE if os.geteuid() == 0 else os.path.join(runtime, "plinius-software"), "android.json")
        os.makedirs(os.path.dirname(out), exist_ok=True)
        state = None if os.geteuid() == 0 else os.path.join(
            os.environ.get("XDG_STATE_HOME") or os.path.join(os.path.expanduser("~"), ".local", "state"),
            "plinius-software", "repo-stamp")
        verdict, manifest = description(out, state)
        result["result"] = reported(verdict, manifest)
        if result["result"] == STALE_STAMP:
            result["days"] = stale_days(verdict)
        if manifest is not None:
            have = installed(images)
            result["available"] = dict(summary(manifest), download=sum(manifest["images"][n]["size"] for n in IMAGES))
            st = read_json(STATE)
            if all(have[n] == manifest["images"][n]["image_sha256"] for n in IMAGES):
                result["installed"] = summary(manifest)
            else:
                result["installed"] = st.get("installed") if isinstance(st.get("installed"), dict) else None
                result["update"] = True
    if as_json:
        print(json.dumps(result))
    else:
        print(f"Android image: {result['result']}, update: {'yes' if result['update'] else 'no'}")
    if result["update"]:
        return EXIT_UPDATE
    return EXIT_UNREACHABLE if result["result"] == "android_unreachable" else (
        EXIT_NOTHING if result["result"] in ("noandroid", "ok", "skip", "none") else EXIT_ERROR)


class Progress:
    """Machine-readable progress on stdout for Settings (--progress): "step NAME" as a step
    begins, "bytes DONE TOTAL" while a download runs (at most every PROGRESS_INTERVAL seconds,
    and once at its end). Without --progress it says nothing."""

    def __init__(self, on):
        self.on = on
        self.last = float("-inf")

    def step(self, name):
        if self.on:
            print("step " + name, flush=True)

    def bytes(self, done, total, final=False):
        if not self.on:
            return
        now = time.monotonic()
        if final or now - self.last >= PROGRESS_INTERVAL:
            self.last = now
            print(f"bytes {done} {total}", flush=True)


def download(url, path, size, digest, counted=None):
    """The file at url to path, at most size bytes, with the SHA-256 digest; raises OSError.
    counted(n) is told of every block of n bytes."""
    h = hashlib.sha256()
    got = 0
    request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
    with urllib.request.urlopen(request, timeout=TIMEOUT) as response, open(path, "wb") as f:
        while True:
            block = response.read(CHUNK)
            if not block:
                break
            got += len(block)
            if got > size:
                raise OSError(f"{url} is larger than its description says")
            h.update(block)
            f.write(block)
            if counted:
                counted(len(block))
    if got != size or h.hexdigest() != digest:
        raise OSError(f"{url} is not the file its description names")


def channel_description():
    """(verdict, description) of the update channel as root (CACHE), or an exit code for a
    channel without a usable description (logged)."""
    os.makedirs(CACHE, mode=0o755, exist_ok=True)
    verdict, manifest = description(os.path.join(CACHE, "android.json"))
    result = verdict.get("result")
    if result in ("noandroid", "skip", "none"):
        log("the update channel has no Android image")
        return EXIT_NOTHING
    if result == STALE:
        days = stale_days(verdict)
        log("the signed stamp of the update channel is %s old: no Android image is installed until "
            "it is current again" % ("%d days" % days if days is not None else "too"))
        return EXIT_ERROR
    if result != "ok":
        log(verdict.get("message") or f"the description of the Android image could not be had ({result})")
        return EXIT_UNREACHABLE if result in ("android_unreachable", "unreachable", "http", "missing") else EXIT_ERROR
    if manifest is None:
        log("the description of the Android image is malformed")
        return EXIT_ERROR
    return verdict, manifest


def fetch(verdict, manifest, wanted, images, progress):
    """The wanted images of the description into images, each checked: first all downloads
    into CACHE, then each unpacked next to its final name (.NAME.img.new) and checked again.
    Returns the exit code: EXIT_UPDATE once every one is in place under its name (each by a
    rename, so a running Android keeps the file it has open) and in STATE."""
    need_cache = sum(manifest["images"][n]["size"] for n in wanted)
    need_images = sum(manifest["images"][n]["image_size"] for n in wanted)
    for path, need in ((CACHE, need_cache), (images, need_images)):
        if shutil.disk_usage(path).free < need + SPARE:
            log(f"not enough space in {path} for the Android image ({need // 1048576} MiB and some to spare)")
            return EXIT_ERROR
    server = str(verdict.get("server", "")).rstrip("/")
    if not server.startswith("https://"):
        log("no https server for the Android image")
        return EXIT_ERROR
    packed = {n: os.path.join(CACHE, n + ".img.zst") for n in wanted}
    staged = []
    done = 0

    def counted(n):
        nonlocal done
        done += n
        progress.bytes(done, need_cache)

    try:
        progress.step("download")
        for name in wanted:
            image = manifest["images"][name]
            log(f"downloading the {name} image ({image['size'] // 1048576} MiB)")
            download(server + "/" + image["file"], packed[name], image["size"], image["sha256"], counted)
        progress.bytes(done, need_cache, final=True)
        progress.step("unpack")
        for name in wanted:
            image = manifest["images"][name]
            target = os.path.join(images, "." + name + ".img.new")
            staged.append(target)
            log(f"unpacking the {name} image")
            subprocess.run(["zstd", "-d", "-q", "-f", "--long=27", "-o", target, packed[name]], check=True, timeout=3600)
            os.remove(packed[name])
            if os.path.getsize(target) != image["image_size"] or sha256(target) != image["image_sha256"]:
                raise OSError(f"the unpacked {name} image is not the one described")
            os.chmod(target, 0o644)
    except (OSError, urllib.error.URLError, subprocess.SubprocessError, ValueError) as e:
        log(f"the Android image was not put in place: {e}")
        for path in staged + list(packed.values()):
            try:
                os.remove(path)
            except OSError:
                pass
        return EXIT_UNREACHABLE if isinstance(e, urllib.error.URLError) else EXIT_ERROR
    entries = dict(read_json(STATE).get("images", {}))
    for name, target in zip(wanted, staged):
        final = os.path.join(images, name + ".img")
        os.replace(target, final)
        st = os.stat(final)
        entries[name] = {"sha256": manifest["images"][name]["image_sha256"], "size": st.st_size, "mtime": st.st_mtime_ns}
    write_json(STATE, {"images": entries, "installed": summary(manifest)})
    return EXIT_UPDATE


def upgrade(progress):
    if os.geteuid() != 0:
        log("upgrade needs root")
        return EXIT_ERROR
    images = images_dir()
    if images is None:
        log("Android is not set up, nothing to update")
        return EXIT_NOTHING
    got = channel_description()
    if isinstance(got, int):
        return got
    verdict, manifest = got
    have = installed(images)
    if all(have[n] == manifest["images"][n]["image_sha256"] for n in IMAGES):
        log(f"Android {manifest['version']} is already in place")
        return EXIT_NOTHING
    wanted = [n for n in IMAGES if have[n] != manifest["images"][n]["image_sha256"]]
    code = fetch(verdict, manifest, wanted, images, progress)
    if code == EXIT_UPDATE:
        log(f"Android {manifest['android']} (LineageOS {manifest['lineage']}, security update "
            f"{manifest['security_patch']}) is in place as {manifest['version']}; it is used from Android's next start")
    return code


def install(progress):
    """The channel's image where Waydroid looks for one first (PREINSTALLED), for Android's
    first set-up (waydroid-plinius-manage setup runs waydroid init afterwards). An image that is
    there already and is the described one is kept."""
    if os.geteuid() != 0:
        log("install needs root")
        return EXIT_ERROR
    if images_dir() is not None:
        log("Android is set up already; its image comes with the updates")
        return EXIT_NOTHING
    got = channel_description()
    if isinstance(got, int):
        return got
    verdict, manifest = got
    os.makedirs(PREINSTALLED, mode=0o755, exist_ok=True)
    wanted = []
    for name in IMAGES:
        path = os.path.join(PREINSTALLED, name + ".img")
        image = manifest["images"][name]
        if not (os.path.isfile(path) and os.path.getsize(path) == image["image_size"]
                and sha256(path) == image["image_sha256"]):
            wanted.append(name)
    if not wanted:
        st = {n: os.stat(os.path.join(PREINSTALLED, n + ".img")) for n in IMAGES}
        write_json(STATE, {"images": {n: {"sha256": manifest["images"][n]["image_sha256"], "size": st[n].st_size,
                                          "mtime": st[n].st_mtime_ns} for n in IMAGES},
                           "installed": summary(manifest)})
        log(f"Android {manifest['version']} is already in place")
        return EXIT_UPDATE
    code = fetch(verdict, manifest, wanted, PREINSTALLED, progress)
    if code == EXIT_UPDATE:
        log(f"Android {manifest['android']} (LineageOS {manifest['lineage']}, security update "
            f"{manifest['security_patch']}) is in place as {manifest['version']}")
    return code


def available(as_json):
    """What the channel has, whether or not Android is set up (Settings' Android page before
    the set-up): its versions and the sizes of the download and of the images."""
    runtime = os.environ.get("XDG_RUNTIME_DIR") or tempfile.gettempdir()
    out = os.path.join(CACHE if os.geteuid() == 0 else os.path.join(runtime, "plinius-software"), "android.json")
    os.makedirs(os.path.dirname(out), exist_ok=True)
    state = None if os.geteuid() == 0 else os.path.join(
        os.environ.get("XDG_STATE_HOME") or os.path.join(os.path.expanduser("~"), ".local", "state"),
        "plinius-software", "repo-stamp")
    verdict, manifest = description(out, state)
    result = {"result": reported(verdict, manifest), "available": None}
    if result["result"] == STALE_STAMP:
        result["days"] = stale_days(verdict)
    if manifest is not None:
        result["available"] = dict(summary(manifest),
                                   download=sum(manifest["images"][n]["size"] for n in IMAGES),
                                   size=sum(manifest["images"][n]["image_size"] for n in IMAGES))
    if as_json:
        print(json.dumps(result))
    else:
        print(f"Android image: {result['result']}" +
              (f", {result['available']['version']}" if result["available"] else ""))
    if manifest is not None:
        return EXIT_UPDATE
    return EXIT_UNREACHABLE if result["result"] in ("android_unreachable", "unreachable", "http", "missing") else (
        EXIT_NOTHING if result["result"] in ("noandroid", "skip", "none") else EXIT_ERROR)


def main(argv):
    args = argv[1:]
    if args in (["check"], ["check", "--json"]):
        return check(args[-1] == "--json")
    if args in (["available"], ["available", "--json"]):
        return available(args[-1] == "--json")
    if args in (["upgrade"], ["upgrade", "--progress"], ["install"], ["install", "--progress"]):
        progress = Progress(args[-1] == "--progress")
        return upgrade(progress) if args[0] == "upgrade" else install(progress)
    print("usage: plinius-android-image check [--json] | available [--json] | upgrade [--progress] | "
          "install [--progress]", file=sys.stderr)
    return EXIT_ERROR


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