#!/usr/bin/python3
# SPDX-License-Identifier: MIT
"""waydroid-plinius-app: an Android app's permissions and removal, for its page in Settings.

  waydroid-plinius-app list PACKAGE
  waydroid-plinius-app set PACKAGE GROUP on|off
  waydroid-plinius-app remove PACKAGE

Settings shows the permissions of an Android app as Android's own settings group them (camera,
microphone, location, ...) and switches a group on or off. Android keeps them per app; only root
in the Waydroid container may change them (pm grant / pm revoke), so Settings runs this through
pkexec (org.plinius.waydroid.app, no PIN for the active session, as in Android's settings;
Settings asks before it removes an app).

Only the caller's own Android is touched: the running Waydroid session must be the caller's
(PKEXEC_UID). A frozen container is thawed first (Android freezes it while idle).

list prints JSON: {"state": "running" | "stopped" | "other-user", "removable": bool, "groups":
[{"group": ID, "granted": bool, "fixed": bool}, ...]}, the groups whose permissions the app asks
for, in the order of GROUPS. A group is granted when one of its permissions is; fixed when Android
does not let the user change any of them (system or policy fixed, restricted). removable: the app
is installed and not part of Android's system (those Android only disables, Settings does not).

set grants or revokes the group's permissions the app asks for, as Android's settings do: on
grants the foreground ones (location and body sensors in the background stay the user's step in
Android), off revokes all of them, including the background ones. Each is marked as set by the
user. pm answers 0 even when it fails, so the permissions are read again afterwards.

remove uninstalls the app with its data (pm uninstall), never an app of Android's system; an app
that is not installed counts as removed. Waydroid takes its launcher away by itself.

Exit status: 0 done, 1 failed, 2 bad arguments, 3 Android does not run (or not the caller's).
"""

import json
import os
import re
import subprocess
import sys

# An Android package name (com.android.chrome): nothing that could pass for an option of pm
PACKAGE = re.compile(r"[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+")
TIMEOUT = 30
A = "android.permission."

# Android's permission groups as its settings show them (PermissionController's platform groups)
GROUPS = (
    ("camera", (A + "CAMERA",)),
    ("microphone", (A + "RECORD_AUDIO",)),
    ("location", (A + "ACCESS_FINE_LOCATION", A + "ACCESS_COARSE_LOCATION", A + "ACCESS_BACKGROUND_LOCATION")),
    ("nearby", (A + "BLUETOOTH_SCAN", A + "BLUETOOTH_CONNECT", A + "BLUETOOTH_ADVERTISE",
                A + "NEARBY_WIFI_DEVICES", A + "UWB_RANGING", A + "RANGING")),
    ("notifications", (A + "POST_NOTIFICATIONS",)),
    ("contacts", (A + "READ_CONTACTS", A + "WRITE_CONTACTS", A + "GET_ACCOUNTS")),
    ("calendar", (A + "READ_CALENDAR", A + "WRITE_CALENDAR")),
    ("phone", (A + "READ_PHONE_STATE", A + "READ_PHONE_NUMBERS", A + "CALL_PHONE", A + "ANSWER_PHONE_CALLS",
               "com.android.voicemail.permission.ADD_VOICEMAIL", A + "USE_SIP", A + "ACCEPT_HANDOVER")),
    ("call_log", (A + "READ_CALL_LOG", A + "WRITE_CALL_LOG", A + "PROCESS_OUTGOING_CALLS")),
    ("sms", (A + "SEND_SMS", A + "RECEIVE_SMS", A + "READ_SMS", A + "RECEIVE_WAP_PUSH", A + "RECEIVE_MMS",
             A + "READ_CELL_BROADCASTS")),
    ("photos", (A + "READ_MEDIA_IMAGES", A + "READ_MEDIA_VIDEO", A + "READ_MEDIA_VISUAL_USER_SELECTED")),
    ("music", (A + "READ_MEDIA_AUDIO",)),
    ("files", (A + "READ_EXTERNAL_STORAGE", A + "WRITE_EXTERNAL_STORAGE")),
    ("activity", (A + "ACTIVITY_RECOGNITION",)),
    ("sensors", (A + "BODY_SENSORS", A + "BODY_SENSORS_BACKGROUND")),
)
# Granted only by the user's own step in Android; off takes them too
BACKGROUND = {A + "ACCESS_BACKGROUND_LOCATION", A + "BODY_SENSORS_BACKGROUND"}
# Flags under which the user cannot change a permission
FIXED = {"SYSTEM_FIXED", "POLICY_FIXED", "APPLY_RESTRICTION"}
# "    android.permission.CAMERA: granted=true, flags=[ USER_SET|USER_SENSITIVE_WHEN_GRANTED]"
RUNTIME = re.compile(r"\s+([A-Za-z0-9_.]+): granted=(true|false)(?:, flags=\[\s*([A-Z_|]*)\s*\])?\s*$")
SESSION_USER = re.compile(r".*\((\d+)\)\s*$")


class Failed(Exception):
    pass


def run(*args):
    """waydroid ARGS: the finished process, None if it could not run or hung."""
    try:
        return subprocess.run(["waydroid", *args], capture_output=True, text=True, timeout=TIMEOUT)
    except (OSError, subprocess.TimeoutExpired):
        return None


def status():
    """(container state, uid of the session's user or None); Failed if Waydroid does not answer."""
    r = run("status")
    if r is None:
        raise Failed("Waydroid does not answer")
    state, uid = None, None
    for line in r.stdout.splitlines():
        key, sep, value = line.partition(":")
        if not sep:
            continue
        if key.strip() == "Container":
            state = value.strip()
        elif key.strip() == "Session user":
            m = SESSION_USER.fullmatch(value)
            uid = int(m.group(1)) if m else None
    if state is None:
        raise Failed("Waydroid does not answer")
    return state, uid


def ready(caller):
    """"running" once the caller's Android can be asked (thawed), "stopped" or "other-user"."""
    state, uid = status()
    if state not in ("RUNNING", "FROZEN"):
        return "stopped"
    if uid != caller:
        return "other-user"
    if state == "FROZEN":
        r = run("container", "unfreeze")
        if r is None or r.returncode != 0:
            raise Failed("cannot thaw the container")
    return "running"


class App:
    """What Android's dumpsys package says about the app."""

    def __init__(self):
        self.installed = False
        self.system = False
        self.perms = {}  # {permission: (granted, flags)}, runtime permissions in user 0


def read(package):
    r = run("shell", "--", "dumpsys", "package", package)
    if r is None or r.returncode != 0:
        raise Failed(f"cannot read the permissions of {package}")
    app, perms, user0, block = App(), {}, False, False
    app.perms = perms
    for line in r.stdout.splitlines():
        if line.strip().startswith(f"Package [{package}]"):
            app.installed = True
        elif app.installed and not app.system and line.strip().startswith("pkgFlags=["):
            app.system = "SYSTEM" in line.strip()[len("pkgFlags=["):].rstrip("]").split()
        if block:
            m = RUNTIME.fullmatch(line)
            if not m:
                break
            perms[m.group(1)] = (m.group(2) == "true", set(filter(None, (m.group(3) or "").split("|"))))
        elif line.strip().startswith("User 0:"):
            user0 = True
        elif user0 and line.strip() == "runtime permissions:":
            block = True
    return app


def runtime(package):
    """{permission: (granted, flags)} of the app's runtime permissions in Android's user 0."""
    return read(package).perms


def groups(perms):
    out = []
    for group, members in GROUPS:
        asked = [p for p in members if p in perms and p not in BACKGROUND]
        if not asked:
            continue
        out.append({"group": group,
                    "granted": any(perms[p][0] for p in asked),
                    "fixed": all(perms[p][1] & FIXED for p in asked)})
    return out


def pm(*args):
    r = run("shell", "--", "pm", *args)
    if r is None or r.returncode != 0:
        raise Failed("pm " + " ".join(args) + " failed")


def set_group(package, group, on):
    members = dict(GROUPS)[group]
    perms = runtime(package)
    changeable = [p for p in members if p in perms and not perms[p][1] & FIXED]
    if on:
        changeable = [p for p in changeable if p not in BACKGROUND]
    if not changeable:
        raise Failed(f"{package} has no permission of {group} that can be changed")
    for p in changeable:
        if on:
            pm("clear-permission-flags", "--user", "0", package, p, "user-fixed")
            pm("grant", "--user", "0", package, p)
        else:
            pm("revoke", "--user", "0", package, p)
        pm("set-permission-flags", "--user", "0", package, p, "user-set")
    after = runtime(package)
    if any(after.get(p, (not on,))[0] != on for p in changeable):
        raise Failed(f"Android did not {'grant' if on else 'revoke'} {group} for {package}")


def remove(package):
    app = read(package)
    if not app.installed:
        return
    if app.system:
        raise Failed(f"{package} is part of Android and is not removed")
    r = run("shell", "--", "pm", "uninstall", package)
    if r is None or r.returncode != 0 or read(package).installed:
        raise Failed(f"Android did not remove {package}")


def caller():
    try:
        return int(os.environ["PKEXEC_UID"])
    except (KeyError, ValueError):
        return None


def main(argv):
    args = argv[1:]
    ok = (len(args) == 2 and args[0] in ("list", "remove")) or \
         (len(args) == 4 and args[0] == "set" and args[2] in dict(GROUPS) and args[3] in ("on", "off"))
    if not ok or len(args[1]) > 255 or not PACKAGE.fullmatch(args[1]):
        print("usage: waydroid-plinius-app list PACKAGE | set PACKAGE GROUP on|off | remove PACKAGE",
              file=sys.stderr)
        return 2
    uid = caller()
    if uid is None:
        print("waydroid-plinius-app: run it through pkexec", file=sys.stderr)
        return 1
    try:
        state = ready(uid)
        if args[0] == "list":
            app = read(args[1]) if state == "running" else App()
            print(json.dumps({"state": state, "removable": app.installed and not app.system,
                              "groups": groups(app.perms)}))
            return 0
        if state != "running":
            print(f"waydroid-plinius-app: Android does not run ({state})", file=sys.stderr)
            return 3
        if args[0] == "remove":
            remove(args[1])
        else:
            set_group(args[1], args[2], args[3] == "on")
        return 0
    except Failed as e:
        print(f"waydroid-plinius-app: {e}", file=sys.stderr)
        return 1


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