#!/usr/bin/env python3
# summary: Manage this account's saved app passwords.
"""Manage only this account's login keyring; passwords travel on stdin, never in arguments.

Usage: starchaser keyring status | enable-passwordless-storage | encrypt-storage | on | off | unlock-login | explain [--notify]
    status   JSON: encrypted and passwordlessStorage describe saved sign-ins.
    enable-passwordless-storage (on)
             Remove encryption from saved sign-ins.
             Confirm with the current keyring password (one JSON string on stdin).
             Anyone with this disk can read saved passwords and app sign-ins.
    encrypt-storage (off)
             Restore encryption with a nonempty password (one JSON string on stdin).
    on/off   Compatibility aliases; on means passwordless storage, off restores encryption.
    unlock-login
             Unlock a locked login keyring with the password just accepted by Starchaser's password prompt, at most
             once per sign-in, and only for this account: {"password": ..., "uid": ...} on stdin, uid being the
             account whose password was typed. Says nothing. Exits 0 when it unlocked the keyring, 3 when this
             sign-in's one try is used up (made now or before), 1 when nothing was tried.
    reset    Start your saved passwords fresh, keeping the old encrypted store as a backup.
    reload   Reload the saved-password store after a recovery-code reset.
    explain  Print why saved sign-ins are locked; --notify shows it as a notification with a Password choices
             button and waits for that button (up to a minute)
"""
import argparse
import ctypes as C
import datetime
import stat
import json
import os
import subprocess
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_cli import CommandParser

LOGIN = b"/org/freedesktop/secrets/collection/login"
NOTICE = ("Use your password, or your saved-sign-ins password if you chose a separate one. "
          "After a password recovery reset, use your new password. Start fresh keeps a backup.")


def notice():
    path = Path(os.environ.get("XDG_DATA_HOME", str(Path.home() / ".local/share"))) / "keyrings/starchaser-password-changed.json"
    try:
        day = datetime.date.fromisoformat(json.loads(path.read_text())["changed"])
        return "Use the password you had before " + day.strftime("%B ") + str(day.day) + ". Forgot it? Start fresh keeps a backup of your old saved passwords."
    except (OSError, ValueError, KeyError, TypeError):
        return NOTICE


def reload_store():
    # Replace the secrets service so an already signed-in session drops its cached old store.
    result = subprocess.run(["gnome-keyring-daemon", "--replace", "--components=secrets"],
                            capture_output=True, text=True, timeout=15)
    if result.returncode:
        raise ValueError("Saved passwords start fresh after you sign out and sign in again.")


def reset_own():
    folder = Path(os.environ.get("XDG_DATA_HOME", str(Path.home() / ".local/share"))) / "keyrings"
    try:
        directory = os.open(folder, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
    except FileNotFoundError:
        return {"ok": True, "note": "No saved passwords file was found."}
    try:
        info = os.stat("login.keyring", dir_fd=directory, follow_symlinks=False)
        if not stat.S_ISREG(info.st_mode):
            raise ValueError("The saved passwords file isn't a regular file. Nothing was moved.")
        backup = "login.keyring.before-reset-" + datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%d-%H%M%S-%f")
        os.link("login.keyring", backup, src_dir_fd=directory, dst_dir_fd=directory, follow_symlinks=False)
        os.unlink("login.keyring", dir_fd=directory)
        try:
            os.unlink("starchaser-password-changed.json", dir_fd=directory)
        except FileNotFoundError:
            pass
    except FileNotFoundError:
        return {"ok": True, "note": "No saved passwords file was found."}
    finally:
        os.close(directory)
    note = "Saved passwords start fresh. Your old ones are kept in case you remember the old password."
    try:
        reload_store()
    except (ValueError, OSError, subprocess.SubprocessError):
        note += " Sign out and sign in again to finish."
    return {"ok": True, "note": note}

WARNING = "Saved passwords and app sign-ins are stored unencrypted on this disk. Anyone with the disk can read them."


def status():
    # Read only the format header, not saved secrets. No preference can drift from the real encryption state.
    path = Path(os.environ.get("XDG_DATA_HOME", str(Path.home() / ".local/share"))) / "keyrings/login.keyring"
    try:
        with path.open("rb") as stream:
            header = stream.read(16)
    except FileNotFoundError:
        return {"ok": True, "available": False, "on": False, "encrypted": None, "passwordlessStorage": False,
                "note": "No login keyring yet. Save a sign-in in an app first, then check again."}
    if header.startswith(b"[keyring]\n"):
        return {"ok": True, "available": True, "on": True, "encrypted": False, "passwordlessStorage": True}
    if header.startswith(b"GnomeKeyring\n\r\0\n"):
        return {"ok": True, "available": True, "on": False, "encrypted": True, "passwordlessStorage": False}
    raise ValueError("The saved-password protection couldn't be checked. No change made.")


def change_password(old, new):
    """Use the service's password change, preserving its items and all other collections."""
    master_call(b"ChangeWithMasterPassword", (old, new),
                "The password change could not finish. Check the current password for saved sign-ins and try again.")


def unlock_with_password(password):
    """Unlock the login collection with its password, without a prompt (fails if the password is not the keyring's)."""
    master_call(b"UnlockWithMasterPassword", (password,), "The saved sign-ins stayed locked.")


def master_call(method, passwords, failure):
    """Call gnome-keyring's master-password method on the login collection with each password as an encoded secret.

    libsecret negotiates the D-Bus secret session. ctypes keeps the helper standard-library-only,
    using the same installed libraries as apps instead of requiring Python desktop bindings.
    """
    secret = C.CDLL("libsecret-1.so.0")
    gio = C.CDLL("libgio-2.0.so.0")
    glib = C.CDLL("libglib-2.0.so.0")
    obj = C.CDLL("libgobject-2.0.so.0")
    ptr = C.c_void_p

    def bind(lib, name, result, *args):
        fn = getattr(lib, name)
        fn.restype = result
        fn.argtypes = args
        return fn

    get = bind(secret, "secret_service_get_sync", ptr, C.c_int, ptr, C.POINTER(ptr))
    value_new = bind(secret, "secret_value_new", ptr, C.c_char_p, C.c_ssize_t, C.c_char_p)
    encode = bind(secret, "secret_service_encode_dbus_secret", ptr, ptr, ptr)
    value_unref = bind(secret, "secret_value_unref", None, ptr)
    connection = bind(gio, "g_dbus_proxy_get_connection", ptr, ptr)
    call = bind(gio, "g_dbus_connection_call_sync", ptr, ptr, C.c_char_p, C.c_char_p, C.c_char_p,
                C.c_char_p, ptr, ptr, C.c_int, C.c_int, ptr, C.POINTER(ptr))
    path_new = bind(glib, "g_variant_new_object_path", ptr, C.c_char_p)
    tuple_new = bind(glib, "g_variant_new_tuple", ptr, C.POINTER(ptr), C.c_size_t)
    sink = bind(glib, "g_variant_ref_sink", ptr, ptr)
    unref = bind(glib, "g_variant_unref", None, ptr)
    error_free = bind(glib, "g_error_free", None, ptr)
    object_unref = bind(obj, "g_object_unref", None, ptr)
    error = ptr()
    service = params = reply = None
    values = []
    try:
        service = get(2, None, C.byref(error))  # SECRET_SERVICE_OPEN_SESSION
        if not service:
            raise ValueError("Saved passwords are unavailable. Try again after signing in.")
        for password in passwords:
            data = password.encode("utf-8")
            values.append(value_new(data, len(data), b"text/plain"))
        count = len(values) + 1
        children = (ptr * count)(path_new(LOGIN), *(encode(service, value) for value in values))
        if not all(children):
            raise ValueError("The saved-password change couldn't start. Try again.")
        params = sink(tuple_new(children, count))
        reply = call(connection(service), b"org.gnome.keyring", b"/org/freedesktop/secrets",
                     b"org.gnome.keyring.InternalUnsupportedGuiltRiddenInterface", method,
                     params, None, 0, 30000, None, C.byref(error))
        if not reply:
            raise ValueError(failure)
    finally:
        if reply:
            unref(reply)
        if params:
            unref(params)
        for value in values:
            value_unref(value)
        if service:
            object_unref(service)
        if error:
            error_free(error)


def change(mode, password):
    if not isinstance(password, str) or not password or "\0" in password:
        raise ValueError("Enter a nonempty password.")
    before = status()
    if not before["available"]:
        raise ValueError(before["note"])
    target = mode == "on"
    if before["on"] == target:
        raise ValueError("Saved-password protection has changed. Check its status and try again.")
    change_password(password if target else "", "" if target else password)
    after = status()
    if not after["available"] or after["on"] != target:
        raise ValueError("The saved-password change couldn't be verified. Check its status before trying again.")
    return dict(after, note=WARNING if target else "Saved passwords are protected again. After automatic sign-in, apps will ask for this password.")


def login_locked():
    """True only when the service answers that the login collection is locked (no secret is read or sent)."""
    result = subprocess.run(["busctl", "--user", "get-property", "org.freedesktop.secrets", LOGIN.decode(),
                             "org.freedesktop.Secret.Collection", "Locked"], capture_output=True, text=True, timeout=10)
    return result.returncode == 0 and result.stdout.split() == ["b", "true"]


def unlock_login(request):
    """After automatic sign-in the login keyring stays locked, so the first app with saved passwords asked for it.

    When the person types their own password in Starchaser's password prompt and it works, that same password
    unlocks it (Derek, 2026-11-04): once per sign-in, whatever the result, so a keyring with a password of its own
    is tried once and then left to ask as before. Another account's password (an administrator's, typed for
    this account) is never tried. Nothing is kept: the password lives only in this process.
    Returns "unlocked", "tried" (this sign-in's try is used up) or "skipped" (nothing tried).
    """
    if not isinstance(request, dict):
        return "skipped"
    password, uid = request.get("password"), request.get("uid")
    if not isinstance(password, str) or not password or "\0" in password:
        return "skipped"
    if type(uid) is not int or uid != os.getuid():
        return "skipped"
    runtime = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}"
    marker = Path(runtime) / f"starchaser-keyring-unlock-{os.environ.get('XDG_SESSION_ID', 'session')}"
    if marker.exists():
        return "tried"
    if not status()["encrypted"] or not login_locked():
        return "skipped"
    # made before trying, so a wrong password or a crash still uses up this sign-in's one try
    try:
        os.close(os.open(marker, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600))
    except FileExistsError:
        return "tried"
    try:
        unlock_with_password(password)
    except ValueError:
        return "tried"
    return "unlocked" if not login_locked() else "tried"


def explain(window=""):
    if sys.stderr.isatty():     # the wait below is up to a minute; silence reads as a hang in a terminal
        print("Waiting for your answer in the notification: press Password choices to open Settings.", file=sys.stderr)
    result = subprocess.run([*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", "-i", "dialog-password", "-t", "60000",
                             *(["-h", "string:x-starchaser-prompt-address:" + window] if window else []),
                             "--action=settings=Password choices", "--action=fresh=Start fresh", "Saved passwords", notice()],
                            capture_output=True, text=True, timeout=65)
    if result.returncode == 0 and result.stdout.strip() == "fresh":
        subprocess.run(["starchaser", "settings", "users", "Reset my saved passwords"], check=False, timeout=10)
    elif result.returncode == 0 and result.stdout.strip() == "settings":
        subprocess.run(["starchaser", "settings", "security", "Unlock saved app passwords automatically"], check=False, timeout=10)


def main(argv=None):
    # usage=SUPPRESS: the docstring's own Usage block is the one to read (a second, argparse-made one disagreed with it)
    parser = CommandParser(prog="starchaser keyring", description=__doc__, usage=argparse.SUPPRESS,
                           formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("command", choices=("status", "enable-passwordless-storage", "encrypt-storage", "on", "off",
                                            "unlock-login", "explain", "reset", "reload"))
    parser.add_argument("--window", default="", help="window address for the saved-password prompt")
    parser.add_argument("--notify", action="store_true", help="show the explanation as a desktop notification")
    args = parser.parse_args(argv)
    if args.notify and args.command != "explain":
        parser.error("--notify is only for explain")
    try:
        if args.command == "reset":
            print(json.dumps(reset_own()))
            return 0
        if args.command == "reload":
            reload_store()
            return 0
        if args.command == "explain":
            if args.notify:
                if args.window and not __import__('re').fullmatch(r'0x[0-9a-fA-F]+', args.window):
                    raise ValueError('Choose an open password prompt.')
                explain(args.window)
            else:
                print(notice() + " Open Settings > Security for Password choices.")
            return 0
        if args.command == "unlock-login":
            # quiet either way: the prompt that sent this has already closed, and an app still asks if this failed
            try:
                request = json.loads(sys.stdin.read(65600))
            except (json.JSONDecodeError, UnicodeDecodeError):
                return 1
            try:
                return {"unlocked": 0, "tried": 3}.get(unlock_login(request), 1)
            except (OSError, ValueError, AttributeError, subprocess.SubprocessError):
                return 1
        if args.command == "status":
            result = status()
        else:
            # Bounded input also rejects truncation and extra JSON. Never echo any input or native error.
            try:
                password = json.loads(sys.stdin.read(65537))
            except json.JSONDecodeError:
                raise ValueError("Supply a password as one JSON string on standard input. No change made.") from None
            mode = {"enable-passwordless-storage": "on", "encrypt-storage": "off"}.get(args.command, args.command)
            result = change(mode, password)
        print(json.dumps(result))
        return 0
    except (OSError, ValueError, AttributeError, subprocess.SubprocessError) as exc:
        note = str(exc) if type(exc) is ValueError else "Saved passwords are unavailable. Check again after signing in."
        print(note, file=sys.stderr)
        return 1


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