#!/usr/bin/env python3
"""Ragol's Wrath updater for Linux / Steam Deck - the same job as update.ps1, same signed releases, same rules.

  python3 ragolswrath_update.py [--root <client folder>] [--base-url <url>]      (normally run by update-linux.sh)

TRUST: manifest.json is signed with RSA-3072 / SHA-256 / PKCS#1 v1.5 by Bo's USB key. The signature is checked against the
two public keys pinned below (the same two as update.ps1) BEFORE the manifest is read; every file is then pinned by SHA-256
+ size inside it. Anything unsigned, tampered, redirected, cut off or from an older build is REFUSED and nothing changes.
Only the Python 3 standard library is used (the RSA check is pure Python: pow() and a padding compare).
EXIT: 0 ok / up to date, 1 offline (nothing changed), 2 refused (nothing changed).
Never touched: display.json login.json options.lua imgui.ini log bmp update-state.json _update settings-backups.
psobb.exe / ultima.dll change only through the manifest's byte edits (each only on the exact golden copy), never as files.
"""
import argparse, base64, hashlib, http.client, json, os, re, shutil, ssl, sys, time, urllib.parse, zipfile

BASE_URL = 'https://ragolswrath.web.app/update/'
# PINNED-KEYS: keep identical to update.ps1 (test_update_linux.py checks it)
PINNED = [
 ('primary fa9af2edabcdf992', '3ptG0lAmXTGwDU7ChQ+03UKj/BBoUNd2KwN/LF6fIJD8iMFAGk6loMN4oIjZx/FQPeBNwmbATWHvOMaJvUDCE8/9hyEgVs39bidYUst3bagMsQ7EZy0liYhlRBJtQYrGPJ4d7VSfL3zqPdcdaIn1qR/MesHYYSu4p4Iuu75nOzAPDFpG6RrKqtEfOVxaKcCwdHRgK9svp7W29K3c8z6mVN9fokmjikcHrYRUwxn9LPsBo7E0YpMA8FlOvu2pA96UOTzSpHjOZnz5zKlqghsshj9Eq4QlIPeBvB4jZEt3FvIYn0NRxGYRfv47OB86e9qXR0bRRL2MkzQ57XmnsOjU42xOZTQancClm18oh2BhNZsRtAlSnICENbdEOyFC85tJXd5gDOk3mUKdvLWRfthoUxB33yc4o1hCoKuWKisXboADOyhmkHGZfpvsGa8HO5XbA8nSmxkpmCkM6TwS+cj1W+teA8biKvKSe2aEja4EoSbvHs7MMnRkhfp/dqX+pQav', 'AQAB'),
 ('spare 8279fa54b3c927bd', 'y/SadkHdLvEpFoQAYNZhxteTbQD/5FvSZEie9gRL1PO8oPn5campdCTVZeZQnRm70lL70CmGJ0Gcu5P2Cu6k6c6anG4lCWjIDKIgyk2spljOUonUtE3Le5pO6lDjYFNBebWeMvOEpq+6wrbD55BaM0VTeb9h9ylnO/g9HRexEEgdwqpJqQJQe+WxJMVxe2QDdFCRCsbJWgth0gQOblVlwmp5Uw0cgn73c6AVSn91EKREsm5ho9WdBJxvzIxLfLp7P/7PjOBn0Fim8nAR2EEf0CXwwLsn/J/mFsBcRL4ZkndfSCNgBKEZ86hdJx+H6Q6bml/pvU4eA1k2Unz9TV+CY3CF3951O02s0lpQGlVoLjv/tyTni/GDrt77bkgjhUDZyNaigcBa1ZzC6hKp/twhh4qRxeQo4x4YgRWTepytkKKzIVS9wyt+6U88s0Qngv1m6LSdfMp+aOzzGdpkVJo/I7traBT0i336VHmwHEEjRi7gSrPaXRHVqAP5dyOKIUqn', 'AQAB'),
]
OLD_LOADERS = {'aa134cf2a629468a63dc50a00684e01b1893234d5896d954e7a244bf0590b483'}   # same as update.ps1 $OldLoaders
SEGMENT = re.compile(r"^[A-Za-z0-9 _.()'+,&!-]+$")
NEVER = re.compile(r'^(display\.json|login\.json|options\.lua|imgui\.ini|log|bmp|update-state\.json|_update|settings-backups)$', re.I)
DEVICE = re.compile(r'^(con|prn|aux|nul|com\d|lpt\d)(\.|$)', re.I)
HEX64 = re.compile(r'^[0-9a-f]{64}$')
SHA256_PREFIX = bytes.fromhex('3031300d060960864801650304020105000420')   # DigestInfo header for SHA-256


class Refused(Exception): pass
class Offline(Exception): pass


def sha(b): return hashlib.sha256(b).hexdigest()
def whole(v): return isinstance(v, int) and not isinstance(v, bool) and v >= 0
def slurp(p):
    with open(p, 'rb') as f: return f.read()


def verify(data, sig):
    """RSA PKCS#1 v1.5 + SHA-256 against each pinned key. Returns the key id or None."""
    for kid, n64, e64 in PINNED:
        n = int.from_bytes(base64.b64decode(n64), 'big'); e = int.from_bytes(base64.b64decode(e64), 'big')
        k = (n.bit_length() + 7) // 8
        if len(sig) != k: continue
        m = pow(int.from_bytes(sig, 'big'), e, n).to_bytes(k, 'big')
        want = b'\x00\x01' + b'\xff' * (k - len(SHA256_PREFIX) - 32 - 3) + b'\x00' + SHA256_PREFIX + hashlib.sha256(data).digest()
        if m == want: return kid
    return None


def allowed_url(u):
    p = urllib.parse.urlsplit(u)
    return p.scheme == 'https' or (p.scheme == 'http' and p.hostname in ('127.0.0.1', 'localhost', '::1'))


def get_bytes(url, maxlen, exact=-1):
    """GET with redirects OFF. Offline = could not connect; Refused = it answered wrongly."""
    if not allowed_url(url): raise Refused('not https: ' + url)
    p = urllib.parse.urlsplit(url)
    path = p.path + ('?' + p.query if p.query else '')
    c = None
    try:
        if p.scheme == 'https': c = http.client.HTTPSConnection(p.hostname, p.port, timeout=30, context=ssl.create_default_context())
        else: c = http.client.HTTPConnection(p.hostname, p.port, timeout=30)
        c.request('GET', path, headers={'User-Agent': 'RagolsWrath-Updater-Linux/1', 'Cache-Control': 'no-cache'})
        r = c.getresponse()
        if 300 <= r.status < 400: raise Refused('redirect (%d) for %s - updates never follow redirects' % (r.status, url))
        if r.status != 200: raise Refused('the site answered %d for %s' % (r.status, url))
        cl = r.getheader('Content-Length')
        if exact >= 0 and cl is not None and int(cl) != exact: raise Refused('%s is %s bytes, the release says %d' % (url, cl, exact))
        buf = bytearray()
        while True:
            chunk = r.read(65536)
            if not chunk: break
            buf += chunk
            if len(buf) > maxlen: raise Refused('%s is bigger than the release says' % url)
        if exact >= 0 and len(buf) != exact: raise Refused('%s came in at %d bytes, the release says %d (cut off?)' % (url, len(buf), exact))
        return bytes(buf)
    except (OSError, http.client.HTTPException) as ex:   # includes ssl errors and timeouts
        raise Offline('%s %s' % (ex, url))
    finally:
        if c: c.close()


def client_path(root, rel):
    """Same rules as update.ps1 Resolve-ClientPath, plus: no symlinked folder may lead out of the client folder."""
    if not rel or len(rel) > 200: raise Refused("bad path '%s'" % rel)
    for s in rel.split('/'):
        if not SEGMENT.match(s) or s in ('.', '..') or re.search(r'[. ]$', s) or DEVICE.match(s): raise Refused("unsafe path '%s'" % rel)
        if NEVER.match(s): raise Refused("'%s' is on the never-touch list" % rel)
    full = os.path.normpath(os.path.join(root, *rel.split('/')))
    if not full.startswith(root + os.sep): raise Refused("'%s' is outside the client folder" % rel)
    rr = os.path.realpath(root); d = os.path.realpath(os.path.dirname(full))
    if d != rr and not d.startswith(rr + os.sep): raise Refused("'%s' leads out of the client folder through a link" % rel)
    return full


def game_running():
    try:
        for pid in os.listdir('/proc'):
            if pid.isdigit() and pid != str(os.getpid()):
                try: cmd = slurp('/proc/%s/cmdline' % pid).lower()
                except OSError: continue
                if b'psobb.exe' in cmd and b'ragolswrath_update' not in cmd: return True
    except OSError: pass   # no /proc (not Linux): skip the check
    return False


def read_state(sf):
    try:
        with open(sf, encoding='utf-8-sig') as f: j = json.load(f)
        return {'build': j['build'] if whole(j.get('build')) else 0, 'news': j.get('news') or []}
    except Exception: return {'build': 0, 'news': []}


def write_state(sf, build, news, result, message):
    o = {'build': build, 'result': result, 'message': message, 'checkedAt': time.strftime('%Y-%m-%dT%H:%M:%S'), 'news': news}
    with open(sf + '.tmp', 'w', encoding='utf-8') as f: json.dump(o, f, indent=2)
    os.replace(sf + '.tmp', sf)


def update_addon_loader(root, stage, m):
    """Port of update.ps1 Update-AddonLoader: swaps an OLD add-on loader for the one inside the signed add-ons package."""
    try:
        dll = os.path.join(root, 'dinput8.dll')
        if not os.path.isdir(os.path.join(root, 'addons')) or not os.path.isfile(dll): return ''
        old = sha(slurp(dll))
        if old not in OLD_LOADERS: return ''
        pk = sorted((f for f in m['files'] if re.match(r'^addons-\d{1,9}\.zip$', str(f.get('path')))), key=lambda f: int(re.sub(r'\D', '', f['path'])), reverse=True)
        if not pk: return ''
        zp = os.path.join(root, pk[0]['path'])
        if not os.path.isfile(zp) or sha(slurp(zp)) != pk[0]['sha256']: return '; add-on loader not changed (%s is not the signed copy)' % pk[0]['path']
        with zipfile.ZipFile(zp) as z:
            if z.namelist().count('dinput8.dll') != 1: return '; add-on loader not changed (%s has no single dinput8.dll)' % pk[0]['path']
            data = z.read('dinput8.dll')
        if sha(data) == old: return ''
        bak = os.path.join(root, 'settings-backups', 'addon-loader-' + old[:8]); os.makedirs(bak, exist_ok=True)
        shutil.copy2(dll, os.path.join(bak, 'dinput8.dll'))
        os.makedirs(stage, exist_ok=True); tmp = os.path.join(stage, 'dinput8.dll')
        with open(tmp, 'wb') as f: f.write(data)
        os.replace(tmp, dll)
        return '; add-on loader updated from %s (old one kept in settings-backups/%s)' % (pk[0]['path'], os.path.basename(bak))
    except Exception as ex: return '; add-on loader not changed (%s)' % ex


def run(root, base, state, stage):
    if not os.path.isdir(root): raise Refused('no client folder at ' + root)
    if game_running(): raise Refused('the game is running - close it, then run the update again')
    if not base.endswith('/'): base += '/'
    if not allowed_url(base): raise Refused('the update address is not https: ' + base)
    mb = get_bytes(urllib.parse.urljoin(base, 'manifest.json'), 2 << 20)
    st = get_bytes(urllib.parse.urljoin(base, 'manifest.json.sig'), 4096)
    try: sig = base64.b64decode(st.strip(), validate=True)
    except Exception: raise Refused('the signature file is damaged')
    kid = verify(mb, sig)
    if not kid: raise Refused('the release signature does not match a pinned key - update ignored')
    try: m = json.loads(mb.decode('utf-8').lstrip('﻿'))
    except Exception: raise Refused('the signed manifest is not valid JSON')
    build = m.get('build')
    if not whole(build) or build < 1: raise Refused('the manifest has no valid build number')
    if build < state['build']: raise Refused('the site offers build %d but build %d is installed (an old release replayed?)' % (build, state['build']))

    addons = os.path.isdir(os.path.join(root, 'addons'))
    seen = set(); todo = []
    for f in m.get('files') or []:
        rel = str(f.get('path')); full = client_path(root, rel)
        if re.match(r'^(psobb\.exe|ultima\.dll)$', rel, re.I): raise Refused(rel + ' only changes through byte edits')
        if full in seen: raise Refused("'%s' is listed twice" % rel)
        seen.add(full)
        if not HEX64.match(str(f.get('sha256'))): raise Refused('bad SHA-256 for ' + rel)
        if not whole(f.get('size')) or f['size'] > 512 << 20: raise Refused('bad size for ' + rel)
        if f.get('policy') not in ('replace', 'ifMissing'): raise Refused('bad policy for ' + rel)
        if f.get('group') not in ('base', 'addons'): raise Refused('bad group for ' + rel)
        if not isinstance(f.get('url'), str) or not f['url']: raise Refused('no url for ' + rel)
        url = urllib.parse.urljoin(base, f['url'])
        if not allowed_url(url): raise Refused('not https: ' + url)
        if f['group'] == 'addons' and not addons: continue
        if os.path.isdir(full): raise Refused("'%s' is a folder here" % rel)
        if os.path.exists(full):
            if f['policy'] == 'ifMissing': continue
            if os.path.getsize(full) == f['size'] and sha(slurp(full)) == f['sha256']: continue
        todo.append({'rel': rel, 'full': full, 'url': url, 'size': f['size'], 'sha': f['sha256']})

    by = {}
    for e in m.get('edits') or []:
        p = str(e.get('path')).lower()
        if p not in ('psobb.exe', 'ultima.dll'): raise Refused("byte edits are only for psobb.exe / ultima.dll, not '%s'" % e.get('path'))
        if not HEX64.match(str(e.get('from'))) or not HEX64.match(str(e.get('to'))): raise Refused('bad hash in a byte edit of ' + p)
        by.setdefault(p, []).append(e)
    edited = []
    for p, chain in by.items():
        full = next((os.path.join(root, nm) for nm in os.listdir(root) if nm.lower() == p), None)   # Windows zips may keep "Psobb.exe"
        if not full or not os.path.isfile(full): raise Refused(p + ' is missing from the client folder')
        b = bytearray(slurp(full)); orig = cur = sha(bytes(b))
        for e in chain:
            if cur != e['from']: continue
            for op in e.get('ops') or []:
                off = op.get('off')
                try: old = bytes.fromhex(op['old']); new = bytes.fromhex(op['new'])
                except Exception: raise Refused('bad hex in a byte edit')
                if not whole(off) or len(old) != len(new) or off + len(old) > len(b): raise Refused('bad op in a byte edit of ' + p)
                if bytes(b[off:off + len(old)]) != old: raise Refused('%s does not have the expected bytes at 0x%X - nothing applied' % (p, off))
                b[off:off + len(new)] = new
            cur = sha(bytes(b))
            if cur != e['to']: raise Refused(p + ' came out different from what the release says - nothing applied')
        if cur != chain[-1]['to']: raise Refused(p + ' is not a version this release knows (changed by hand?) - nothing applied')
        if cur != orig: edited.append({'rel': p, 'full': full, 'bytes': bytes(b)})

    state['manifest'] = m
    if not todo and not edited:
        state['build'] = build; state['news'] = m.get('news') or []
        return 'up to date (build %d)' % build

    # Download + check everything before touching a single file.
    os.makedirs(stage, exist_ok=True); n = 0
    for t in todo:
        b = get_bytes(t['url'], t['size'], t['size'])
        if sha(b) != t['sha']: raise Refused('%s failed its SHA-256 check (damaged or tampered download) - nothing changed' % t['rel'])
        t['staged'] = os.path.join(stage, 'f%d' % n); n += 1
        with open(t['staged'], 'wb') as f: f.write(b)
    for e in edited:
        e['staged'] = os.path.join(stage, 'e%d' % n); n += 1
        with open(e['staged'], 'wb') as f: f.write(e['bytes'])

    # Swap in; the updater's own files last. Any failure puts back everything already swapped.
    self_files = ('ragolswrath_update.py', 'update-linux.sh')
    order = [t for t in todo if t['rel'] not in self_files] + edited + [t for t in todo if t['rel'] in self_files]
    done = []
    try:
        for t in order:
            os.makedirs(os.path.dirname(t['full']), exist_ok=True)
            if os.path.exists(t['full']):
                t['backup'] = t['staged'] + '.old'; shutil.copy2(t['full'], t['backup'])
                shutil.copymode(t['full'], t['staged'])   # keep the old file's permissions (psobb.exe may need +x under Wine)
            else: t['backup'] = None
            os.replace(t['staged'], t['full']); done.append(t)
    except Exception as ex:
        lost = []
        for t in reversed(done):
            try:
                if t['backup']: shutil.copyfile(t['backup'], t['full'])
                else: os.remove(t['full'])
            except Exception: lost.append(t['rel'])
        if lost: raise Refused('could not swap the new files in (%s) and could not put back: %s - run the update again to repair' % (ex, ', '.join(lost)))
        raise Refused('could not swap the new files in (%s) - everything was put back' % ex)
    state['build'] = build; state['news'] = m.get('news') or []
    return 'updated to build %d (%d file(s), %d byte edit(s); signed by %s)' % (build, len(todo), len(edited), kid)


def screen_size(sysroot='/'):
    """The biggest connected screen's native size from /sys/class/drm (X11 and Wayland alike), landscape (the Steam Deck's panel
    reports 800x1280). None when unknown."""
    best = None
    for st in sorted(os.listdir(os.path.join(sysroot, 'sys/class/drm')) if os.path.isdir(os.path.join(sysroot, 'sys/class/drm')) else []):
        d = os.path.join(sysroot, 'sys/class/drm', st)
        try:
            if open(os.path.join(d, 'status')).read().strip() != 'connected': continue
            m = re.match(r'^(\d+)x(\d+)', open(os.path.join(d, 'modes')).readline())
        except OSError: continue
        if m:
            w, h = sorted((int(m.group(1)), int(m.group(2))), reverse=True)
            if not best or w * h > best[0] * best[1]: best = (w, h)
    return best


def game_settings(prefix, size):
    """Give a Wine / Proton prefix the settings the game needs to draw at full size - the Windows launcher writes them, the Linux
    scripts did not (2026-10-17: the game drew 640x480 stretched). psobb loads its saved size only when CTRLBUF is 12 bytes and
    GRAPHICCTRL 36 (0x00482EAC), otherwise it draws a fixed 640x480; ultima.dll sizes the picture from RWrath WindowWidth /
    WindowHeight (640x480 when missing). ONLY MISSING values are added (a player's own stay). Edits user.reg as text while the game
    is not running. -> what was done, for the log."""
    reg = os.path.join(prefix, 'user.reg')
    if not os.path.isfile(reg): return 'no %s yet (the first start creates it) - full-size settings from the next start' % reg
    text = open(reg, encoding='utf-8', errors='surrogateescape').read()
    hexv = lambda b: 'hex:' + ','.join('%02x' % x for x in b)
    gc = bytearray(36); gc[0] = 3; gc[24] = 1; gc[32] = 1                     # the launcher's defaults (Settings.cs)
    want = [('Software\\\\SonicTeam\\\\PSOBB', [('CTRLBUF', hexv(bytes([2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]))), ('GRAPHICCTRL', hexv(gc)),
                                                ('WINDOW_MODE', 'dword:00000001')])]
    if size: want.append(('Software\\\\SonicTeam\\\\PSOBB\\\\RWrath', [('WindowWidth', 'dword:%08x' % size[0]), ('WindowHeight', 'dword:%08x' % size[1]),
                                                                    ('WindowMode', 'dword:00000002')]))   # 2 = borderless, maximised
    if re.search(r'^\[Software\\\\Wow6432Node(\\\\|\])', text, re.M | re.I):                 # 32-bit programs read there when it exists
        want += [(k.replace('Software', 'Software\\\\Wow6432Node', 1), v) for k, v in want]
    lines, added = text.split('\n'), []
    for key, vals in want:
        head = next((i for i, l in enumerate(lines) if re.match(r'^\[%s\](\s|$)' % re.escape(key), l, re.I)), None)
        if head is None:
            lines += ['', '[%s] %d' % (key, int(time.time()))]; head = len(lines) - 1
        end = next((i for i in range(head + 1, len(lines)) if lines[i].startswith('[')), len(lines))
        at = head + 1
        while at < end and lines[at].startswith('#'): at += 1                          # after #time= / #class= lines
        have = {m.group(1).lower() for m in (re.match(r'^"([^"]+)"=', l) for l in lines[head + 1:end]) if m}
        new = ['"%s"=%s' % (n, v) for n, v in vals if n.lower() not in have]
        lines[at:at] = new; added += [key.replace('\\\\', '\\') + '\\' + l.split('"')[1] for l in new]
    if not added: return 'game settings already there'
    shutil.copy2(reg, reg + '.ragolswrath-bak')
    with open(reg + '.tmp', 'w', encoding='utf-8', errors='surrogateescape', newline='\n') as f: f.write('\n'.join(lines))
    os.replace(reg + '.tmp', reg)
    return 'added %s%s (old file: user.reg.ragolswrath-bak)' % (', '.join(added), '' if size else '; screen size unknown, not set')


def main(argv=None):
    ap = argparse.ArgumentParser()
    ap.add_argument('--root', default=os.path.dirname(os.path.abspath(__file__))); ap.add_argument('--base-url', default=BASE_URL)
    ap.add_argument('--game-settings', metavar='PREFIX', help='only add the missing full-size game settings to this Wine prefix (play-linux.sh)')
    a = ap.parse_args(argv)
    if a.game_settings:
        try: print('settings: ' + game_settings(a.game_settings, screen_size()))
        except Exception as ex: print('settings: not changed (%r)' % ex)
        return 0
    root = os.path.normpath(os.path.abspath(a.root)); stage = os.path.join(root, '_update'); sf = os.path.join(root, 'update-state.json')
    state = read_state(sf); prev = dict(state); result, code = 'ok', 0
    try:
        if os.path.isdir(stage): shutil.rmtree(stage, ignore_errors=True)   # left over from a crash
        msg = run(root, a.base_url, state, stage)
        if state.get('manifest'): msg += update_addon_loader(root, stage, state['manifest'])
    except Offline as ex: result, code, msg = 'offline', 1, 'update site not reachable, starting with what you have (%s)' % ex; state.update(prev)
    except Refused as ex: result, code, msg = 'refused', 2, str(ex); state.update(prev)
    except Exception as ex: result, code, msg = 'refused', 2, 'unexpected error, nothing changed: %r' % ex; state.update(prev)
    finally: shutil.rmtree(stage, ignore_errors=True)
    try: write_state(sf, state['build'], state['news'], result, msg)
    except Exception: pass
    print('update: %s - %s' % (result, msg))
    return code


if __name__ == '__main__': sys.exit(main())
