#!/usr/bin/env python3
# summary: Manage authenticated remote access to the sign-in screen.
"""starchaser login remote status | enable | disable

Login-screen remote desktop enrollment and signed requests over an existing fleet connection.
Use Settings > Fleet to grant or end login-screen remote desktop permission.
"""
import importlib.machinery,importlib.util,json,os,secrets,subprocess,sys,time
from pathlib import Path

def module(name,path):
    loader=importlib.machinery.SourceFileLoader(name,str(path));spec=importlib.util.spec_from_loader(name,loader);m=importlib.util.module_from_spec(spec);loader.exec_module(m);return m

def protocol():
    path=Path(__file__).resolve().parent.parent/'system/usr/local/lib/starchaser/login_remote.py'
    if not path.is_file():path=Path('/usr/local/lib/starchaser/login_remote.py')
    return module('login_screen_protocol',path)

def recovery():return module('login_screen_fleet',Path(__file__).resolve().with_name('starchaser-fleet-safety'))

def document(target,action,enrollment='',pin='',session=''):
    client=recovery();F=client.fleet();F.load_link().ensure_identity()
    body={'v':1,'source':F.device_id(),'target':target,'enrollment':enrollment,'action':action,'nonce':secrets.token_hex(16),'issued':time.time(),'pin':pin,'session':session}
    return protocol().sign(F.DEVICES/'id_ed25519',body)

def enroll(enable):
    client=recovery();F=client.fleet();doc=F.load()
    sources=[{'id':e['link']['device'],'key':e['link']['key'],'name':F.display_name(e),'role':'mine','generation':e['gen']}
             for e in doc['machines'] if e.get('link') and e['id'].startswith('dev-') and e.get('addedVia')!='help']
    if enable and not sources:raise ValueError("Pair at least one of your own computers first. Helpers can't use the sign-in screen.")
    payload={'target':F.device_id(),'sources':sources}
    result=subprocess.run(['pkexec','/usr/local/lib/starchaser/starchaser-fleet-safety-root','stream-enroll' if enable else 'stream-disable'],input=json.dumps(payload),capture_output=True,text=True,timeout=120)
    try:value=json.loads(result.stdout)
    except ValueError:value={'ok':False,'error':"Login-screen permission wasn't changed. Administrator approval is required."}
    return value

def relay(expected_source=''):
    import select
    if not select.select([sys.stdin],[],[],10)[0]:raise ValueError("The request didn't arrive.")
    data=sys.stdin.buffer.readline(65537)
    if len(data)>65536:raise ValueError('That request is too large.')
    value=json.loads(data)
    if expected_source and value.get('body',{}).get('source')!=expected_source:raise ValueError("The signing computer doesn't match this connection.")
    return protocol().local_request(value)

def stream(expected_source):
    import select,socket
    deadline=time.monotonic()+10;data=bytearray()
    while not data.endswith(b'\n'):
        remaining=deadline-time.monotonic()
        if remaining<=0 or not select.select([0],[],[],remaining)[0]:raise ValueError("The signed connection didn't arrive.")
        byte=os.read(0,1)
        if not byte:raise ValueError('The signed connection ended.')
        data.extend(byte)
        if len(data)>65536:raise ValueError('That request is too large.')
    value=json.loads(data)
    if value.get('body',{}).get('source')!=expected_source or value['body'].get('action')!='connect':raise ValueError('Use a signed connection from this computer.')
    _,descriptor=protocol().local_request(value,want_fd=True)
    with socket.socket(fileno=descriptor) as connection:
        connection.setblocking(True)
        while True:
            ready,_,_=select.select([0,connection],[],[],30)
            if not ready:continue
            if 0 in ready:
                block=os.read(0,65536)
                if not block:break
                connection.sendall(block)
            if connection in ready:
                block=connection.recv(65536)
                if not block:break
                while block:
                    count=os.write(1,block);block=block[count:]


def main(args):
    if args in ([],['--help'],['-h'],['help']):
        print(__doc__);return
    if args[:1]==['stream'] and len(args)==2:stream(args[1]);return
    if args[:1]==['stop-peer'] and len(args)==3:
        L=recovery().fleet().load_link();peer=L.peer(args[1]);probe=L.login_screen_request(peer,'probe')
        if probe.get('nonce')==args[2]:L.login_screen_request(peer,'stop',probe.get('enrollment',''),session=args[2])
        return
    if args==['status']:result=recovery().post('stream-status')
    elif args==['enable']:result=enroll(True)
    elif args==['disable']:result=enroll(False)
    elif args[:1]==['relay'] and len(args)<=2:result=relay(args[1] if len(args)==2 else '')
    elif args[:1]==['sign'] and len(args) in (3,4,5,6):result=document(args[1],args[2],args[3] if len(args)>3 else '',args[4] if len(args)>4 else '',args[5] if len(args)>5 else '')
    else:raise ValueError('Use Settings > Fleet to allow or turn off login-screen remote desktop.')
    print(json.dumps(result),flush=True)
    if result.get('ok') is False:raise SystemExit(1)
if __name__=='__main__':
    try:main(sys.argv[1:])
    except (ValueError,OSError,subprocess.SubprocessError):
        print(json.dumps({'ok':False,'error':'Login-screen remote desktop is unavailable. Check its permission in Settings > Fleet.'}));raise SystemExit(1)
