#!/usr/bin/python3
# SPDX-License-Identifier: MIT
"""waydroid-plinius-usage: how much storage Android takes, for Settings' Android page.

Run through pkexec (org.plinius.waydroid.usage, no PIN for the active session): Android's files
belong to Android's own user IDs, which the phone's user cannot look into. It only reads, and
only sizes. Prints JSON, in bytes on the disk:

  system  Android's image and Waydroid's set-up of the phone (shared by every user)
  apps    the calling user's Android: apps, their data, accounts, settings
          (~/.local/share/waydroid)
  files   the calling user's ~/Android, Android's internal storage (photos, downloads)
  gsf_id  the Android ID of Google's services in the calling user's Android (null without them):
          Google asks for it to register a phone it does not know (google.com/android/uncertified)

A tree is counted without following symbolic links and without leaving its file system, every
file once (hard links). A path that is no directory of its own counts 0. The home belongs to
the user, who may swap any directory in it for a link while this runs as root: every path is
opened from / down without following a link, each directory below it from the one it is in,
and only read through its descriptor (Google's database too), so a name swapped meanwhile leads
nowhere else.
Exit: 0, 1 an error (not run through pkexec).
"""

import configparser
import json
import os
import pwd
import sqlite3
import stat
import sys

WAYDROID_CFG = "/var/lib/waydroid/waydroid.cfg"
WORK = "/var/lib/waydroid"
IMAGES = ("system.img", "vendor.img")
# Google's services keep their Android ID here, in the user's Android data: in GmsCore since it took
# the database over from GoogleServicesFramework (gservices.db.migrated there), before in GSF
GSERVICES = tuple((".local", "share", "waydroid", "data", "data", package, "databases", "gservices.db")
                  for package in ("com.google.android.gms", "com.google.android.gsf"))


OPEN_DIR = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC


def open_dir(parent_fd, name):
    """The directory name in parent_fd, never through a symbolic link; None if it is none."""
    try:
        return os.open(name, OPEN_DIR, dir_fd=parent_fd)
    except OSError:
        # With O_DIRECTORY a symbolic link is "not a directory" (ENOTDIR), not ELOOP
        return None


def open_path(path, last=OPEN_DIR):
    """The absolute path opened from / down, part by part without following a link (its last
    part with the flags last); None if a part is missing or a link, or path is not absolute."""
    if not os.path.isabs(path):
        return None
    parts = [p for p in os.path.normpath(path).split("/") if p]
    fd = os.open("/", OPEN_DIR)
    for i, name in enumerate(parts):
        try:
            if i == len(parts) - 1:
                child = os.open(name, last, dir_fd=fd)
            else:
                child = open_dir(fd, name)
        except OSError:
            child = None
        os.close(fd)
        if child is None:
            return None
        fd = child
    return fd


def tree_size(top):
    """Bytes on the disk of everything below top (top a real directory), 0 otherwise."""
    # No symbolic link on the way either (a home's .local could lead anywhere)
    fd = open_path(top)
    if fd is None:
        return 0
    seen = set()
    total, device = 0, None

    def count(dir_fd):
        """Adds the entries of dir_fd; its directories as (name, inode) to go into."""
        nonlocal total
        try:
            entries = list(os.scandir(dir_fd))
        except OSError:
            return []
        dirs = []
        for entry in entries:
            try:
                est = entry.stat(follow_symlinks=False)
            except OSError:
                continue
            if est.st_dev != device:
                continue
            if est.st_nlink > 1:
                if (est.st_dev, est.st_ino) in seen:
                    continue
                seen.add((est.st_dev, est.st_ino))
            total += est.st_blocks * 512
            if stat.S_ISDIR(est.st_mode):
                dirs.append((entry.name, est.st_ino))
        return dirs

    # One descriptor per level: a directory is opened when the walk goes into it, from its parent;
    # each one open is on the stack, which the end closes, however the walk ends
    stack = [(fd, iter(()))]
    try:
        st = os.fstat(fd)
        total, device = st.st_blocks * 512, st.st_dev
        stack[-1] = (fd, iter(count(fd)))
        while stack:
            dir_fd, subdirs = stack[-1]
            for name, ino in subdirs:
                child = open_dir(dir_fd, name)
                if child is None:
                    continue
                stack.append((child, iter(())))
                cst = os.fstat(child)
                if (cst.st_dev, cst.st_ino) != (device, ino):
                    # Swapped since it was counted: not the directory counted
                    stack.pop()
                    os.close(child)
                    continue
                stack[-1] = (child, iter(count(child)))
                break
            else:
                stack.pop()
                os.close(dir_fd)
    finally:
        for dir_fd, _ in stack:
            os.close(dir_fd)
    return total


def images_size():
    cfg = configparser.ConfigParser()
    try:
        cfg.read(WAYDROID_CFG)
        path = cfg.get("waydroid", "images_path")
    except (configparser.Error, OSError):
        return 0
    # Images under WORK count with it
    if os.path.normpath(path).startswith(WORK.rstrip("/") + "/"):
        return 0
    total = 0
    for name in IMAGES:
        try:
            st = os.stat(os.path.join(path, name))
        except OSError:
            continue
        if stat.S_ISREG(st.st_mode):
            total += st.st_blocks * 512
    return total


def gsf_id(home):
    """The Android ID of Google's services (a decimal number as text), or None."""
    for parts in GSERVICES:
        found = android_id(os.path.join(home, *parts))
        if found:
            return found
    return None


def android_id(path):
    # No symbolic link on the way, only a file of its own (O_PATH: a pipe or a device planted
    # there is not opened for real), read through the descriptor opened
    fd = open_path(path, os.O_PATH | os.O_NOFOLLOW | os.O_CLOEXEC)
    if fd is None:
        return None
    try:
        if not stat.S_ISREG(os.fstat(fd).st_mode):
            return None
        # Read only, and as it is: no journal or lock is written into Android's data
        con = sqlite3.connect(f"file:/proc/self/fd/{fd}?mode=ro&immutable=1", uri=True)
        try:
            row = con.execute("SELECT value FROM main WHERE name = 'android_id'").fetchone()
        finally:
            con.close()
    except sqlite3.Error:
        return None
    finally:
        os.close(fd)
    value = str(row[0]) if row else ""
    return value if value.isdigit() and value != "0" else None


def main(argv):
    uid = os.environ.get("PKEXEC_UID", "")
    if len(argv) != 1 or not uid.isdigit():
        print("usage: pkexec waydroid-plinius-usage", file=sys.stderr)
        return 1
    try:
        home = pwd.getpwuid(int(uid)).pw_dir
    except KeyError:
        print(f"waydroid-plinius-usage: no user {uid}", file=sys.stderr)
        return 1
    result = {
        "system": images_size() + tree_size(WORK),
        "apps": tree_size(os.path.join(home, ".local", "share", "waydroid")),
        "files": tree_size(os.path.join(home, "Android")),
        "gsf_id": gsf_id(home),
    }
    print(json.dumps(result))
    return 0


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