#!/usr/bin/env python3
# summary: Report the lock screen's confirmed state to its graphical login session.
"""Usage: starchaser session lock state true|false

Report the lock screen's confirmed state to its local graphical login session.
"""
import json
import os
import subprocess
import sys


def run(*args):
    try:
        result = subprocess.run(args, capture_output=True, text=True, timeout=3)
    except (OSError, subprocess.SubprocessError) as error:
        raise ValueError("The login service didn't answer.") from error
    if result.returncode:
        raise ValueError("The locked state couldn't be reported to the login service.")
    return result.stdout


def graphical_session(uid):
    rows = json.loads(run('loginctl', 'list-sessions', '--json=short'))
    candidates = []
    for row in rows:
        if row.get('uid') != uid or row.get('class') != 'user' or not row.get('seat'):
            continue
        session = str(row['session'])
        info = run('loginctl', 'show-session', session, '-p', 'Active', '-p', 'Class', '-p', 'Remote', '-p', 'Type')
        fields = dict(line.split('=', 1) for line in info.splitlines() if '=' in line)
        if fields.get('Active') == 'yes' and fields.get('Class') == 'user' and fields.get('Remote') != 'yes' and fields.get('Type') in ('wayland', 'x11'):
            candidates.append(session)
    preferred = os.environ.get('XDG_SESSION_ID', '')
    if preferred in candidates:
        return preferred
    if len(candidates) != 1:
        raise ValueError("The active desktop login couldn't be identified.")
    return candidates[0]


def set_hint(locked, uid=None):
    session = graphical_session(os.getuid() if uid is None else uid)
    result = json.loads(run('busctl', '--system', '--timeout=2s', '--json=short', 'call', 'org.freedesktop.login1',
                            '/org/freedesktop/login1', 'org.freedesktop.login1.Manager', 'GetSession', 's', session))
    path = result['data'][0]
    if not isinstance(path, str) or not path.startswith('/org/freedesktop/login1/session/'):
        raise ValueError("The desktop login address wasn't reported.")
    run('busctl', '--system', '--timeout=2s', 'call', 'org.freedesktop.login1', path,
        'org.freedesktop.login1.Session', 'SetLockedHint', 'b', 'true' if locked else 'false')


def main(args):
    if args in (['--help'], ['-h'], ['help']):
        print(__doc__)
        return 0
    if len(args) != 1 or args[0] not in ('true', 'false'):
        print(__doc__, file=sys.stderr)
        return 2
    try:
        set_hint(args[0] == 'true')
        return 0
    except (ValueError, KeyError, TypeError, IndexError) as error:
        print(str(error), file=sys.stderr)
        return 1


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