#!/usr/bin/env python3
"""SAN MLAT TLS relay for an existing mlat-client. Python standard library only.
Configure interactively: python3 san-mlat.py --configure /path/config.json
Run: python3 san-mlat.py --config /path/config.json
Then start mlat-client with --server 127.0.0.1:31094 --no-udp.
Raw Beast input must be from YOUR local receiver, normally 127.0.0.1:30005.
"""
import argparse, asyncio, contextlib, getpass, json, os, ssl
from pathlib import Path
async def relay(r,w,config):
    remote=None;tasks=[]
    try:
        rr,remote=await asyncio.open_connection('www.sannetwork.net',31090,ssl=ssl.create_default_context(),server_hostname='www.sannetwork.net')
        remote.write(json.dumps({'key':config['key'],'station_id':config['station_id']}).encode()+b'\n');await remote.drain()
        async def pipe(a,b):
            while data:=await a.read(65536):b.write(data);await b.drain()
        tasks=[asyncio.create_task(pipe(r,remote)),asyncio.create_task(pipe(rr,w))]
        await asyncio.wait(tasks,return_when=asyncio.FIRST_COMPLETED)
    except (OSError,ssl.SSLError):print('SAN MLAT connection unavailable; mlat-client will retry.',flush=True)
    finally:
        for t in tasks:t.cancel()
        if tasks:await asyncio.gather(*tasks,return_exceptions=True)
        for s in (remote,w):
            if s:
                s.close()
                with contextlib.suppress(Exception):await s.wait_closed()
async def main(config):
    server=await asyncio.start_server(lambda r,w:relay(r,w,config),'127.0.0.1',31094)
    async with server:await server.serve_forever()
if __name__=='__main__':
    p=argparse.ArgumentParser(description=__doc__);g=p.add_mutually_exclusive_group(required=True);g.add_argument('--configure');g.add_argument('--config');a=p.parse_args()
    if a.configure:
        target=Path(a.configure).expanduser();target.parent.mkdir(parents=True,exist_ok=True)
        config={'station_id':input('SAN station UUID: ').strip(),'key':getpass.getpass('SAN ADS-B sending key (hidden): ')}
        fd=os.open(target,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
        with os.fdopen(fd,'w')as f:json.dump(config,f)
        print('Private configuration saved. Start relay with --config, then start mlat-client.')
    else:
        path=Path(a.config).expanduser()
        if path.stat().st_mode&0o077:raise SystemExit('Config must be private: chmod 600 '+str(path))
        asyncio.run(main(json.loads(path.read_text())))
