import json
from remote import ROOT, python, run

code = r'''
import hashlib,json,os,subprocess,sys,shutil
from pathlib import Path
definition=json.loads(Path('/etc/contextra-maintenance/server.json').read_text())
assert definition['server']=='icerti-ai2'
sys.path.insert(0,definition['paths']['tools'])
import compose_backend as cb,server_context as s
a,site,cp,approved,live,source=cb.inspect()
rows=cb.containers()
out=dict(server=definition['server'],tools=definition['paths']['tools'],state=str(cb.state_path()),
 transaction=a.get('transaction'),active_hash=hashlib.sha256((cb.state_path()/'active.json').read_bytes()).hexdigest(),
 approved_equals_live=approved==live,source_hash=cb.canonical(source),services={},
 source_files=s.CURRENT['compose_files'],env_files=s.CURRENT['env_files'],
 root_free=shutil.disk_usage('/').free,storage_free=shutil.disk_usage('/storage').free)
for r in rows:
 role=r['Config']['Labels']['com.docker.compose.service']
 env=dict(v.split('=',1) for v in r['Config']['Env'] if '=' in v)
 out['services'][role]=dict(id=r['Id'],image=r['Image'],tag=r['Config']['Image'],running=r['State']['Running'],
  health=r['State'].get('Health',{}).get('Status'),env_keys=sorted(env),
  mounts=[dict(type=m['Type'],source=m.get('Source'),target=m['Destination'],rw=m['RW']) for m in r['Mounts']],
  safe_env={k:v for k,v in env.items() if k in ('CONTEXTRA_ROI_POLICY_FILE','CONTEXTRA_FIGHT_ENGINE_DEFAULT','CONTEXTRA_STREAM_CONFIG','CONTEXTRA_STREAM_CONFIG_PATH')})
out['memory']=dict(line.split(':',1) for line in Path('/proc/meminfo').read_text().splitlines() if line.startswith(('MemAvailable:','MemTotal:')))
print(json.dumps(out))
'''
data=json.loads(python(code,sudo=True))
(ROOT/'preflight.json').write_text(json.dumps(data,indent=2)+'\n')
print(json.dumps(dict(transaction=data['transaction'],approved_equals_live=data['approved_equals_live'],
    services={k:{x:v[x] for x in ('id','image','running','health')} for k,v in data['services'].items()},
    root_free=data['root_free'],storage_free=data['storage_free'],memory=data['memory']),indent=2))
