#!/usr/bin/env python3
# summary: Read and write files through the authenticated fleet connection.
"""starchaser fleet files list [FOLDER] | read FILE | write FILE SIZE

Home-folder file operations through Mission Control's authenticated, consent-gated SSH bridge.
read and write stream binary data; a write publishes only a complete new file, never an overwrite.
"""
import contextlib
import json
import os
import secrets
import signal
import stat
import sys
from pathlib import Path

HOME = Path.home()
MAX_BYTES = 4 * 1024**3


def parts(path, empty=False):
    if not isinstance(path,str) or '\0' in path or path.startswith('/') or any(p == '..' for p in path.split('/')):
        raise ValueError('Choose a file inside the Home folder.')
    result=[p for p in path.split('/') if p not in ('','.')] 
    if not empty and not result:
        raise ValueError('Choose a file name.')
    return result


@contextlib.contextmanager
def folder(path):
    fd=os.open(HOME,os.O_RDONLY|os.O_DIRECTORY)
    try:
        for part in parts(path,empty=True):
            next_fd=os.open(part,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=fd)
            os.close(fd);fd=next_fd
        yield fd
    finally:os.close(fd)


def list_files(path=''):
    with folder(path) as fd:
        rows=[]
        for name in sorted(os.listdir(fd),key=str.casefold)[:10000]:
            info=os.stat(name,dir_fd=fd,follow_symlinks=False)
            rows.append({'name':name,'path':'/'.join([*parts(path,True),name]),'folder':stat.S_ISDIR(info.st_mode),
                         'link':stat.S_ISLNK(info.st_mode),'bytes':info.st_size,'modified':info.st_mtime})
    return {'ok':True,'home':str(HOME),'folder':path,'files':rows}


def read_file(path,out):
    names=parts(path)
    with folder('/'.join(names[:-1])) as fd:
        source=os.open(names[-1],os.O_RDONLY|os.O_NOFOLLOW|os.O_NONBLOCK,dir_fd=fd)
        with os.fdopen(source,'rb') as stream:
            info=os.fstat(stream.fileno())
            if not stat.S_ISREG(info.st_mode) or info.st_size>MAX_BYTES:
                raise ValueError('Choose a regular file of at most 4 GB.')
            while chunk:=stream.read(256*1024):out.write(chunk)


def write_file(path,source,size):
    names=parts(path)
    if type(size) is not int or not 0<=size<=MAX_BYTES:
        raise ValueError('Choose a file of at most 4 GB.')
    with folder('/'.join(names[:-1])) as fd:
        temporary='.upload-'+secrets.token_hex(12)
        try:
            output=os.open(temporary,os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o600,dir_fd=fd)
            with os.fdopen(output,'wb') as stream:
                remaining=size
                while remaining:
                    chunk=source.read(min(remaining,256*1024))
                    if not chunk:raise ValueError('The upload stopped before it finished. Nothing was kept.')
                    stream.write(chunk);remaining-=len(chunk)
                if source.read(1):raise ValueError('The upload is larger than expected. Nothing was kept.')
                stream.flush();os.fsync(stream.fileno())
            os.link(temporary,names[-1],src_dir_fd=fd,dst_dir_fd=fd,follow_symlinks=False)
        finally:
            with contextlib.suppress(FileNotFoundError):os.unlink(temporary,dir_fd=fd)
    return {'ok':True,'saved':path,'bytes':size}


def main(argv):
    if argv in ([],['--help'],['-h'],['help']):print(__doc__);return
    if argv[:1]==['list'] and len(argv) in (1,2):result=list_files(argv[1] if len(argv)==2 else '')
    elif argv[:1]==['read'] and len(argv)==2:read_file(argv[1],sys.stdout.buffer);return
    elif argv[:1]==['write'] and len(argv)==3 and argv[2].isascii() and argv[2].isdigit():result=write_file(argv[1],sys.stdin.buffer,int(argv[2]))
    else:raise ValueError('Choose list, read or write and a path inside Home.')
    print(json.dumps(result))


if __name__=='__main__':
    # Bridge cancellation terminates the process. Unwind write_file's finally block
    # so Stop removes its private incomplete upload as well as closing the channel.
    def stopped(signum, frame):
        raise SystemExit(1)
    for signum in (signal.SIGTERM, signal.SIGHUP):
        signal.signal(signum, stopped)
    try:main(sys.argv[1:])
    except (ValueError,OSError) as error:print(str(error),file=sys.stderr);sys.exit(1)
