#!/usr/bin/env python3
# summary: Ask before allowing a Thunderbolt device.
"""Thunderbolt consent on the USB protection page. USB permission stays independent.

    starchaser thunderbolt status
    starchaser thunderbolt allow|remember|forget UUID CONNECTION
    starchaser thunderbolt watch    started by the existing USB question service
"""
import json
import html
import os
import re
import runpy
import select
import subprocess
import sys
import threading
import time
from pathlib import Path

LIB = Path('/usr/local/lib/starchaser')
if not (LIB / 'thunderbolt.py').is_file():
    LIB = Path(__file__).resolve().parents[1] / 'system/usr/local/lib/starchaser'
sys.path.insert(0, str(LIB))
from thunderbolt import Bolt, ThunderboltError, WAITING, unlocked_local

NOTIFICATION_TIMEOUT = 10
NOTIFICATION_OWNER = re.compile(r':[0-9]+\.[0-9]+')
THUNDERBOLT_DEVICES = Path('/sys/bus/thunderbolt/devices')


class NotificationDeliveryError(Exception):
    pass


def notification_owner():
    result = subprocess.run(['busctl', '--user', '--json=short', '--timeout=2', 'call',
                             'org.freedesktop.DBus', '/org/freedesktop/DBus', 'org.freedesktop.DBus',
                             'GetNameOwner', 's', 'org.freedesktop.Notifications'],
                            capture_output=True, text=True, timeout=3)
    try:
        owner = json.loads(result.stdout)['data'][0]
        if result.returncode == 0 and isinstance(owner, str) and NOTIFICATION_OWNER.fullmatch(owner):
            return owner
    except (ValueError, KeyError, IndexError, TypeError):
        pass
    raise NotificationDeliveryError('No notification service owner')


def notification_id(proc):
    """Read a complete ID within one deadline, including when only part of it arrives."""
    deadline = time.monotonic() + NOTIFICATION_TIMEOUT
    value = bytearray()
    while True:
        remaining = deadline - time.monotonic()
        if remaining <= 0 or not select.select([proc.stdout], [], [], remaining)[0]:
            raise NotificationDeliveryError('Notification delivery timed out')
        char = os.read(proc.stdout.fileno(), 1)
        if char == b'\n':
            if not value or not 0 < int(value) <= 4294967295:
                raise NotificationDeliveryError('No notification ID')
            return value.decode('ascii')
        if not char or char not in b'0123456789' or len(value) >= 10:
            raise NotificationDeliveryError('Invalid notification ID')
        value.extend(char)


def notification_answer(proc, valid):
    """Wait for a person without waiting forever on a departed service or stale ticket."""
    value = bytearray()
    while valid():
        if not select.select([proc.stdout], [], [], 0.5)[0]:
            continue
        chunk = os.read(proc.stdout.fileno(), 64)
        if not chunk:
            if valid():
                return value.decode('ascii').strip()
            break
        value.extend(chunk)
        if len(value) > 64 or not value.isascii():
            break
    raise NotificationDeliveryError('Notification question is no longer current')


def finish_notification(proc):
    """Do not leave a failed delivery or an invalidated question's child running."""
    try:
        if proc.poll() is None:
            proc.terminate()
        try:
            proc.wait(timeout=1)
        except subprocess.TimeoutExpired:
            proc.kill()
            proc.wait(timeout=1)
    finally:
        proc.stdout.close()


def status():
    try:
        hardware = next(THUNDERBOLT_DEVICES.iterdir(), None) is not None
    except OSError:
        hardware = False
    try:
        return {'hardware': hardware, 'available': True, 'devices': Bolt().devices()}
    except ThunderboltError as e:
        return {'hardware': hardware, 'available': False, 'devices': [], 'message': str(e)}


def notification(args, owner=None):
    """The private notification credential is an inherited descriptor, never a command argument."""
    path = Path(os.environ.get('XDG_RUNTIME_DIR', f'/run/user/{os.getuid()}')) / 'starchaser-notifications' / 'token'
    with path.open('rb') as token:
        destination = ['--destination=' + owner] if owner else []
        return subprocess.Popen(['starchaser', 'notify', f'--credential-fd={token.fileno()}', *destination, '-a', 'Starchaser',
                                 '-p', *args], pass_fds=(token.fileno(),), stdout=subprocess.PIPE, text=True)


def close_notice(card):
    owner, nid = card
    if not NOTIFICATION_OWNER.fullmatch(owner) or not str(nid).isdigit():
        return
    try:
        # IDs are scoped to the unique owner; a replacement may reuse them immediately.
        subprocess.run(['gdbus', 'call', '--session', '--dest', owner,
                        '--object-path', '/org/freedesktop/Notifications',
                        '--method', 'org.freedesktop.Notifications.CloseNotification', str(nid)],
                       capture_output=True, timeout=5)
    except (OSError, subprocess.SubprocessError):
        pass  # Best effort: a departed owner has already lost its on-screen cards.


class Questions:
    """One question per attachment, with late replies invalidated on lock/removal/authorization."""
    def __init__(self, show=None, close=None):
        self.lock = threading.RLock()
        self.live, self.seen, self.cards = {}, set(), {}
        self.show = show or self.start_question
        self.close = close or self.close_question

    def current(self, key, ticket=None):
        with self.lock:
            return key in self.live and (ticket is None or self.live[key] is ticket)

    def reconcile(self, devices, unlocked):
        waiting = {(d['uid'], d['connected']): d for d in devices if d['status'] in WAITING}
        with self.lock:
            for key in list(self.live):
                if not unlocked or key not in waiting:
                    self.live.pop(key)
                    self.close(key)
                    if not unlocked:
                        self.seen.discard(key)  # unanswered questions return after unlock
            self.seen.intersection_update(waiting)
            if not unlocked:
                return
            for key, d in waiting.items():
                if key not in self.seen:
                    self.seen.add(key)
                    self.live[key] = object()
                    self.show(d)

    def close_question(self, key):
        card = self.cards.pop(key, None)
        if card:
            threading.Thread(target=close_notice, args=(card,), daemon=True).start()

    def retry(self, key, ticket):
        with self.lock:
            if self.current(key, ticket):
                self.seen.discard(key)
                self.live.pop(key, None)
                self.close(key)

    def start_question(self, d):
        key = (d['uid'], d['connected'])
        threading.Thread(target=self.question, args=(d, self.live[key]), daemon=True).start()

    def question(self, d, ticket):
        key = (d['uid'], d['connected'])
        proc = None
        try:
            if not self.current(key, ticket) or not unlocked_local():
                self.retry(key, ticket)
                return
            owner = notification_owner()
            proc = notification(['-u', 'critical', '-i', 'drive-removable-media', '-t', '0',
                                 '-A', 'once=Allow for now', '-A', 'always=Always allow', '-A', 'block=Keep blocked', '-w',
                                 'New Thunderbolt device: allow ' + d['name'] + '?',
                                 html.escape(d['name']) + ' is waiting. Allowing it asks for an administrator password. '
                                 'USB devices plugged into it may ask separately.'], owner=owner)
            nid = notification_id(proc)
            card = (owner, nid)
            with self.lock:
                if self.current(key, ticket) and unlocked_local():
                    self.cards[key] = card
                else:
                    close_notice(card)
                    self.retry(key, ticket)
                    return
            # Save the known delivery target before any fallible ownership check.
            if notification_owner() != owner:
                raise NotificationDeliveryError('Notification owner changed during delivery')
            answer = notification_answer(proc, lambda: self.current(key, ticket) and notification_owner() == owner)
            if proc.wait(timeout=2) != 0:
                self.retry(key, ticket)
                return
            with self.lock:
                valid = (self.current(key, ticket) and self.cards.get(key) == card
                         and notification_owner() == owner)
                if valid:
                    self.cards.pop(key, None)
                    self.live.pop(key, None)  # answered: preserve this connection's refusal across lock/unlock
                else:
                    self.retry(key, ticket)
            if valid and answer in ('once', 'always') and unlocked_local():
                try:
                    # Use the existing USB service's desktop-session password launcher.
                    usb = runpy.run_path(str(Path(__file__).resolve().with_name('starchaser-usb')))
                    result = usb['session_change'](['allow' if answer == 'once' else 'remember', d['uid'], str(d['connected'])],
                                                   admin_command='thunderbolt-device')
                    failed = result.returncode not in (0, 126)
                except Exception:
                    # An unexpected launcher failure must give the person the Settings recovery route too.
                    failed = True
                if failed:
                    p = notification(['-u', 'normal', 'Thunderbolt device still blocked',
                                      'Check the device in Settings > Privacy > USB protection.'])
                    try:
                        p.communicate(timeout=NOTIFICATION_TIMEOUT)
                    finally:
                        finish_notification(p)
        except (OSError, subprocess.SubprocessError, NotificationDeliveryError):
            # A question that could not appear at sign-in must retry once the desktop is ready.
            self.retry(key, ticket)
        finally:
            if proc is not None:
                finish_notification(proc)


QUIET = 300   # seconds between looks when nothing waits: boltd's and logind's signals wake the loop at once
BUSY = 5      # while a device waits or a question is up: a question that couldn't show is retried this soon


def watch_step(questions, read=None, unlocked=None):
    """One look: the devices (only when the computer has Thunderbolt at all), the lock state only when a device is
    waiting or a question is up. Returns how long to wait for a signal before the next look."""
    read = read or (lambda: status()['devices'] if hardware_present() else [])
    unlocked = unlocked or unlocked_local
    devices = read()
    waiting = any(d['status'] in WAITING for d in devices)
    questions.reconcile(devices, unlocked() if waiting or questions.live else False)
    return BUSY if waiting or questions.live else QUIET


def hardware_present():
    try:
        return next(THUNDERBOLT_DEVICES.iterdir(), None) is not None
    except OSError:
        return False


def watch():
    questions = Questions()
    filters = ["type='signal',sender='org.freedesktop.bolt'",
               "type='signal',sender='org.freedesktop.login1'"]
    while True:
        try:
            with subprocess.Popen(['dbus-monitor', '--system', '--profile', *filters],
                                  stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) as monitor:
                while monitor.poll() is None:
                    wait = watch_step(questions)
                    if select.select([monitor.stdout], [], [], wait)[0]:
                        os.read(monitor.stdout.fileno(), 65536)
        except (OSError, subprocess.SubprocessError, ThunderboltError):
            questions.reconcile([], False)
        time.sleep(5)


def main(args):
    if args in (['--help'], ['-h'], ['help']):
        print(__doc__.strip())
        return 0
    if args == ['status']:
        print(json.dumps(status()))
        return 0
    if args == ['watch']:
        watch()
        return 0
    if len(args) == 3 and args[0] in ('allow', 'remember', 'forget'):
        return subprocess.run(['pkexec', '/usr/local/lib/starchaser/starchaser-admin',
                               'thunderbolt-device', *args]).returncode
    print(__doc__.strip(), file=sys.stderr)
    return 2


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