"""Read-only VPS baseline for a browser release; emit JSON to the caller."""
import base64, gzip, hashlib, json, pathlib, re, shutil, subprocess, sys
root = pathlib.Path('/var/www/html/ro-th-online')
sha = lambda p: hashlib.sha256(p.read_bytes()).hexdigest()
index = root/'mobile/index.html'
current = re.search(r'mobile-([a-f0-9]{8})', index.read_text())[1]
manifests = []
for p in (root/'deploy').glob('*/release.json'):
    d = json.loads(p.read_text(encoding='utf-8-sig'))
    if d.get('release') == 'mobile-'+current and d.get('verification', {}).get('httpsIndexBothUrls'):
        manifests.append(d)
assert manifests
manifest = max(manifests, key=lambda d:d.get('publishedAtUtc',''))
paths = {'mobile':index, 'chunk':root/'public/Build'/('mobile-'+current)/'chunk-loader.js',
         'config':pathlib.Path('/etc/apache2/sites-enabled/zz-ro-th-download-ssl.conf').resolve(),
         'owner':root/'public/index.html'}
live = {k:dict(sha256=sha(p),base64=base64.b64encode(p.read_bytes()).decode()) for k,p in paths.items()}
apkroot = pathlib.Path('/var/www/html/test-apk')
catalog = apkroot/'patches/Maps/latest.json.gz'
maps = json.loads(gzip.decompress(catalog.read_bytes()))
request = json.loads(pathlib.Path(sys.argv[1]).read_text(encoding='utf-8-sig'))
rows=[]
for entry in request['changed']:
    record=next(m for m in maps['maps'] if m['name']==entry['map'])
    obj=maps['objects'][record['package']]
    p=catalog.parent/'objects'/(obj['sha256']+obj['extension'])
    rows.append(dict(map=entry['map'],catalogHash=obj['sha256'],diskHash=sha(p),files=len(record['files']),expectedNew=entry['afterSha256'],expectedOld=entry['beforeSha256']))
result=dict(current='mobile-'+current,manifest=manifest,live=live,
 apk=json.loads((apkroot/'apks/latest.json').read_text()),mapCatalogHash=sha(catalog),mapRows=rows,
 freeBytes=shutil.disk_usage(root).free,retained=sorted(p.name for p in (root/'public/Build').glob('mobile-*') if p.is_dir()),
 gameServicePids={n:subprocess.check_output(['pgrep','-x',n],text=True).strip().splitlines() for n in ['map-server','voice-server','login-server','char-server']},
 gatewayUnit=subprocess.check_output(['systemctl','cat','ro-th-online-gateway'],text=True))
print(json.dumps(result,indent=2))
