#!/usr/bin/python3
# SPDX-License-Identifier: MIT
"""waydroid-plinius-manage: Settings' Android page sets Android up, resets it and removes it.

Run through pkexec (org.plinius.waydroid.manage, an administrator's PIN). The user is the one who
called pkexec (PKEXEC_UID): reset and remove touch only that user's Android of the phone's users.

  setup             Android's image from the update channel (plinius-android-image install: signed,
                    checked), waydroid init, and the container service started: Android starts
                    with the first Android app. Only before Android is set up.
  reset [--files]   the user's Android as new: its apps, accounts and settings go
                    (~/.local/share/waydroid, the apps' entries in ~/.local/share/applications);
                    with --files also ~/Android, Android's internal storage (photos, downloads).
                    Android stops first.
  remove [--files]  the same, and Android's image and Waydroid's set-up of the phone go too: the
                    container service stops and does not start again until Android is set up
                    anew. The Android data of the phone's other users stays, for a new set-up.

Android's files belong to Android's own user IDs, which is why this needs root. Everything in a
home is deleted through directory descriptors opened without following symbolic links, so that
no link in the home leads the deletion anywhere else.

Progress for Settings on stdout: "step NAME" as a step begins (download, unpack: the image's;
setup, start; stop, delete) and plinius-android-image's "bytes DONE TOTAL".

Exit: 0 done, 6 nothing to do (setup: Android set up already, the channel has no image), 4 the
update server did not hand out the image, 1 an error, 2 bad arguments.
"""

import configparser
import os
import pwd
import re
import shutil
import stat
import subprocess
import sys

WAYDROID_CFG = "/var/lib/waydroid/waydroid.cfg"
WORK = "/var/lib/waydroid"
PREINSTALLED = "/etc/waydroid-extra/images"
IMAGE_CACHE = "/var/cache/plinius-android"
ANDROID_IMAGE = "/usr/lib/waydroid-plinius/plinius-android-image"
LXC_PATH = "/var/lib/waydroid/lxc"
MOUNTINFO = "/proc/self/mountinfo"
SERVICE = "waydroid-container.service"
STOP = ["gdbus", "call", "--system", "--dest", "id.waydro.Container", "--object-path", "/ContainerManager",
        "--method", "id.waydro.ContainerManager.Stop", "true"]
# The user's Android, below the home (Waydroid's session defaults; pkexec gives no XDG_DATA_HOME)
USER_DATA = (".local", "share", "waydroid")
USER_APPS = (".local", "share", "applications")
USER_FILES = ("Android",)
# The entries Waydroid writes for Android's apps
APP_ENTRY = re.compile(r"waydroid\.[A-Za-z0-9_.]+\.desktop")
TIMEOUT = 600

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


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


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


def run(command, timeout=TIMEOUT):
    """The exit code of command (127 when it cannot run, 124 after the timeout)."""
    try:
        return subprocess.run(command, timeout=timeout).returncode
    except OSError:
        return 127
    except subprocess.TimeoutExpired:
        return 124


def container_state():
    """RUNNING, FROZEN, STOPPED (lxc-info), or "" when the container is not there."""
    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():
    """Android stopped (with the session of whoever runs it); False if it still runs."""
    if container_state() in ("RUNNING", "FROZEN"):
        # Waydroid's container manager stops it and ends the session
        run(STOP, timeout=120)
    if container_state() in ("RUNNING", "FROZEN"):
        log("Android does not stop")
        return False
    return True


def open_dir(parent_fd, name):
    """The directory name below parent_fd, never through a symbolic link; None if it is not one."""
    try:
        return os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC, dir_fd=parent_fd)
    except (FileNotFoundError, NotADirectoryError):
        # With O_DIRECTORY a symbolic link is "not a directory" (ENOTDIR), not ELOOP
        return None


def delete_entry(dir_fd, name):
    """Deletes name in dir_fd: a directory with everything in it (without following links), anything
    else by itself; nothing if it is not there."""
    try:
        st = os.lstat(name, dir_fd=dir_fd)
    except FileNotFoundError:
        return
    if stat.S_ISDIR(st.st_mode):
        shutil.rmtree(name, dir_fd=dir_fd)
    else:
        os.unlink(name, dir_fd=dir_fd)


def in_home(home, parts, action):
    """action(fd, last) with fd the directory of parts[:-1] below home, opened without following
    links; nothing if one of them is no directory."""
    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[:-1]:
            fd = open_dir(fd, part)
            if fd is None:
                return
            fds.append(fd)
        action(fd, parts[-1])
    finally:
        for fd in fds:
            os.close(fd)


def delete_app_entries(fd, name):
    apps = open_dir(fd, name)
    if apps is None:
        return
    try:
        for entry in os.listdir(apps):
            if APP_ENTRY.fullmatch(entry):
                delete_entry(apps, entry)
    finally:
        os.close(apps)


def delete_user_android(home, files):
    """The user's Android data, the entries of its apps and, with files, ~/Android."""
    in_home(home, USER_DATA, delete_entry)
    in_home(home, USER_APPS, delete_app_entries)
    if files:
        in_home(home, USER_FILES, delete_entry)


def caller():
    """The home of the user who called pkexec, or None."""
    uid = os.environ.get("PKEXEC_UID", "")
    if not uid.isdigit() or int(uid) == 0:
        log("run through pkexec by the user whose Android it is")
        return None
    try:
        home = pwd.getpwuid(int(uid)).pw_dir
    except KeyError:
        log(f"no user {uid}")
        return None
    if not os.path.isabs(home) or os.path.realpath(home) != os.path.normpath(home) or not os.path.isdir(home):
        log(f"the home of user {uid} is no directory of its own")
        return None
    return home


def images_path():
    cfg = configparser.ConfigParser()
    try:
        cfg.read(WAYDROID_CFG)
        return cfg.get("waydroid", "images_path")
    except (configparser.Error, OSError):
        return None


def mounted_below(path):
    """Mount points at or below path (the container's rootfs while Android runs)."""
    found = []
    try:
        with open(MOUNTINFO, encoding="utf-8") as f:
            for line in f:
                fields = line.split()
                if len(fields) > 4:
                    point = fields[4].replace("\\040", " ")
                    if point == path or point.startswith(path.rstrip("/") + "/"):
                        found.append(point)
    except OSError:
        pass
    return found


def setup():
    if os.path.isfile(WAYDROID_CFG):
        log("Android is set up already")
        return EXIT_NOTHING
    code = run([ANDROID_IMAGE, "install", "--progress"], timeout=None)
    if code != EXIT_DONE:
        return code if code in (EXIT_NOTHING, EXIT_UNREACHABLE) else EXIT_ERROR
    step("setup")
    if run(["waydroid", "init"]) != 0 or not os.path.isfile(WAYDROID_CFG):
        log("waydroid init failed")
        return EXIT_ERROR
    step("start")
    run(["systemctl", "enable", SERVICE], timeout=60)
    if run(["systemctl", "restart", SERVICE], timeout=300) != 0:
        log(f"{SERVICE} did not start")
        return EXIT_ERROR
    return EXIT_DONE


def reset(home, files):
    step("stop")
    if not stop_android():
        return EXIT_ERROR
    step("delete")
    delete_user_android(home, files)
    return EXIT_DONE


def remove(home, files):
    step("stop")
    if not stop_android():
        return EXIT_ERROR
    images = images_path()
    run(["systemctl", "stop", SERVICE], timeout=300)
    busy = mounted_below(WORK)
    if busy:
        log("still mounted: " + ", ".join(busy))
        return EXIT_ERROR
    step("delete")
    delete_user_android(home, files)
    # Waydroid's set-up (waydroid.cfg, the container, the overlays); the directory stays
    work = os.open(WORK, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC) if os.path.isdir(WORK) else None
    if work is not None:
        try:
            for entry in os.listdir(work):
                delete_entry(work, entry)
        finally:
            os.close(work)
    # The images, only where we put them (one under WORK went with it; a package's stay)
    if images == PREINSTALLED:
        for name in ("system.img", "vendor.img"):
            try:
                os.unlink(os.path.join(PREINSTALLED, name))
            except FileNotFoundError:
                pass
    shutil.rmtree(IMAGE_CACHE, ignore_errors=True)
    return EXIT_DONE


def main(argv):
    args = argv[1:]
    if args == ["setup"]:
        return setup()
    if args and args[0] in ("reset", "remove") and args[1:] in ([], ["--files"]):
        home = caller()
        if home is None:
            return EXIT_ERROR
        files = args[1:] == ["--files"]
        return reset(home, files) if args[0] == "reset" else remove(home, files)
    print("usage: waydroid-plinius-manage setup | reset [--files] | remove [--files]", file=sys.stderr)
    return EXIT_USAGE


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