#!/usr/bin/python3
# SPDX-License-Identifier: MIT
"""waydroid-plinius-stores: the app stores in the user's Android, for Settings' Android page.

Runs as the user whose Android it is (no root: Waydroid's "app install", "app remove" and
"app list" talk to the user's Android session). The stores come from a list in the package
(/usr/share/waydroid-plinius/stores.json): each APK is fixed by its SHA-256 and size and is
downloaded only over https; once a store is in Android it updates itself.

  list --json   the stores and whether each is in Android: asked of Android while it runs,
                otherwise what was seen last (installed is null if that is not known)
  install ID    the store into Android (Android starts first if it does not run)
  remove ID     the store out of Android; the apps it installed stay
  defaults      every store marked "default" that Android does not have yet (after a set-up or
                reset of Android)
  repo ID       asks the store of a catalog (IzzyOnDroid for F-Droid) to add it: the store
                shows its own question, the user decides there
  start         starts Android and waits until it has booted (after Google's services changed:
                whether Android comes up with them)

Progress for Settings on stdout: "step NAME" as a step begins (start: Android starts; download;
install; remove) and "bytes DONE TOTAL" while a download runs; defaults prints only "step
stores".

Exit: 0 done, 6 nothing to do, 4 the store could not be downloaded, 5 Android did not start,
1 an error (a download that does not match, Android did not take the store), 2 bad arguments.
"""

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

STORES = "/usr/share/waydroid-plinius/stores.json"
# How long Android may take to start (a first start after a set-up or reset takes the longest),
# and to show an installed or removed store
START_TIMEOUT = 300
SETTLE_TIMEOUT = 30
POLL = 3
CHUNK = 256 * 1024
NET_TIMEOUT = 30

EXIT_DONE = 0
EXIT_ERROR = 1
EXIT_USAGE = 2
EXIT_UNREACHABLE = 4
EXIT_NOT_STARTED = 5
EXIT_NOTHING = 6

ID = re.compile(r"[a-z0-9]+")
PACKAGE = re.compile(r"[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+")
SHA256 = re.compile(r"[0-9a-f]{64}")


class Mismatch(Exception):
    """A download that is not the store's APK."""


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


def step(name):
    print("step " + name, flush=True)


def data_home():
    return os.environ.get("XDG_DATA_HOME") or os.path.join(os.path.expanduser("~"), ".local", "share")


def cache_dir():
    base = os.environ.get("XDG_CACHE_HOME") or os.path.join(os.path.expanduser("~"), ".cache")
    return os.path.join(base, "waydroid-plinius", "stores")


def state_file():
    # Inside the user's Android data: a reset of Android takes it along
    return os.path.join(data_home(), "waydroid", "plinius-stores.json")


def load_list(path=None):
    """(stores, repos) of the package's list; only entries that are well-formed."""
    with open(path or STORES, encoding="utf-8") as f:
        data = json.load(f)
    stores = []
    for s in data.get("stores", []):
        if (isinstance(s, dict) and isinstance(s.get("id"), str) and ID.fullmatch(s["id"])
                and isinstance(s.get("name"), str) and isinstance(s.get("package"), str)
                and PACKAGE.fullmatch(s["package"]) and isinstance(s.get("sha256"), str)
                and SHA256.fullmatch(s["sha256"]) and isinstance(s.get("size"), int) and s["size"] > 0
                and isinstance(s.get("urls"), list) and s["urls"]
                and all(isinstance(u, str) and u.startswith("https://") for u in s["urls"])):
            stores.append(s)
        else:
            log(f"skipping a malformed store: {s!r:.80}")
    repos = [r for r in data.get("repos", []) if isinstance(r, dict) and isinstance(r.get("id"), str)
             and isinstance(r.get("store"), str) and isinstance(r.get("uri"), str)
             and r["uri"].startswith("fdroidrepos://")]
    return stores, repos


# ----- Android -----

def waydroid(*args, timeout=120):
    """(exit code, stdout) of waydroid ARGS; (127, "") when it cannot run, (124, "") on a timeout."""
    try:
        r = subprocess.run(["waydroid", *args], capture_output=True, text=True, timeout=timeout)
    except OSError:
        return 127, ""
    except subprocess.TimeoutExpired:
        return 124, ""
    return r.returncode, r.stdout


def session_running():
    code, out = waydroid("status", timeout=30)
    for line in out.splitlines():
        key, sep, value = line.partition(":")
        if sep and key.strip() == "Session":
            return value.strip() == "RUNNING"
    return False


def packages():
    """The packages of Android's apps, or None while Android cannot tell (not running, booting)."""
    code, out = waydroid("app", "list")
    found = {line.split(":", 1)[1].strip() for line in out.splitlines() if line.startswith("packageName:")}
    # Android always has apps (its settings at least): none means it did not answer
    return found or None


def start_android(steps=True):
    """Android's packages once it runs, starting its session if need be; None if it does not come."""
    found = packages() if session_running() else None
    if found is not None:
        return found
    if steps:
        step("start")
    if not session_running():
        try:
            # The session lives on after this helper (as when an Android app starts it)
            subprocess.Popen(["waydroid", "session", "start"], stdin=subprocess.DEVNULL,
                             stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
        except OSError as e:
            log(f"cannot start Android: {e}")
            return None
    deadline = time.monotonic() + START_TIMEOUT
    while time.monotonic() < deadline:
        time.sleep(POLL)
        found = packages() if session_running() else None
        if found is not None:
            return found
    log("Android did not start")
    return None


def save_state(found):
    path = state_file()
    try:
        os.makedirs(os.path.dirname(path), exist_ok=True)
        tmp = path + ".tmp"
        with open(tmp, "w", encoding="utf-8") as f:
            json.dump({"packages": sorted(found)}, f)
        os.replace(tmp, path)
    except OSError as e:
        log(f"cannot keep what Android has: {e}")


def saved_state():
    try:
        with open(state_file(), encoding="utf-8") as f:
            found = json.load(f).get("packages")
    except (OSError, ValueError, AttributeError):
        return None
    return set(found) if isinstance(found, list) else None


def wait_for(package, present):
    """Android's packages once package is there (present) or gone; None after the timeout."""
    deadline = time.monotonic() + SETTLE_TIMEOUT
    while True:
        found = packages()
        if found is not None and (package in found) == present:
            return found
        if time.monotonic() >= deadline:
            return None
        time.sleep(1)


# ----- Downloads -----

def fetch(url, dest, store):
    """Downloads url to dest; Mismatch if it is not the store's APK, OSError if it cannot be had."""
    want, size = store["sha256"], store["size"]
    digest = hashlib.sha256()
    done = 0
    with urllib.request.urlopen(url, timeout=NET_TIMEOUT) as r:
        # A redirect may only lead to https as well
        if not r.geturl().startswith("https://"):
            raise Mismatch(f"{url} leads to {r.geturl()}")
        with open(dest, "wb") as f:
            print(f"bytes 0 {size}", flush=True)
            while True:
                chunk = r.read(CHUNK)
                if not chunk:
                    break
                done += len(chunk)
                if done > size:
                    raise Mismatch(f"{url} is larger than {size} bytes")
                digest.update(chunk)
                f.write(chunk)
                print(f"bytes {done} {size}", flush=True)
    if done != size or digest.hexdigest() != want:
        raise Mismatch(f"{url} is not the APK of {store['name']} (SHA-256 {digest.hexdigest()})")


def download(store):
    """The store's APK in the cache, checked; None if it could not be had (Mismatch if what came is
    not it)."""
    folder = cache_dir()
    os.makedirs(folder, mode=0o700, exist_ok=True)
    path = os.path.join(folder, store["id"] + ".apk")
    if os.path.isfile(path) and os.path.getsize(path) == store["size"]:
        with open(path, "rb") as f:
            if hashlib.sha256(f.read()).hexdigest() == store["sha256"]:
                return path
    part = path + ".part"
    mismatch = None
    for url in store["urls"]:
        try:
            fetch(url, part, store)
            os.replace(part, path)
            return path
        except Mismatch as e:
            log(str(e))
            mismatch = e
        except (OSError, urllib.error.URLError, ValueError) as e:
            log(f"{url}: {e}")
        try:
            os.unlink(part)
        except FileNotFoundError:
            pass
    if mismatch:
        raise mismatch
    return None


def forget(path):
    try:
        os.unlink(path)
    except OSError:
        pass


# ----- Commands -----

def listing(stores):
    found = packages() if session_running() else None
    running = found is not None
    if running:
        save_state(found)
    else:
        found = saved_state()
    print(json.dumps({
        "running": running,
        "stores": [{"id": s["id"], "name": s["name"], "package": s["package"],
                    "default": bool(s.get("default")),
                    "installed": None if found is None else s["package"] in found}
                   for s in stores],
    }))
    return EXIT_DONE


def put_in(store, steps=True):
    """Downloads and installs store; the exit code."""
    if steps:
        step("download")
    try:
        apk = download(store)
    except Mismatch:
        return EXIT_ERROR
    if apk is None:
        return EXIT_UNREACHABLE
    if steps:
        step("install")
    waydroid("app", "install", apk, timeout=300)
    found = wait_for(store["package"], True)
    if found is None:
        log(f"Android did not take {store['name']}")
        return EXIT_ERROR
    save_state(found)
    # Android has its own copy now
    forget(apk)
    return EXIT_DONE


def install(store):
    found = start_android()
    if found is None:
        return EXIT_NOT_STARTED
    if store["package"] in found:
        save_state(found)
        return EXIT_NOTHING
    return put_in(store)


def remove(store):
    found = start_android()
    if found is None:
        return EXIT_NOT_STARTED
    if store["package"] not in found:
        save_state(found)
        return EXIT_NOTHING
    step("remove")
    waydroid("app", "remove", store["package"])
    found = wait_for(store["package"], False)
    if found is None:
        log(f"Android did not remove {store['name']}")
        return EXIT_ERROR
    save_state(found)
    return EXIT_DONE


def defaults(stores):
    step("stores")
    found = start_android(steps=False)
    if found is None:
        return EXIT_NOT_STARTED
    missing = [s for s in stores if s.get("default") and s["package"] not in found]
    if not missing:
        save_state(found)
        return EXIT_NOTHING
    worst = EXIT_DONE
    for store in missing:
        code = put_in(store, steps=False)
        if code != EXIT_DONE:
            # The others still come; the first failure is what is told
            worst = worst or code
    return worst


def add_repo(repo, stores):
    store = next((s for s in stores if s["id"] == repo["store"]), None)
    if store is None:
        log(f"no store {repo['store']} for {repo['id']}")
        return EXIT_ERROR
    found = start_android()
    if found is None:
        return EXIT_NOT_STARTED
    if store["package"] not in found:
        log(f"{store['name']} is not in Android")
        return EXIT_ERROR
    # The store asks the user itself whether to add the catalog
    code, _ = waydroid("app", "intent", "android.intent.action.VIEW", repo["uri"], timeout=60)
    return EXIT_DONE if code == 0 else EXIT_ERROR


def main(argv):
    args = argv[1:]
    try:
        stores, repos = load_list()
    except (OSError, ValueError) as e:
        log(f"cannot read {STORES}: {e}")
        return EXIT_ERROR
    by_id = {s["id"]: s for s in stores}
    if args == ["list", "--json"]:
        return listing(stores)
    if args == ["defaults"]:
        return defaults(stores)
    if args == ["start"]:
        return EXIT_DONE if start_android() is not None else EXIT_NOT_STARTED
    if len(args) == 2 and args[0] in ("install", "remove") and args[1] in by_id:
        return install(by_id[args[1]]) if args[0] == "install" else remove(by_id[args[1]])
    if len(args) == 2 and args[0] == "repo":
        repo = next((r for r in repos if r["id"] == args[1]), None)
        if repo is not None:
            return add_repo(repo, stores)
    print("usage: waydroid-plinius-stores list --json | install ID | remove ID | defaults | repo ID | start",
          file=sys.stderr)
    return EXIT_USAGE


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