#!/usr/bin/env python3
# summary: Deliver a desktop notification.
"""Deliver system notices with a private credential only for Starchaser's own callers."""
import argparse
import hashlib
import hmac
import json
import fcntl
import os
import re
import secrets
import stat
import sys
from pathlib import Path


def credential(runtime, renew=False):
    folder = Path(runtime) / 'starchaser-notifications'
    folder.mkdir(mode=0o700, exist_ok=True)
    info = folder.lstat()
    if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
        raise PermissionError("Notification runtime folder isn't private")
    with (folder / 'lock').open('a') as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        token = folder / 'token'
        if not renew:
            try:
                return token.read_text().strip()
            except FileNotFoundError:
                pass
        value = secrets.token_hex(32)
        temporary = folder / f'.token.{os.getpid()}.tmp'
        try:
            fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
            with os.fdopen(fd, 'w') as stream:
                stream.write(value + '\n')
                stream.flush()
                os.fsync(stream.fileno())
            os.replace(temporary, token)
        finally:
            temporary.unlink(missing_ok=True)
        return value



def supplied_credential(args):
    """Only a caller possessing the private session key can request a proof.

    Executable arguments cannot authenticate interpreted code: the process can
    rewrite them. Own call sites open the private key as a descriptor instead.
    As with the session bus itself, arbitrary code with access to the account's
    private files is inside this boundary. Sandboxed apps get neither the key
    nor a signing service that guesses their identity from process arguments.
    """
    if not args or not args[0].startswith('--credential-fd='):
        return args, None
    option, *args = args
    try:
        fd = int(option.split('=', 1)[1])
    except ValueError:
        return args, None
    if fd < 3:
        return args, None
    try:
        with os.fdopen(fd, 'r') as stream:
            info = os.fstat(stream.fileno())
            if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
                return args, None
            key = stream.read(66).strip()
            if len(key) == 64 and all(c in '0123456789abcdef' for c in key):
                return args, key
    except (OSError, ValueError, UnicodeError):
        pass
    return args, None


def notification_options(args):
    parser = argparse.ArgumentParser(prog="starchaser notify", add_help=False, exit_on_error=False, allow_abbrev=False)
    for short, long in [('-a', '--app-name'), ('-i', '--icon'), ('-t', '--expire-time'), ('-u', '--urgency'), ('-c', '--category'), ('-r', '--replace-id')]:
        parser.add_argument(short, long)
    parser.add_argument('-h', '--hint', action='append', default=[])
    parser.add_argument('-A', '--action', action='append', default=[])
    for short, long in [('-p', '--print-id'), ('-w', '--wait'), ('-e', '--transient')]:
        parser.add_argument(short, long, action='store_true')
    parser.add_argument('words', nargs='*')
    return parser.parse_args(args)


def proof_args(args, token):
    parsed = notification_options(args)
    if not parsed.app_name or not 1 <= len(parsed.words) <= 2:
        raise ValueError('A system notice needs an app name and title.')
    hints = {}
    for item in parsed.hint:
        kind, key, value = item.split(':', 2)
        if key.startswith('x-starchaser-') and key != 'x-starchaser-proof':
            hints[key] = value if kind == 'string' else value in ('true', '1') if kind == 'boolean' else int(value)
    nonce = secrets.token_hex(16)
    hints['x-starchaser-nonce'] = nonce
    actions = [part.split('=', 1) if '=' in part else [str(i), part] for i, part in enumerate(parsed.action)]
    payload = {'actions': sorted(actions), 'app': parsed.app_name, 'summary': parsed.words[0],
               'body': parsed.words[1] if len(parsed.words) > 1 else '', 'hints': dict(sorted(hints.items()))}
    text = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
    signature = hmac.new(token.encode(), text.encode(), hashlib.sha256).hexdigest()
    return ['-h', 'string:x-starchaser-nonce:' + nonce, '-h', 'string:x-starchaser-proof:' + signature] + args


def deliver_to_owner(args, owner):
    """Bind delivery and action signals to one unique bus owner, even across replacement."""
    if not re.fullmatch(r':[0-9]+\.[0-9]+', owner):
        raise ValueError('A unique notification service owner is required.')
    import gi
    gi.require_version('Gio', '2.0')
    from gi.repository import Gio, GLib
    parsed = notification_options(args)
    if not 1 <= len(parsed.words) <= 2:
        raise ValueError('A notification needs a title and optional body.')
    hints = {'urgency': GLib.Variant('y', {'low': 0, 'normal': 1, 'critical': 2}[parsed.urgency or 'normal'])}
    for hint in parsed.hint:
        kind, key, value = hint.split(':', 2)
        signature, convert = {'string': ('s', str), 'boolean': ('b', lambda v: v in ('true', '1')),
                              'int': ('i', int), 'double': ('d', float), 'byte': ('y', int)}[kind]
        hints[key] = GLib.Variant(signature, convert(value))
    if parsed.category:
        hints['category'] = GLib.Variant('s', parsed.category)
    if parsed.transient:
        hints['transient'] = GLib.Variant('b', True)
    actions = [part for i, action in enumerate(parsed.action)
               for part in (action.split('=', 1) if '=' in action else [str(i), action])]
    bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
    loop = GLib.MainLoop()
    nid = None
    def signal(conn, sender, path, interface, name, parameters):
        values = parameters.unpack()
        if values[0] != nid:
            return
        if name == 'ActionInvoked':
            print(values[1], flush=True)
            loop.quit()
        elif name == 'NotificationClosed':
            loop.quit()
    # Subscribe before Notify so a fast action/close cannot be missed.
    subscription = bus.signal_subscribe(owner, 'org.freedesktop.Notifications', None,
        '/org/freedesktop/Notifications', None, Gio.DBusSignalFlags.NONE, signal)
    try:
        reply = bus.call_sync(owner, '/org/freedesktop/Notifications', 'org.freedesktop.Notifications', 'Notify',
            GLib.Variant('(susssasa{sv}i)', (parsed.app_name or '', int(parsed.replace_id or 0), parsed.icon or '',
                parsed.words[0], parsed.words[1] if len(parsed.words) > 1 else '', actions, hints,
                int(parsed.expire_time) if parsed.expire_time is not None else -1)),
            GLib.VariantType.new('(u)'), Gio.DBusCallFlags.NO_AUTO_START, 5000, None)
        nid, = reply.unpack()
        if parsed.print_id:
            print(nid, flush=True)
        if parsed.wait:
            loop.run()
    finally:
        bus.signal_unsubscribe(subscription)
    return 0


def main():
    args, token = supplied_credential(sys.argv[1:])
    owner = None
    if args and args[0].startswith('--destination='):
        owner, args = args[0].split('=', 1)[1], args[1:]
    if args in (['--help'], ['-h']):
        print('Usage: starchaser notify [notify-send options] TITLE [BODY]\nDeliver a notification. System identity is restricted to Starchaser callers.')
        return 0
    runtime = os.environ.get('XDG_RUNTIME_DIR', f'/run/user/{os.getuid()}')
    if args == ['--init']:
        credential(runtime)
        return 0
    # Drop caller-supplied copies, even from a trusted script: the credential always comes from this session.
    clean = []
    i = 0
    while i < len(args):
        if args[i] in ('-h', '--hint') and i + 1 < len(args) and any(':' + key + ':' in args[i + 1] for key in ('x-starchaser-token', 'x-starchaser-proof', 'x-starchaser-nonce')):
            i += 2
            continue
        if args[i].startswith('--hint=') and any(':' + key + ':' in args[i] for key in ('x-starchaser-token', 'x-starchaser-proof', 'x-starchaser-nonce')):
            i += 1
            continue
        clean.append(args[i])
        i += 1
    if token:
        try:
            clean = proof_args(clean, token)
        except (ValueError, argparse.ArgumentError):
            pass  # Invalid arguments remain ordinary and are reported by notify-send.
    if owner is not None:
        return deliver_to_owner(clean, owner)
    os.execv('/usr/bin/notify-send', ['notify-send', *clean])


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