#!/usr/bin/env python3
"""Kit Remote local access management for the person at this computer.

Talks to the Kit Remote host service over /run/kit-remote/local-access.sock. The service checks with the
kernel (SO_PEERCRED) that you are the user signed in at the console (or root); other local users are refused.

  kit-remote-access list                 people with saved access, blocks and live sessions
  kit-remote-access status               service status (computer ID, counts, core hash)
  kit-remote-access revoke <ref>         remove one person's saved access and end their sessions
  kit-remote-access end <ref>            end one live session (saved access stays)
  kit-remote-access unblock <ref>        lift a block; the person must be approved again on screen
  kit-remote-access revoke-all           remove everyone's saved access and end every session
  sudo kit-remote-access clear-remote-control
                                         re-enable full computer file access after remote access

There is no command to approve or allow access: approval happens only in the on-screen prompt.

After a remote desktop or file session on your account, a program it started or left in your files (for
example in autostart) could act as you. Until root runs clear-remote-control, full computer file access is
refused, and without sudo, list shows only live sessions and unblock is refused. Check for programs and
files you did not put there first.
Add --json to print the raw reply.
"""
import json
import os
import socket
import sys

SOCKET = os.environ.get('KIT_REMOTE_ACCESS_SOCKET', '/run/kit-remote/local-access.sock')
COMMANDS = {'list': 'list', 'status': 'status', 'revoke': 'revoke', 'end': 'end-session', 'unblock': 'unblock', 'revoke-all': 'revoke-all',
            'clear-remote-control': 'clear-remote-control'}
EXPLAIN = {
    'end-remote-desktop-sessions-first': 'end the remote desktop sessions first (kit-remote-access list, then end <ref>).',
    'end-remote-sessions-first': 'end the remote desktop and file sessions first (kit-remote-access list, then end <ref>).',
    'needs-root-after-remote-control': 'this account was accessed remotely; run the command with sudo.',
    'storage-failed': 'the Kit Remote service could not save the change; full computer file access stays off.',
    'needs-root': 'run this command with sudo.',
}


def call(message):
    with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
        s.settimeout(5)
        s.connect(SOCKET)
        s.sendall((json.dumps(message) + '\n').encode())
        data = b''
        while not data.endswith(b'\n'):
            chunk = s.recv(65536)
            if not chunk:
                break
            data += chunk
    return json.loads(data.decode() or '{"ok": false, "error": "no-reply"}')


def show(reply, command):
    if not reply.get('ok'):
        error = str(reply.get('error', 'unknown error'))
        print('Refused: ' + EXPLAIN.get(error, error), file=sys.stderr)
        return 1
    if command == 'list':
        people = reply.get('people') or []
        if reply.get('restricted'):
            print('This account was accessed remotely, so saved access is hidden: %s saved, %s blocked. Use sudo to see it.'
                  % (reply.get('grantsCount'), reply.get('blockedRequesters')))
            if not people:
                print('No live sessions.')
        elif not people:
            print('Nobody has saved access to this computer.')
        for p in people:
            access = ', '.join(p.get('scopes') or []) or 'no saved access'
            until = p.get('expiresAt')
            line = '%s  %s  [%s]' % (p['ref'], p.get('name', 'Kit Remote user'), access)
            if p.get('scopes'):
                line += '  until ' + (until or 'revoked (no end date)')
            if p.get('blocked'):
                line += '  BLOCKED until ' + (p.get('blockedUntil') or 'unblocked')
            print(line)
            for s in p.get('sessions') or []:
                print('    session %s  %s  since %s' % (s['ref'], s.get('scope'), s.get('since')))
    elif command == 'status':
        for key in ('kitRemoteId', 'activeSessions', 'grantsCount', 'blockedRequesters', 'coreHash'):
            if key in reply:
                print('%s: %s' % (key, reply[key]))
    else:
        print('Done.')
    return 0


def main(argv):
    raw = '--json' in argv
    argv = [a for a in argv if a != '--json']
    if not argv or argv[0] not in COMMANDS or (argv[0] in ('revoke', 'end', 'unblock') and len(argv) != 2):
        print(__doc__, file=sys.stderr)
        return 2
    message = {'cmd': COMMANDS[argv[0]], 'id': 'cli'}
    if len(argv) == 2:
        message['ref'] = argv[1]
    try:
        reply = call(message)
    except (ConnectionResetError, BrokenPipeError):
        reply = {'ok': False, 'error': 'not-authorized'}
    except OSError as e:
        print('Kit Remote host service is not reachable: %s' % e.strerror, file=sys.stderr)
        return 3
    if reply.get('error') == 'not-authorized' and not raw:
        print('Refused: only the person signed in at this computer (or root) can manage Kit Remote access.', file=sys.stderr)
        return 1
    if raw:
        print(json.dumps(reply, indent=2))
        return 0 if reply.get('ok') else 1
    return show(reply, argv[0])


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))
