#!/usr/bin/env python3
"""Derive the public web edition of RZL-ENGINE-0.2.6-RSHELL.rzl.

Usage: derive_web_pack.py <signed-original.rzl> <out-web.rzl>

The signed original (sha256 9ea0f9cf...) is never modified. The web edition is a separate,
UNSIGNED derivative that differs only by the text edits below (every edit is asserted):
  1. GHOSTKEY panel: no longer says signing is armed/ACTIVE; this page signs nothing.
  2. Public file hygiene: local service addresses and ports in help text become "local service";
     the Apple team id in help text is dropped.
  3. Browser boot: RFEEDS and RAUTO stay off, no feed adapter (offline, online hooks off).
  4. RIZAL Mono is the default font (same-origin /rfont.css).
Everything else (engine, weights section, corpus, ring, tests) is byte-identical.
"""
import sys, re, json, struct, hashlib

sh = lambda x: hashlib.sha256(x).hexdigest()
src, out = sys.argv[1], sys.argv[2]
b = open(src, 'rb').read()
assert b[:8] == b'RZLPACK1'
ml = struct.unpack('>I', b[8:12])[0]
man = json.loads(b[12:12 + ml]); base = 12 + ml
secs = {}
for s in man['sections']:
    secs[s['name']] = b[base + s['offset']: base + s['offset'] + s['clen']]
orig_sha = sh(b)

def sub(name, old, new, count=1):
    t = secs[name].decode('utf8')
    assert t.count(old) == count, (name, old, t.count(old))
    secs[name] = t.replace(old, new).encode('utf8')

def rsub(name, pat, new, minimum=1):
    t = secs[name].decode('utf8')
    t2, n = re.subn(pat, new, t)
    assert n >= minimum, (name, pat, n)
    secs[name] = t2.encode('utf8')

P = 'rghostkey-panel/rghostkey-panel.js'
W = 'window/R-SHELLwindow.html'
R = 'ros/ros-base.js'

# 1. GHOSTKEY panel wording and behaviour: verify the PUBLIC ring only, never arm signing
sub(P, " * On a verified ring the panel shows: GHOSTKEY · VERIFIED · ACTIVE · signing.\n * Signing is armed automatically on open. There is no Unlock command, no button, no biometric or password",
       " * On a verified ring the web edition shows: GHOSTKEY · public ring VERIFIED · read-only (this page signs nothing).\n * Web edition: signing is never armed. There is no Unlock command, no button, no biometric or password")
sub(P, "return 'GHOSTKEY · VERIFIED · ACTIVE · signing';", "return 'GHOSTKEY · public ring VERIFIED · read-only (this page signs nothing)';")
sub(P, "self.state.signing = ok; /* armed automatically when the public ring verifies; no user gate */", "self.state.signing = false; /* web edition: never armed; this page cannot sign */")
sub(P, "(auto on open; signing armed when the ring verifies)", "(auto on open; read-only: this page signs nothing)")
sub(R, "public verify on open, signing armed when the ring verifies", "public verify on open, read-only, never signs")
sub(W, 'title="public GHOSTKEY ring: auto-verified on open; signing armed when the ring verifies"', 'title="public GHOSTKEY ring: auto-verified on open; read-only, this page signs nothing"')
sub(W, "no login, password or biometric step; signing is armed when the public ring verifies. No new credentials are stored.", "no login, password or biometric step; this page only verifies the public ring and signs nothing. No new credentials are stored.")
sub(W, "The public GHOSTKEY ring is verified on open. Signing is armed when that check passes.", "The public GHOSTKEY ring is verified on open. This page is read-only and signs nothing.")

# 2. public hygiene: addresses, ports, team id -> "local service"
rsub(W, r'\b127\.\d+\.\d+\.\d+:\d{2,5}(?:/send)?', 'local service')
rsub(W, r'loopback :\d{4,5}\b', 'local service')
rsub(W, r':\d{4,5}\b', 'local service')
rsub(W, r"signing as team [A-Z0-9]{10}", "signing with the Apple developer team of the owner")

# 3. browser boot: offline, online hooks off
sub(W, "{ onProgress: function (e) { status(e.pct + '% ' + e.stage + ': ' + e.text); }, ringBytes: ring,",
       "{ noFeeds: true, noAuto: true, feedsAdapter: {}, onProgress: function (e) { status(e.pct + '% ' + e.stage + ': ' + e.text); }, ringBytes: ring,")

# 4. RIZAL Mono default font
rsub(W, r'"RZL Prompt", ui-monospace', '"RZL Prompt", "RIZAL Mono", ui-monospace', minimum=4)
sub(W, '<link rel="icon" href="data:," />', '<link rel="icon" href="data:," />\n    <link rel="stylesheet" href="/rfont.css" />')

# hard checks: nothing sensitive left in any section
for n, d in secs.items():
    t = d.decode('utf8', 'ignore')
    assert not re.search(r'\b127\.\d+\.\d+\.\d+\b', t), n
    assert not re.search(r'(?<![\w.\-])localhost\b', t), n
    assert not re.search(r'team [A-Z0-9]{10}\b', t), n
    if n == W:
        assert not re.search(r':\d{4,5}\b', t), n

# rebuild manifest
off = 0
for s in man['sections']:
    d = secs[s['name']]
    s['offset'] = off; s['clen'] = len(d); s['size'] = len(d)
    s['sha256'] = sh(d); s['csha256'] = sh(d)
    off += len(d)
lines = sorted(s['name'] + ':' + s['sha256'] + ':' + str(s['size']) for s in man['sections'])
man['root'] = sh(('\n'.join(lines) + '\n').encode())
man['bytes'] = off
man['build'] = dict(man['build'], signed=False, staged=True, target='web',
                    derived_from_sha256=orig_sha, derived_note='web edition: text edits only, see DERIVE-WEB-PACK.py; UNSIGNED')
mj = json.dumps(man, separators=(',', ':')).encode('utf8')
blob = b'RZLPACK1' + struct.pack('>I', len(mj)) + mj + b''.join(secs[s['name']] for s in man['sections'])
open(out, 'wb').write(blob)
print(json.dumps({'out': out, 'bytes': len(blob), 'sha256': sh(blob), 'root': man['root'], 'orig_sha256': orig_sha}, indent=1))
