#!/usr/bin/env python3
# summary: View another fleet computer's sign-in screen.
"""starchaser login view COMPUTER [--view-only]

A pinned, authenticated login-screen viewer over the existing fleet SSH channel.
Choose Remote desktop in Settings > Fleet to connect. Ctrl+Shift+Esc ends the connection.
"""
import importlib.machinery,importlib.util,json,os,socket,subprocess,sys
from pathlib import Path

def load_client():
    path=Path(__file__).resolve().with_name('starchaser-login-remote');loader=importlib.machinery.SourceFileLoader('login_view_protocol',str(path));spec=importlib.util.spec_from_loader(loader.name,loader);m=importlib.util.module_from_spec(spec);loader.exec_module(m);return m

def credential_types(values):
    for index in range(values.n_values):
        value=values.get_nth(index)
        yield value.get_value() if hasattr(value,'get_value') else value


def prepare_connection(display,label,name):
    display.set_sensitive(False)
    def ready(widget):
        label.set_text('Connected to '+name+'. Sign in there; reconnect for your desktop. Ctrl + Shift + Esc ends this connection.')
        widget.set_sensitive(True);widget.grab_focus()
    display.connect('vnc-initialized',ready)


def main(args):
    if args in ([],['--help'],['-h'],['help']):
        print(__doc__);return
    if args==['--check']:
        import gi
        gi.require_version('Gtk','3.0');gi.require_version('GtkVnc','2.0');from gi.repository import GtkVnc
        if not hasattr(GtkVnc.DisplayCredential,'CA_CERT_DATA'):raise ValueError('Update the login-screen viewer.')
        return
    if len(args) not in (1,2) or len(args)==2 and args[1]!='--view-only':raise ValueError('Choose Remote desktop in Settings > Fleet.')
    import gi
    gi.require_version('Gtk','3.0');gi.require_version('GtkVnc','2.0')
    from gi.repository import Gtk,GtkVnc,GVnc,GObject,Gdk
    client=load_client();L=client.recovery().fleet().load_link();peer=L.peer(args[0])
    if peer.get('role') in ('helper','help-target'):raise ValueError("A helper can't use the sign-in screen.")
    probe=L.login_screen_request(peer,'probe');transport=probe.get('transport') or {}
    if not probe.get('ok') or probe.get('state')!='ready' or transport.get('kind')!='vnc':raise ValueError("The login-screen connection isn't ready. Connect again from Fleet.")
    certificate=transport.get('certificate','')
    if not certificate.startswith('-----BEGIN CERTIFICATE-----') or 'PRIVATE KEY' in certificate or len(certificate)>32768:raise ValueError('The screen certificate was refused.')
    own,other=socket.socketpair();error_log=__import__('tempfile').TemporaryFile()
    connection=subprocess.Popen(L.ssh_command(peer,peer['address'],'login-vnc'),stdin=other,stdout=other,stderr=error_log,preexec_fn=client.protocol().die_with_parent);other.close()
    signed=client.document(peer['id'],'connect',probe['enrollment'],session=probe['nonce']);own.sendall(json.dumps(signed).encode()+b'\n')
    window=Gtk.Window(title=peer['name']+' — Login screen');window.set_default_size(1100,760)
    column=Gtk.Box(orientation=Gtk.Orientation.VERTICAL,spacing=8);column.set_border_width(10);window.add(column)
    header=Gtk.Box(spacing=12);column.pack_start(header,False,False,0)
    label=Gtk.Label(label='Connecting securely to '+peer['name']+'… Wait until connected before typing. Ctrl + Shift + Esc ends this connection.');label.set_line_wrap(True);header.pack_start(label,True,True,0)
    end=Gtk.Button.new_with_label('End connection');header.pack_start(end,False,False,0)
    display=GtkVnc.Display.new();display.set_scaling(True);display.set_keep_aspect_ratio(True);display.set_pointer_grab(False);display.set_keyboard_grab(False);display.set_read_only(len(args)==2)
    display.get_accessible().set_name('Remote login screen. Type the remote password and press Enter. Ctrl+Shift+Esc ends the connection.')
    display.set_credential_types([GtkVnc.DisplayCredential.USERNAME,GtkVnc.DisplayCredential.PASSWORD,GtkVnc.DisplayCredential.CLIENTNAME,GtkVnc.DisplayCredential.CA_CERT_DATA])
    wire=display.get_connection()
    # Replace the widget's automatic protocol choice: only pinned X509 Plain over TLS is permitted.
    for signal in ('vnc-auth-choose-type','vnc-auth-choose-subtype'):
        ident=GObject.signal_lookup(signal,GVnc.Connection.__gtype__)
        GObject.signal_handlers_block_matched(wire,GObject.SignalMatchType.ID,ident,0,None,None,None)
    wire.connect('vnc-auth-choose-type',lambda connection,types:connection.set_auth_type(GVnc.ConnectionAuth.VENCRYPT))
    wire.connect('vnc-auth-choose-subtype',lambda connection,major,types:connection.set_auth_subtype(GVnc.ConnectionAuthVencrypt.X509PLAIN) if major==GVnc.ConnectionAuth.VENCRYPT else display.close())
    def credentials(widget,types):
        values={GtkVnc.DisplayCredential.USERNAME:transport['username'],GtkVnc.DisplayCredential.PASSWORD:transport['password'],GtkVnc.DisplayCredential.CLIENTNAME:'Starchaser',GtkVnc.DisplayCredential.CA_CERT_DATA:certificate}
        for kind in credential_types(types):
            if kind not in values:display.close();return
            widget.set_credential(kind,values[kind])
    display.connect('vnc-auth-credential',credentials)
    display.connect('vnc-auth-failure',lambda widget,*details:label.set_text('The screen did not authenticate. End this connection and connect again.'))
    display.connect('vnc-error',lambda widget,*details:label.set_text('The screen connection ended. End this connection and connect again.'))
    display.connect('vnc-disconnected',lambda widget:label.set_text('Connection ended. If someone signed in, reconnect from Fleet for their desktop.'))
    column.pack_start(display,True,True,0)
    prepare_connection(display,label,peer['name'])
    closing=False
    def finish(*unused):
        nonlocal closing
        if closing:return
        closing=True;display.close()
        subprocess.Popen([str(Path(__file__).resolve().with_name('starchaser-login-remote')),'stop-peer',peer['id'],probe['nonce']],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,start_new_session=True)
        connection.terminate();window.destroy();Gtk.main_quit()
    end.connect('clicked',finish);window.connect('delete-event',lambda *unused:finish() or True)
    def key(widget,event):
        if event.keyval==Gdk.KEY_Escape and event.state&Gdk.ModifierType.CONTROL_MASK and event.state&Gdk.ModifierType.SHIFT_MASK:finish();return True
        return False
    window.connect('key-press-event',key);window.show_all();display.open_fd_with_hostname(own.detach(),'localhost');Gtk.main()
    try:connection.wait(timeout=3)
    except subprocess.TimeoutExpired:connection.kill();connection.wait(timeout=3)
    error_log.close()

if __name__=='__main__':
    try:main(sys.argv[1:])
    except (ValueError,OSError,ImportError) as error:
        print('The login-screen viewer could not start. Open Settings > Fleet and try connecting again.',file=sys.stderr);raise SystemExit(1)
