#!/usr/bin/python3 -I
# c8-wallet-import [--clear]: copies every secret from KWallet into the
# oo7 login wallet that cont8nuum uses. --clear empties the oo7 wallet
# first (a copy of its file is kept as login.keyring.bak-DATE).
#
# KWallet is left as it is. In Plasma it is the session's secrets service
# and the oo7 wallet is opened by a private oo7-daemon on a bus of its own
# (the password asked with c8-askpass, twice when the wallet is new, since
# an empty one takes any password). In cont8nuum, where the session's
# service is oo7 (already open), KWallet's ksecretd is started on a
# private bus to read from instead, and the items go to the running oo7.
# An item with the same label and attributes as one already there
# replaces it, so running it again does no harm. Nothing secret is printed.
import os
import pty
import select
import shutil
import subprocess
import sys
import time

import gi
gi.require_version('Gio', '2.0')
from gi.repository import Gio, GLib

SECRETS = 'org.freedesktop.secrets'
ROOT = '/org/freedesktop/secrets'
SERVICE = 'org.freedesktop.Secret.Service'
COLLECTION = 'org.freedesktop.Secret.Collection'
ITEM = 'org.freedesktop.Secret.Item'
PROMPT = 'org.freedesktop.Secret.Prompt'
# oo7 0.6 from build-oo7.sh, else the packaged one
DAEMON = next((d for d in ('/usr/local/libexec/oo7-daemon',
                           '/usr/libexec/oo7-daemon')
               if os.access(d, os.X_OK)), '/usr/libexec/oo7-daemon')
KSECRETD = '/usr/bin/ksecretd'


def die(msg):
    print(f'c8-wallet-import: {msg}', file=sys.stderr)
    sys.exit(1)


def call(bus, path, iface, method, args=None, reply=None, timeout=-1):
    return bus.call_sync(SECRETS, path, iface, method, args,
                         GLib.VariantType(reply) if reply else None,
                         Gio.DBusCallFlags.NONE, timeout, None).unpack()


def prop(bus, path, iface, name):
    return call(bus, path, 'org.freedesktop.DBus.Properties', 'Get',
                GLib.Variant('(ss)', (iface, name)), '(v)')[0]


def run_prompt(bus, path):
    """Shows a prompt and waits for it; true unless dismissed"""
    if path == '/':
        return True
    loop = GLib.MainLoop()
    result = {}

    def completed(conn, sender, obj, iface, signal, params):
        result['dismissed'] = params.unpack()[0]
        loop.quit()
    sub = bus.signal_subscribe(SECRETS, PROMPT, 'Completed', path, None,
                               Gio.DBusSignalFlags.NONE, completed)
    call(bus, path, PROMPT, 'Prompt', GLib.Variant('(s)', ('',)))
    loop.run()
    bus.signal_unsubscribe(sub)
    return not result.get('dismissed', True)


def read_all(bus):
    """Every item in every collection: (label, attributes, secret, type)"""
    cols = prop(bus, ROOT, SERVICE, 'Collections')
    locked = [c for c in cols if prop(bus, c, COLLECTION, 'Locked')]
    if locked:
        print('Unlock the wallet to copy from when it asks.')
        _, prompt = call(bus, ROOT, SERVICE, 'Unlock',
                         GLib.Variant('(ao)', (locked,)), '(aoo)')
        if not run_prompt(bus, prompt):
            die('the wallet to copy from stayed locked')
    _, session = call(bus, ROOT, SERVICE, 'OpenSession',
                      GLib.Variant('(sv)', ('plain', GLib.Variant('s', ''))),
                      '(vo)')
    items = []
    for c in cols:
        for path in prop(bus, c, COLLECTION, 'Items'):
            label = prop(bus, path, ITEM, 'Label')
            attrs = prop(bus, path, ITEM, 'Attributes')
            (secret,) = call(bus, path, ITEM, 'GetSecret',
                             GLib.Variant('(o)', (session,)), '((oayays))')
            _, _, value, ctype = secret
            items.append((label, dict(attrs), bytes(value), ctype))
    call(bus, session, 'org.freedesktop.Secret.Session', 'Close')
    return items


def tell_apart(items):
    """oo7 0.4.3 keeps one item per set of attributes on disk, and only
    finds an item by all of them. Items that share theirs (KWallet's own
    entries, which KDE apps read through KWallet, not oo7) get their name
    as one more, so none is lost; the rest stay as they are, so the apps
    that stored them still find them. Returns how many were changed."""
    seen = {}
    for _, attrs, _, _ in items:
        key = frozenset(attrs.items())
        seen[key] = seen.get(key, 0) + 1
    changed = 0
    for label, attrs, _, _ in items:
        if seen[frozenset(attrs.items())] > 1:
            attrs['c8:name'] = label
            changed += 1
    return changed


def source_is_oo7(bus):
    try:
        (pid,) = bus.call_sync('org.freedesktop.DBus', '/org/freedesktop/DBus',
                               'org.freedesktop.DBus',
                               'GetConnectionUnixProcessID',
                               GLib.Variant('(s)', (SECRETS,)),
                               GLib.VariantType('(u)'),
                               Gio.DBusCallFlags.NONE, -1, None).unpack()
        with open(f'/proc/{pid}/comm') as f:
            return f.read().strip().startswith('oo7')
    except (GLib.Error, OSError):
        return False


def ask(prompt):
    askpass = shutil.which('c8-askpass') or os.environ.get('SSH_ASKPASS')
    if not askpass:
        die('no c8-askpass to ask for the password with')
    r = subprocess.run([askpass, prompt], stdout=subprocess.PIPE)
    if r.returncode != 0:
        die('cancelled')
    return r.stdout.rstrip(b'\n')


def wallet_password(exists):
    if exists:
        return ask('Password of your cont8nuum wallet:')
    while True:
        first = ask('A password for your new cont8nuum wallet '
                    '(your login password lets it open by itself later):')
        if not first:
            continue
        if ask('Type the wallet password again:') == first:
            return first
        print('The two passwords were different; try again.')


def start_private_daemon(password):
    """oo7-daemon on a bus of its own, given the password through a pty"""
    bus_proc = subprocess.Popen(['dbus-daemon', '--session', '--nofork',
                                 '--print-address=1'],
                                stdout=subprocess.PIPE)
    address = bus_proc.stdout.readline().decode().strip()
    pid, fd = pty.fork()
    if pid == 0:
        os.environ['DBUS_SESSION_BUS_ADDRESS'] = address
        os.execv(DAEMON, [DAEMON, '--login'])
    # It asks once it starts; answer then
    out = b''
    deadline = time.time() + 10
    while b'password' not in out and time.time() < deadline:
        r, _, _ = select.select([fd], [], [], 0.2)
        if r:
            try:
                out += os.read(fd, 4096)
            except OSError:
                break
    os.write(fd, password + b'\n')
    bus = Gio.DBusConnection.new_for_address_sync(
        address, Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT |
        Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION, None, None)
    # Ready once it owns the name; gone if the password was wrong
    deadline = time.time() + 15
    while time.time() < deadline:
        r, _, _ = select.select([fd], [], [], 0.2)
        if r:
            try:
                out += os.read(fd, 4096)
            except OSError:
                pass
        done, status = os.waitpid(pid, os.WNOHANG)
        if done:
            bus_proc.terminate()
            if b'IncorrectSecret' in out:
                die('that is not the wallet password')
            die('oo7-daemon stopped: ' + out.decode(errors='replace')[-300:])
        (owned,) = bus.call_sync('org.freedesktop.DBus', '/org/freedesktop/DBus',
                                 'org.freedesktop.DBus', 'NameHasOwner',
                                 GLib.Variant('(s)', (SECRETS,)),
                                 GLib.VariantType('(b)'),
                                 Gio.DBusCallFlags.NONE, -1, None).unpack()
        if owned:
            return bus, pid, fd, bus_proc
    die('oo7-daemon did not start')


def write_all(bus, items):
    (default,) = call(bus, ROOT, SERVICE, 'ReadAlias',
                      GLib.Variant('(s)', ('default',)), '(o)')
    if default == '/':
        die('the oo7 wallet has no default collection')
    _, session = call(bus, ROOT, SERVICE, 'OpenSession',
                      GLib.Variant('(sv)', ('plain', GLib.Variant('s', ''))),
                      '(vo)')
    for label, attrs, value, ctype in items:
        # Only an earlier copy of this same item gives way: KWallet gives
        # many items the same attributes, so replacing by those alone
        # would keep just one of each
        # (with or without the c8:name an earlier run may have added)
        base = {k: v for k, v in attrs.items() if k != 'c8:name'}
        for look in (attrs, base):
            found, _ = call(bus, ROOT, SERVICE, 'SearchItems',
                            GLib.Variant('(a{ss})', (look,)), '(aoao)')
            for path in found:
                old = dict(prop(bus, path, ITEM, 'Attributes'))
                old.pop('c8:name', None)
                if prop(bus, path, ITEM, 'Label') == label and old == base:
                    call(bus, path, ITEM, 'Delete')
        props = {
            'org.freedesktop.Secret.Item.Label': GLib.Variant('s', label),
            'org.freedesktop.Secret.Item.Attributes':
                GLib.Variant('a{ss}', attrs),
        }
        _, prompt = call(bus, default, COLLECTION, 'CreateItem',
                         GLib.Variant('(a{sv}(oayays)b)',
                                      (props, (session, b'', value, ctype),
                                       False)), '(oo)')
        if prompt != '/':
            die('oo7 asked for a prompt while storing')
    return default, session


def check(bus, default, session, items):
    """Reads every copied item back and compares"""
    bad = 0
    for label, attrs, value, ctype in items:
        found, _ = call(bus, ROOT, SERVICE, 'SearchItems',
                        GLib.Variant('(a{ss})', (attrs,)), '(aoao)')
        ok = False
        for path in found:
            if prop(bus, path, ITEM, 'Label') != label:
                continue
            (secret,) = call(bus, path, ITEM, 'GetSecret',
                             GLib.Variant('(o)', (session,)), '((oayays))')
            if bytes(secret[2]) == value:
                ok = True
        bad += not ok
    return bad


# Chromium-based browsers name themselves in lowercase to libsecret
LIBSECRET_APP = {'Chrome': 'chrome', 'Chromium': 'chromium'}


def bridged(label, attrs):
    """Where an app looks for a key KWallet holds, when it asks the Secret
    Service instead: Chromium and Electron apps keep theirs in KWallet as
    "NAME Keys/NAME Safe Storage", and the KWallet portal keeps a Flatpak
    app's as "xdg-desktop-portal/APP_ID". (label, attributes) or None."""
    server, user = attrs.get('server'), attrs.get('user')
    if server and user and server.endswith(' Keys') and \
            user == server[:-5] + ' Safe Storage':
        name = server[:-5]
        return (f'{name} Safe Storage',
                {'application': LIBSECRET_APP.get(name, name),
                 'xdg:schema': 'chrome_libsecret_os_crypt_password_v2'})
    if server == 'xdg-desktop-portal' and user:
        return (f'Secret Portal token for {user}',
                {'xdg:schema': 'org.freedesktop.Secret.Generic',
                 'app_id': user})
    return None


def bridge(bus, items):
    """Gives each app the key it had under KWallet where it looks for it
    now, so what it saved in Plasma still opens here and the other way
    round. One already there with another value gives way: Plasma's is
    the one its data is locked with."""
    (default,) = call(bus, ROOT, SERVICE, 'ReadAlias',
                      GLib.Variant('(s)', ('default',)), '(o)')
    _, session = call(bus, ROOT, SERVICE, 'OpenSession',
                      GLib.Variant('(sv)', ('plain', GLib.Variant('s', ''))),
                      '(vo)')
    done = []
    for label, attrs, value, ctype in items:
        to = bridged(label, attrs)
        if to is None:
            continue
        new_label, new_attrs = to
        found, _ = call(bus, ROOT, SERVICE, 'SearchItems',
                        GLib.Variant('(a{ss})', (new_attrs,)), '(aoao)')
        same = False
        for path in found:
            (secret,) = call(bus, path, ITEM, 'GetSecret',
                             GLib.Variant('(o)', (session,)), '((oayays))')
            if bytes(secret[2]) == value:
                same = True
            else:
                call(bus, path, ITEM, 'Delete')
        if not same:
            props = {
                'org.freedesktop.Secret.Item.Label':
                    GLib.Variant('s', new_label),
                'org.freedesktop.Secret.Item.Attributes':
                    GLib.Variant('a{ss}', new_attrs),
            }
            call(bus, default, COLLECTION, 'CreateItem',
                 GLib.Variant('(a{sv}(oayays)b)',
                              (props, (session, b'', value, ctype), True)),
                 '(oo)')
        done.append(new_label)
    call(bus, session, 'org.freedesktop.Secret.Session', 'Close')
    return done


def private_bus():
    proc = subprocess.Popen(['dbus-daemon', '--session', '--nofork',
                             '--print-address=1'], stdout=subprocess.PIPE,
                            stderr=subprocess.DEVNULL)
    address = proc.stdout.readline().decode().strip()
    bus = Gio.DBusConnection.new_for_address_sync(
        address, Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT |
        Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION, None, None)
    return bus, address, proc


def has_owner(bus, name):
    return bus.call_sync('org.freedesktop.DBus', '/org/freedesktop/DBus',
                         'org.freedesktop.DBus', 'NameHasOwner',
                         GLib.Variant('(s)', (name,)), GLib.VariantType('(b)'),
                         Gio.DBusCallFlags.NONE, -1, None).unpack()[0]


def start_kwallet():
    """KWallet's ksecretd on a bus of its own, to read from"""
    if not os.access(KSECRETD, os.X_OK):
        die(f'no {KSECRETD} to read KWallet with')
    bus, address, bus_proc = private_bus()
    proc = subprocess.Popen([KSECRETD],
                            env=dict(os.environ,
                                     DBUS_SESSION_BUS_ADDRESS=address),
                            stdout=subprocess.DEVNULL,
                            stderr=subprocess.DEVNULL)
    deadline = time.time() + 15
    while not has_owner(bus, SECRETS):
        if time.time() > deadline or proc.poll() is not None:
            proc.kill()
            bus_proc.terminate()
            die('KWallet did not start')
        time.sleep(0.2)

    def stop():
        proc.terminate()
        proc.wait()
        bus_proc.terminate()
        bus_proc.wait()
    return bus, stop


def clear(bus, keyring):
    """Empties the default collection, keeping a copy of the file"""
    if os.path.exists(keyring):
        backup = keyring + '.bak-' + time.strftime('%Y%m%d-%H%M%S')
        shutil.copy2(keyring, backup)
        print(f'Kept a copy of the old wallet as {backup}.')
    (default,) = call(bus, ROOT, SERVICE, 'ReadAlias',
                      GLib.Variant('(s)', ('default',)), '(o)')
    if default == '/':
        die('the oo7 wallet has no default collection')
    paths = prop(bus, default, COLLECTION, 'Items')
    for path in paths:
        call(bus, path, ITEM, 'Delete')
    print(f'Removed {len(paths)} items from the oo7 wallet.')


def main():
    clearing = sys.argv[1:] == ['--clear']
    if sys.argv[1:] and not clearing:
        die('usage: c8-wallet-import [--clear]')
    data = os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share')
    target = os.path.join(data, 'keyrings', 'v1', 'login.keyring')

    session_bus = Gio.bus_get_sync(Gio.BusType.SESSION)
    running = source_is_oo7(session_bus)
    if running:
        source, stop = start_kwallet()
        try:
            items = read_all(source)
        finally:
            stop()
    else:
        if not os.access(DAEMON, os.X_OK):
            die('oo7-daemon is not installed (zypper in oo7-daemon)')
        items = read_all(session_bus)
    print(f'Read {len(items)} items to copy.')
    alike = tell_apart(items)
    if alike:
        print(f'{alike} of them have the same attributes as another; they '
              'get their name as an extra c8:name attribute.')
    if not items:
        return

    if running:
        # cont8nuum: the wallet is open already
        if clearing:
            clear(session_bus, target)
        default, session = write_all(session_bus, items)
        bad = check(session_bus, default, session, items)
        keys = bridge(session_bus, items)
    else:
        password = wallet_password(os.path.exists(target))
        bus, pid, fd, bus_proc = start_private_daemon(password)
        try:
            if clearing:
                clear(bus, target)
            default, session = write_all(bus, items)
            bad = check(bus, default, session, items)
            keys = bridge(bus, items)
        finally:
            os.kill(pid, 15)
            os.waitpid(pid, 0)
            os.close(fd)
            bus_proc.terminate()
            bus_proc.wait()
    if bad:
        die(f'{bad} of {len(items)} items did not read back the same')
    print(f'Copied {len(items)} items into {target}; all read back the same.')
    if keys:
        print('Apps that find their keys as before: ' + ', '.join(keys) + '.')


if __name__ == '__main__':
    main()
