#!/usr/bin/env python3
# summary: Send selected files to another computer in your fleet.
"""starchaser fleet send [FILE ...] | --plugin | --window | --install-plugin FOLDER

Send selected files through the authenticated fleet link, in a visible window with Cancel.
"""
import contextlib
import importlib.machinery
import importlib.util
import json
import os
from pathlib import Path
import re
import shutil
import signal
import secrets
import subprocess
import sys
import threading

PLUGIN_ID = 'org.starchaser.fleet-files'


def load_link():
    loader = importlib.machinery.SourceFileLoader('fleet_files_link', str(Path(__file__).resolve().with_name('starchaser-link')))
    spec = importlib.util.spec_from_loader(loader.name, loader)
    module = importlib.util.module_from_spec(spec)
    loader.exec_module(module)
    return module


def targets():
    link = load_link()
    return [{'id': p['id'], 'label': 'Send to ' + link.safe_name(p.get('name') or 'Computer'), 'state': 'ready'}
            for p in link.load_peers() if p.get('role') not in ('helper', 'help-target') and not link.fleet().is_removed(p['id'])][:256]


def validate_request(request):
    target = request.get('target')
    if not isinstance(target, str) or not re.fullmatch(r'[0-9a-f]{16}', target) or target not in {p['id'] for p in targets()}:
        raise ValueError("That computer is no longer paired with this one. Open Settings > Fleet to check it.")
    paths = request.get('paths')
    if not isinstance(paths, list) or not 1 <= len(paths) <= 512:
        raise ValueError('Select between 1 and 512 files or folders.')
    if any(not isinstance(p, str) or '\0' in p or not Path(p).is_absolute() or not Path(p).exists() for p in paths):
        raise ValueError("A selected file is no longer available. Select it again in Files.")
    return target, paths


def cancel_transfer(child):
    if child is not None and child.poll() is None:
        with contextlib.suppress(ProcessLookupError):
            os.killpg(child.pid, signal.SIGTERM)


def handle(request):
    if request.get('op') == 'targets':
        return {'op': 'targets', 'targets': targets()}
    if request.get('op') == 'settings':
        return {'op': 'done'}
    if request.get('op') != 'send':
        raise ValueError('This Files extension only sends to paired computers.')
    target, paths = validate_request(request)
    # Files limits plugin address space. The desktop service manager starts the GUI with normal desktop limits.
    child = subprocess.Popen(['systemd-run', '--user', '--collect', '--quiet', '--pipe',
                              '--unit=starchaser-fleet-send-' + secrets.token_hex(6),
                              str(Path(__file__).resolve()), '--window'], stdin=subprocess.PIPE,
                             stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, text=True, start_new_session=True)
    child.stdin.write(json.dumps({'target': target, 'paths': paths}))
    child.stdin.close()
    return {'op': 'done', 'message': 'Transfer opened. Use its Cancel button to stop it.'}


def plugin():
    hello = sys.stdin.readline(65537)
    if len(hello) > 65536 or json.loads(hello).get('op') != 'hello':
        raise ValueError("Files didn't send a valid greeting.")
    print(json.dumps({'op': 'ready', 'protocolVersion': 1}), flush=True)
    while line := sys.stdin.readline(65537):
        try:
            if len(line) > 65536:
                raise ValueError('The selection is too long. Send fewer files at once.')
            result = handle(json.loads(line))
        except (ValueError, OSError, KeyError, TypeError):
            result = {'op': 'error', 'message': "Files couldn't start this transfer. Check the selection and Settings > Fleet."}
        print(json.dumps(result), flush=True)


def window(request):
    import gi
    gi.require_version('Gtk', '3.0')
    from gi.repository import Gtk, GLib, Atk
    win = Gtk.Window(title='Send files to your fleet')
    win.set_default_size(540, 240)
    box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=16, margin=24)
    win.add(box)
    title = Gtk.Label(label='Send files', xalign=0)
    title.set_line_wrap(True)
    status = Gtk.Label(label='', xalign=0)
    status.set_line_wrap(True)
    status.set_selectable(True)
    status.get_accessible().set_role(Atk.Role.STATUSBAR)
    box.pack_start(title, False, False, 0)
    box.pack_start(status, True, True, 0)
    cancel = Gtk.Button(label='Cancel')
    box.pack_end(cancel, False, False, 0)
    child = [None]
    stopped = [False]
    def end(*_):
        stopped[0] = True
        cancel_transfer(child[0])
        Gtk.main_quit()
    cancel.connect('clicked', end)
    win.connect('delete-event', end)
    def key(_win, event):
        if event.keyval == 65307:
            end()
            return True
        return False
    win.connect('key-press-event', key)
    def update(words, finished=False):
        if not stopped[0]:
            status.set_text(words)
            if finished:
                cancel.set_label('Close')
        return False
    def send():
        try:
            target, paths = validate_request(request)
            destination = next(p['label'] for p in targets() if p['id'] == target)
            GLib.idle_add(title.set_text, destination)
            command = [str(Path(__file__).resolve().with_name('starchaser-link')), 'send', target, *paths]
            child[0] = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, start_new_session=True)
            if stopped[0]:
                cancel_transfer(child[0])
                return
            results = []
            for line in child[0].stdout:
                try:
                    value = json.loads(line)
                except ValueError:
                    continue
                words = str(value.get('file') or 'File') + (': sent' if value.get('ok') else ': ' + str(value.get('error') or "couldn't send"))
                results.append(words)
                GLib.idle_add(update, '\n'.join(results[-8:]))
            child[0].wait()
            if not results or child[0].returncode:
                results.append("The transfer didn't finish. Check that the other computer is on and open Settings > Fleet.")
            GLib.idle_add(update, '\n'.join(results[-8:]), True)
        except (OSError, ValueError, KeyError) as error:
            GLib.idle_add(update, str(error), True)
    def begin(target):
        request['target'] = target
        status.set_text('Sending… Cancel stops this transfer. Incomplete files are discarded on the other computer.')
        threading.Thread(target=send, daemon=True).start()
    if request.get('target'):
        begin(request['target'])
    else:
        choices = Gtk.ComboBoxText()
        try:
            peers = targets()
        except (OSError, ValueError):
            peers = []
        for peer in peers:
            choices.append(peer['id'], peer['label'])
        choices.set_active(0)
        choices.get_accessible().set_name('Destination computer')
        box.pack_start(choices, False, False, 0)
        button = Gtk.Button(label='Send')
        button.set_sensitive(bool(peers))
        box.pack_start(button, False, False, 0)
        status.set_text('Choose a paired computer.' if peers else 'No paired computers. Open Settings > Fleet to add one.')
        def choose(_):
            button.hide()
            choices.hide()
            begin(choices.get_active_id())
        button.connect('clicked', choose)
    win.show_all()
    cancel.grab_focus()
    Gtk.main()


def install_plugin(source):
    source = Path(source)
    if json.loads((source/'manifest.json').read_text()).get('id') != PLUGIN_ID:
        raise ValueError('The bundled Files extension is invalid.')
    destination = Path(os.environ.get('XDG_CONFIG_HOME') or Path.home()/'.config')/'flea/plugins'/PLUGIN_ID
    sendto = Path(os.environ.get('XDG_DATA_HOME') or Path.home()/'.local/share')/'Thunar/sendto/starchaser-fleet.desktop'
    sendto.parent.mkdir(parents=True, exist_ok=True)
    if not sendto.is_symlink():
        shutil.copy2(source.parent.parent/'config/Thunar/sendto/starchaser-fleet.desktop', sendto)
    if not shutil.which('flea'):
        return
    if destination.exists():
        # Only refresh our bundled plugin, preserving the enabled/disabled choice in Files' settings.
        if (destination/'.starchaser-bundled').is_file() and not destination.is_symlink():
            for name in ('manifest.json', 'run'):
                target = destination/name
                if target.is_symlink():
                    raise ValueError('The Files extension was changed. Remove it in Files before installing it again.')
                shutil.copy2(source/name, target)
        return
    result = subprocess.run(['flea', 'plugin', 'add', str(source)], capture_output=True, text=True, timeout=15)
    if result.returncode == 0:
        subprocess.run(['flea', 'plugin', 'enable', PLUGIN_ID], capture_output=True, text=True, timeout=15)
        (destination/'.starchaser-bundled').touch(mode=0o600)


def main(args):
    if args == ['--plugin']:
        plugin()
    elif args == ['--window']:
        raw = sys.stdin.read(65537)
        if len(raw) > 65536:
            raise ValueError('The selection is too long. Send fewer files at once.')
        window(json.loads(raw))
    elif len(args) == 2 and args[0] == '--install-plugin':
        install_plugin(args[1])
    elif args[:1] in (['--help'], ['-h']):
        print(__doc__)
    elif args and all(not a.startswith('-') for a in args):
        window({'paths': [str(Path(a).absolute()) for a in args]})
    else:
        raise ValueError('Select files in Files, then choose Send to Fleet.')


if __name__ == '__main__':
    try:
        main(sys.argv[1:])
    except (ValueError, OSError, subprocess.SubprocessError) as error:
        print(str(error), file=sys.stderr)
        raise SystemExit(1)
