"""Read-only baseline for publishing the RTC client without replacing live config."""
import base64,hashlib,json,pathlib,re,shutil,subprocess
root=pathlib.Path('/var/www/html/ro-th-online')
paths={'mobile':root/'mobile/index.html','owner':root/'public/index.html','config':pathlib.Path('/etc/apache2/sites-enabled/zz-ro-th-download-ssl.conf').resolve()}
records={key:dict(sha256=hashlib.sha256(path.read_bytes()).hexdigest(),base64=base64.b64encode(path.read_bytes()).decode()) for key,path in paths.items()}
ids=set(re.findall(r'mobile-([a-f0-9]{8})',paths['mobile'].read_text()))
assert len(ids)==1
current='mobile-'+ids.pop()
matches=[]
for path in (root/'deploy').glob('*/release.json'):
    data=json.loads(path.read_text(encoding='utf-8-sig'))
    if data.get('release')==current and data.get('verification',{}).get('httpsIndexBothUrls'):
        matches.append(data)
assert matches
manifest=max(matches,key=lambda value:value.get('publishedAtUtc',''))
assert records['mobile']['sha256']==manifest['indexHash']
assert current in paths['owner'].read_text()
chunk=root/'public/Build'/current/'chunk-loader.js'
records['chunk']=dict(sha256=hashlib.sha256(chunk.read_bytes()).hexdigest(),base64=base64.b64encode(chunk.read_bytes()).decode())
assert records['chunk']['sha256']==manifest['chunkHash']
apk=json.loads(pathlib.Path('/var/www/html/test-apk/apks/latest.json').read_text())
pids={name:subprocess.check_output(['pgrep','-x',name],text=True).strip().splitlines() for name in ['map-server','voice-server','login-server','char-server']}
print(json.dumps(dict(current=current,manifest=manifest,live=records,apk=apk,freeBytes=shutil.disk_usage(root).free,retained=sorted(p.name for p in (root/'public/Build').glob('mobile-*') if p.is_dir()),gameServicePids=pids),indent=2))
