import hashlib
import json
from pathlib import Path
import subprocess
import urllib.error
import urllib.request

root = Path('/var/www/html/ro-th-online').resolve(strict=True)
task = 'voice-capture-mute-20261001'
deploy = root / 'deploy' / task
record = json.loads((deploy / 'release.json').read_text())
owner = json.loads((deploy / 'owner-release.json').read_text())
before = json.loads((root / 'staging' / (task + '-services-before.json')).read_text())
sha = lambda path: hashlib.sha256(path.read_bytes()).hexdigest()
def pids(name):
    result = subprocess.run(['pgrep', '-x', name], capture_output=True, text=True)
    assert result.returncode in (0, 1)
    return sorted(result.stdout.split())
assert sha(root / 'mobile/index.html') == record['indexHash']
assert sha(root / 'public/index.html') == owner['indexHash']
assert sha(root / 'gateway/WebGateway') == before['gatewayHash']
assert pids('map-server') == before['mapPids']
assert pids('voice-server') == before['voicePids']
assert record['release'] in (root / 'public/index.html').read_text()
pages = []
for path, status in [('/Mobile/', 200), ('/Mobile/?installed=1', 200), ('/browser/', 401), ('/', 404)]:
    request = urllib.request.Request('https://ro-th.online' + path, headers={'Cache-Control': 'no-cache'})
    try:
        response = urllib.request.urlopen(request, timeout=45)
    except urllib.error.HTTPError as error:
        response = error
    with response:
        content = response.read()
        assert response.status == status
        if status == 200:
            assert hashlib.sha256(content).hexdigest() == record['indexHash']
        pages.append(dict(path=path, status=status))
for name, expected in record['files'].items():
    if name != 'WebPreview.data':
        assert sha(root / 'public/Build' / record['release'] / name) == expected['sha256']
assert subprocess.check_output(['systemctl', 'is-active', 'apache2', 'ro-th-online-gateway'], text=True).splitlines() == ['active', 'active']
result = dict(release=record['release'], pages=pages, mapPidsUnchanged=True,
              voicePidsUnchanged=True, gatewayBinaryUnchanged=True,
              ownerAuthenticationUnchanged=owner['authenticationUnchanged'],
              retained=sorted(path.name for path in (root / 'public/Build').glob('mobile-*') if path.is_dir()))
(deploy / 'health.json').write_text(json.dumps(result, indent=2))
print(json.dumps(result, indent=2))
