"""Read-only post-publication verification for the approved browser release."""
import datetime
import hashlib
import json
from pathlib import Path
import subprocess
import urllib.error
import urllib.request

root = Path('/var/www/html/ro-th-online')
task = 'mobile-controls-iron-release-20260929'
record = json.loads((root / 'deploy' / task / 'release.json').read_text())
owner = json.loads((root / 'deploy' / task / 'owner-release.json').read_text())
assert record['release'] == owner['release'] == 'mobile-cf92bb41'
result = dict(release=record['release'], checkedAtUtc=datetime.datetime.now(datetime.timezone.utc).isoformat(), http={}, entries={}, services={})
for page, expected in [('mobile/index.html', record['indexHash']), ('public/index.html', owner['indexHash'])]:
    content = (root / page).read_bytes()
    actual = hashlib.sha256(content).hexdigest()
    assert actual == expected and b'mobile-cf92bb41' in content
    result['entries'][page] = actual
for path, expected in [('/Mobile/', 200), ('/Mobile/?installed=1', 200), ('/browser/', 401), ('/', 404)]:
    try:
        response = urllib.request.urlopen('https://ro-th.online' + path, timeout=45)
    except urllib.error.HTTPError as error:
        response = error
    with response:
        assert response.status == expected
        body = response.read()
        digest = hashlib.sha256(body).hexdigest()
        if expected == 200:
            assert digest == record['indexHash']
        result['http'][path] = dict(status=response.status, sha256=digest)
for service in ['apache2', 'ro-th-online-gateway']:
    status = subprocess.check_output(['systemctl', 'is-active', service], text=True).strip()
    assert status == 'active'
    result['services'][service] = status
retained = sorted(p.name for p in (root / 'public/Build').glob('mobile-*') if p.is_dir())
assert retained == sorted(['mobile-cf92bb41', 'mobile-78423282', 'mobile-f398e377'])
result['retainedReleases'] = retained
result['existingGameProcesses'] = subprocess.check_output(['ps', '-p', '1442316,1302169,2282544', '-o', 'pid=,comm='], text=True).strip().splitlines()
print(json.dumps(result, indent=2))

