#!/usr/bin/python3
# SPDX-License-Identifier: MIT
"""waydroid-plinius-google: Google's services in Android, for Settings' Android page.

Android here comes without Google's services. The user chooses one variant for the whole phone
(Android's system is shared by every user):

  none     no Google services
  microg   microG (GmsCore, Companion), a free replacement; signed with microG's own key, which
           LineageOS lets show Google's signature, and nothing else does
  google   Google's own services and the Play Store (GmsCore, GoogleServicesFramework, Phonesky
           and what they need), the members listed here of MindTheGapps' zip

They go into Android's system as privileged apps through Waydroid's overlay
(/var/lib/waydroid/overlay/system, which Android sees as /system): no second image. Android
enforces its list of privileged permissions (ro.control_privapp_permissions=enforce), so every
variant brings its permission files, which go in before the apps and out after them. Every file
is fixed by its SHA-256 and size in /usr/share/waydroid-plinius/google.json and comes only over
https; of Google's zip only the members listed are read (HTTP ranges).

  status --json   the variant in use, the last one whose data Android may hold, and what each one
                  downloads (any user)
  set VARIANT     switches to VARIANT (root, through pkexec: an administrator's PIN): downloads
                  and checks it, stops Android, takes the old variant out of the overlay and
                  puts the new one in. When microG follows Google or the other way round (also
                  with "none" between them and no start of Android), the data of their apps goes
                  in every user's Android (their accounts there too): the other variant's data
                  does not fit. Updates of the old variant's apps that Android installed by
                  itself (the Play Store updates itself and GmsCore) go as well, also unfinished
                  ones: without the system app they would stay behind as apps of their own.
                  Android starts with the new variant at the next Android app.

Progress for Settings on stdout: "step NAME" as a step begins (download, stop, install, data)
and "bytes DONE TOTAL" while the download runs.

Exit: 0 done, 6 nothing to do (the variant is in use already), 4 a download could not be had,
1 an error (a download that does not match, Android does not stop), 2 bad arguments.
"""

import fcntl
import hashlib
import io
import json
import os
import pwd
import shutil
import stat
import subprocess
import sys
import urllib.error
import urllib.request
import zipfile

LIST = "/usr/share/waydroid-plinius/google.json"
DATA = "/usr/share/waydroid-plinius"
OVERLAY = "/var/lib/waydroid/overlay"
STATE = "/var/lib/waydroid/plinius-google.json"
LOCK = "/var/lib/waydroid/plinius-google.lock"
CACHE = "/var/cache/plinius-android/google"
LXC_PATH = "/var/lib/waydroid/lxc"
STOP = ["gdbus", "call", "--system", "--dest", "id.waydro.Container", "--object-path", "/ContainerManager",
        "--method", "id.waydro.ContainerManager.Stop", "true"]
# A user's Android data and, in it, where an app's data lives
USER_DATA = (".local", "share", "waydroid", "data")
APP_DATA = (("data",), ("user_de", "0"))
# Google's apps under either variant: their data goes when the variant changes between the two
PACKAGES = ("com.google.android.gms", "com.google.android.gsf", "com.android.vending")
# Where Android keeps the apps it installed itself (updates of system apps among them):
# app/~~<random>==/<package>-<random>==, and unfinished installations app/vmdl<n>.tmp/<package>.apk
USER_APPS = USER_DATA + ("app",)
CHUNK = 1 << 20
NET_TIMEOUT = 60

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


class Mismatch(Exception):
    """A download that is not the file of the list."""


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


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


def load_list():
    with open(LIST, encoding="utf-8") as f:
        variants = json.load(f)["variants"]
    return {v["id"]: v for v in variants}


def read_state():
    try:
        with open(STATE, encoding="utf-8") as f:
            state = json.load(f)
    except (OSError, ValueError):
        return {"variant": "none", "files": []}
    if not isinstance(state, dict) or not isinstance(state.get("files"), list):
        return {"variant": "none", "files": []}
    return state


def write_state(state):
    tmp = STATE + ".new"
    with open(tmp, "w", encoding="utf-8") as f:
        json.dump(state, f, indent=1)
    os.chmod(tmp, 0o644)
    os.replace(tmp, STATE)


def is_app(target):
    """Apps (priv-app, app, resource overlays) as opposed to the files that allow them."""
    parts = target.split("/")
    return any(p in ("priv-app", "app", "overlay") for p in parts[:-1])


def safe_target(target):
    """A path below the overlay's system, without .. and absolute parts."""
    parts = target.split("/")
    return (parts[0] == "system" and len(parts) > 1 and all(p not in ("", ".", "..") for p in parts))


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

class Ranged(io.RawIOBase):
    """A file on a server that answers ranges, readable as a local one (for zipfile)."""

    def __init__(self, url):
        r = urllib.request.urlopen(urllib.request.Request(url, method="HEAD"), timeout=NET_TIMEOUT)
        self.url = r.geturl()
        if not self.url.startswith("https://"):
            raise Mismatch(f"{url} leads to {self.url}")
        self.size = int(r.headers["Content-Length"])
        self.pos = 0

    def seekable(self):
        return True

    def readable(self):
        return True

    def tell(self):
        return self.pos

    def seek(self, offset, whence=0):
        self.pos = offset if whence == 0 else self.pos + offset if whence == 1 else self.size + offset
        return self.pos

    def readinto(self, buffer):
        if self.pos >= self.size or len(buffer) == 0:
            return 0
        end = min(self.pos + len(buffer), self.size) - 1
        request = urllib.request.Request(self.url, headers={"Range": f"bytes={self.pos}-{end}"})
        with urllib.request.urlopen(request, timeout=NET_TIMEOUT) as r:
            if r.status != 206:
                raise Mismatch(f"{self.url} does not answer ranges")
            data = r.read()
        buffer[:len(data)] = data
        self.pos += len(data)
        return len(data)


class Progress:
    def __init__(self, total):
        self.total, self.done = total, 0

    def add(self, n):
        self.done += n
        print(f"bytes {self.done} {self.total}", flush=True)


def copy_checked(source, dest, entry, progress):
    """Copies the stream source to dest, checking size and SHA-256 of the entry."""
    digest = hashlib.sha256()
    size = 0
    with open(dest, "wb") as out:
        while True:
            chunk = source.read(CHUNK)
            if not chunk:
                break
            size += len(chunk)
            if size > entry["size"]:
                raise Mismatch(f"{entry['target']} is larger than {entry['size']} bytes")
            digest.update(chunk)
            out.write(chunk)
            progress.add(len(chunk))
    if size != entry["size"] or digest.hexdigest() != entry["sha256"]:
        raise Mismatch(f"{entry['target']} is not the file of the list (SHA-256 {digest.hexdigest()})")


def cached(entry):
    return os.path.join(CACHE, entry["sha256"])


def is_cached(entry):
    path = cached(entry)
    try:
        if os.path.getsize(path) != entry["size"]:
            return False
        with open(path, "rb") as f:
            digest = hashlib.sha256()
            for chunk in iter(lambda: f.read(CHUNK), b""):
                digest.update(chunk)
        return digest.hexdigest() == entry["sha256"]
    except OSError:
        return False


def fetch(entry, progress, archive=None):
    part = cached(entry) + ".part"
    try:
        if archive is not None:
            with archive.open(entry["member"]) as source:
                copy_checked(source, part, entry, progress)
        else:
            if not entry["url"].startswith("https://"):
                raise Mismatch(f"{entry['url']} is no https address")
            with urllib.request.urlopen(entry["url"], timeout=NET_TIMEOUT) as r:
                if not r.geturl().startswith("https://"):
                    raise Mismatch(f"{entry['url']} leads to {r.geturl()}")
                copy_checked(r, part, entry, progress)
        os.replace(part, cached(entry))
    finally:
        if os.path.exists(part):
            os.unlink(part)


def download(variant):
    """Every file of the variant from the net into the cache, checked; the exit code."""
    remote = [e for e in variant["files"] if "local" not in e]
    os.makedirs(CACHE, mode=0o700, exist_ok=True)
    progress = Progress(sum(e["size"] for e in remote))
    try:
        missing = []
        for entry in remote:
            if is_cached(entry):
                progress.add(entry["size"])
            else:
                missing.append(entry)
        archive = None
        if missing and "zip" in variant:
            archive = zipfile.ZipFile(io.BufferedReader(Ranged(variant["zip"]), buffer_size=8 * CHUNK))
        for entry in missing:
            fetch(entry, progress, archive)
    except Mismatch as e:
        log(str(e))
        return EXIT_ERROR
    except (OSError, urllib.error.URLError, zipfile.BadZipFile, KeyError, ValueError) as e:
        log(f"cannot download {variant['name']}: {e}")
        return EXIT_UNREACHABLE
    return EXIT_DONE


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

def container_state():
    try:
        r = subprocess.run(["lxc-info", "-P", LXC_PATH, "-n", "waydroid", "-sH"], capture_output=True,
                           text=True, timeout=60)
    except (OSError, subprocess.TimeoutExpired):
        return ""
    return r.stdout.strip() if r.returncode == 0 else ""


def stop_android():
    if container_state() in ("RUNNING", "FROZEN"):
        try:
            subprocess.run(STOP, timeout=120, stdout=subprocess.DEVNULL)
        except (OSError, subprocess.TimeoutExpired):
            pass
    if container_state() in ("RUNNING", "FROZEN"):
        log("Android does not stop")
        return False
    return True


# ----- The overlay -----

def remove_files(files):
    """The files of a variant out of the overlay, apps before what allows them; then the
    directories that became empty."""
    for rel in sorted(files, key=lambda r: not is_app(r)):
        if not safe_target(rel):
            continue
        path = os.path.join(OVERLAY, rel)
        if os.path.lexists(path) and not os.path.isdir(path):
            os.unlink(path)
        parent = os.path.dirname(path)
        while parent != os.path.join(OVERLAY, "system") and parent.startswith(OVERLAY):
            try:
                os.rmdir(parent)
            except OSError:
                break
            parent = os.path.dirname(parent)


def put(source, rel):
    path = os.path.join(OVERLAY, rel)
    os.makedirs(os.path.dirname(path), mode=0o755, exist_ok=True)
    if os.path.lexists(path):
        os.unlink(path)
    tmp = path + ".new"
    shutil.copyfile(source, tmp)
    os.chmod(tmp, 0o644)
    os.replace(tmp, path)


def install_files(variant, placed):
    """The variant into the overlay, what allows the apps first; placed lists what is there."""
    entries = sorted(variant["files"], key=lambda e: is_app(e["target"]))
    for entry in entries:
        source = os.path.join(DATA, entry["local"]) if "local" in entry else cached(entry)
        put(source, entry["target"])
        placed.append(entry["target"])
        if entry.get("libs"):
            # A system app's native libraries are not unpacked by Android: next to the APK
            lib_dir = os.path.join(os.path.dirname(entry["target"]), "lib", "arm64")
            with zipfile.ZipFile(source) as apk:
                for name in apk.namelist():
                    if name.startswith(f"lib/{entry['libs']}/") and name.endswith(".so") and "/" not in name[len(f"lib/{entry['libs']}/"):]:
                        rel = os.path.join(lib_dir, os.path.basename(name))
                        tmp = os.path.join(CACHE, "lib.tmp")
                        with apk.open(name) as src, open(tmp, "wb") as out:
                            shutil.copyfileobj(src, out)
                        put(tmp, rel)
                        os.unlink(tmp)
                        placed.append(rel)


# ----- Every user's Android data -----

def open_dir(parent_fd, name):
    try:
        return os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC, dir_fd=parent_fd)
    except (FileNotFoundError, NotADirectoryError):
        return None


def delete_below(home, parts, name):
    """Deletes name in the directory home/parts, opened without following links."""
    fds = []
    try:
        fd = os.open(home, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC)
        fds.append(fd)
        for part in parts:
            fd = open_dir(fd, part)
            if fd is None:
                return False
            fds.append(fd)
        try:
            st = os.lstat(name, dir_fd=fd)
        except FileNotFoundError:
            return False
        if stat.S_ISDIR(st.st_mode):
            shutil.rmtree(name, dir_fd=fd)
        else:
            os.unlink(name, dir_fd=fd)
        return True
    except OSError:
        return False
    finally:
        for fd in fds:
            os.close(fd)


def homes():
    """The homes of the phone's users (no system accounts)."""
    found = []
    for pw in pwd.getpwall():
        if 1000 <= pw.pw_uid < 60000 and os.path.isabs(pw.pw_dir) and os.path.isdir(pw.pw_dir):
            found.append(pw.pw_dir)
    return found


def updates_of(app_dir, packages):
    """The entries below app_dir (an open directory) that hold an installed or unfinished copy of
    one of packages: [(directory, entry)] with directory None for app_dir itself."""
    found = []
    for name in os.listdir(app_dir):
        if name.startswith("~~"):
            inner = open_dir(app_dir, name)
            if inner is None:
                continue
            try:
                for entry in os.listdir(inner):
                    if any(entry.startswith(p + "-") for p in packages):
                        found.append((name, entry))
            finally:
                os.close(inner)
        elif name.startswith("vmdl") and name.endswith(".tmp"):
            inner = open_dir(app_dir, name)
            if inner is None:
                continue
            try:
                if any(f"{p}.apk" in os.listdir(inner) for p in packages):
                    found.append((None, name))
            finally:
                os.close(inner)
    return found


def remove_updates(packages):
    """Android's own installations of packages (updates of the system apps) in every user's
    Android; Android forgets an app whose files are gone."""
    for home in homes():
        fds = []
        try:
            fd = os.open(home, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC)
            fds.append(fd)
            for part in USER_APPS:
                fd = open_dir(fd, part)
                if fd is None:
                    break
                fds.append(fd)
            else:
                for directory, entry in updates_of(fd, packages):
                    if directory is None:
                        shutil.rmtree(entry, dir_fd=fd)
                    else:
                        inner = open_dir(fd, directory)
                        shutil.rmtree(entry, dir_fd=inner)
                        os.close(inner)
                        try:
                            os.rmdir(directory, dir_fd=fd)
                        except OSError:
                            pass
                    print(f"{home}: {entry} deleted", file=sys.stderr, flush=True)
        except OSError as e:
            log(f"{home}: {e}")
        finally:
            for fd in fds:
                os.close(fd)


def clear_data():
    for home in homes():
        for where in APP_DATA:
            for package in PACKAGES:
                if delete_below(home, USER_DATA + where, package):
                    print(f"{home}: the data of {package} deleted", file=sys.stderr, flush=True)


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

def status(variants):
    state = read_state()
    print(json.dumps({
        "variant": state.get("variant", "none") if state.get("variant") in variants else "none",
        # The variant whose data Android may still hold: another one deletes it
        "last": state.get("last") if state.get("last") in variants else None,
        "variants": [{"id": v["id"], "name": v["name"], "version": v["version"],
                      "download": sum(e.get("size", 0) for e in v["files"] if "local" not in e)}
                     for v in variants.values()],
    }))
    return EXIT_DONE


def switch(variants, want):
    state = read_state()
    old = state.get("variant", "none")
    if old == want and (want == "none" or state["files"]):
        return EXIT_NOTHING
    variant = variants.get(want)
    if variant is not None:
        step("download")
        code = download(variant)
        if code != EXIT_DONE:
            return code
    step("stop")
    if not stop_android():
        return EXIT_ERROR
    step("install")
    # The last variant whose data Android may still hold
    last = state.get("last") if state.get("last") in variants else (old if old in variants else None)
    remove_files(state["files"])
    write_state({"variant": "none", "files": [], "last": last})
    if old in variants:
        remove_updates(PACKAGES)
    if variant is not None:
        placed = []
        try:
            install_files(variant, placed)
        except (OSError, zipfile.BadZipFile) as error:
            log(f"cannot put {variant['name']} into Android: {error}")
            remove_files(placed)
            return EXIT_ERROR
        # The other variant's data does not fit the new one
        if last is not None and last != want:
            step("data")
            clear_data()
        write_state({"variant": want, "version": variant["version"], "files": placed, "last": want})
    shutil.rmtree(CACHE, ignore_errors=True)
    return EXIT_DONE


def main(argv):
    args = argv[1:]
    try:
        variants = load_list()
    except (OSError, ValueError, KeyError, TypeError) as e:
        log(f"cannot read {LIST}: {e}")
        return EXIT_ERROR
    for v in variants.values():
        if not all(safe_target(e.get("target", "")) for e in v["files"]):
            log(f"{v['id']}: a file outside Android's system")
            return EXIT_ERROR
    if args == ["status", "--json"]:
        return status(variants)
    if len(args) == 2 and args[0] == "set" and (args[1] == "none" or args[1] in variants):
        if os.geteuid() != 0:
            log("run through pkexec")
            return EXIT_ERROR
        os.makedirs(os.path.dirname(LOCK), exist_ok=True)
        with open(LOCK, "w") as lock:
            fcntl.flock(lock, fcntl.LOCK_EX)
            return switch(variants, args[1])
    print("usage: waydroid-plinius-google status --json | set none|" + "|".join(variants), file=sys.stderr)
    return EXIT_USAGE


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