Files

66 lines
5.6 KiB
Python

#!/usr/bin/env python3
"""Compose an offline physical successor with the existing icon/DB2 pipeline."""
import argparse,hashlib,importlib.util,json,struct,sys
from pathlib import Path
OPS=Path(__file__).resolve().parents[1];sys.path.insert(0,str(OPS))
from casc_asset_package import root_groups
def load(path):return json.loads(path.read_text())
def save(path,value):path.parent.mkdir(parents=True,exist_ok=True);path.write_text(json.dumps(value,indent=2)+'\n')
def sha(path):return hashlib.sha256(path.read_bytes()).hexdigest()
def module(name,path):
spec=importlib.util.spec_from_file_location(name,path);result=importlib.util.module_from_spec(spec);sys.modules[name]=result;spec.loader.exec_module(result);return result
def compose(a):
root=a.root;step=root/'content-step';step.mkdir(exist_ok=True);parent_pin=load(root/'native-content-parent.json');parent=a.parent
if sha(a.client/'.build.info')!=parent_pin['build_info_sha256']:raise ValueError('Installed content parent changed')
meta=load(parent/'metadata.json')
if meta['key']!=parent_pin['build_key'] or sha(parent/'.build.info.candidate')!=parent_pin['build_info_sha256']:raise ValueError('Frozen parent does not match LOCAL')
before=(parent/'decoded/root.bin').read_bytes()
if hashlib.md5(before).hexdigest()!=parent_pin['root_md5']:raise ValueError('ROOT parent pin')
layout=root_groups(before);cells={}
for group in layout['groups']:
ident=0
for n,(delta,) in enumerate(struct.iter_unpack('<I',before[group['ids_offset']:group['ckeys_offset']])):
ident+=delta;cells.setdefault(ident,[]).append((group,group['ckeys_offset']+16*n));ident+=1
wanted={f'dbfilesclient/{t.lower()}.db2':t for t in ['Item','ItemEffect','ItemXItemEffect','Spell','SpellName','SpellMisc','SpellEffect']};fdids={}
for line in a.listfile.open():
ident,_,name=line.rstrip().partition(';')
if name.lower() in wanted:fdids[wanted[name.lower()]]=int(ident)
if len(fdids)!=7:raise ValueError('DB2 FDID closure')
specs=[];patched=bytearray(before)
for table,fdid in sorted(fdids.items()):
source=root/'native-baseline'/(table+'.db2');dest=(root/'spell-db2' if table.startswith('Spell') else root/'candidate/db2')/(table+'.db2')
old=source.read_bytes();new=dest.read_bytes();ckey=hashlib.md5(old).hexdigest()
matches=[at for g,at in cells[fdid] if g['locale']&2 and before[at:at+16].hex()==ckey]
if len(matches)!=1:raise ValueError('Unique enUS content cell required: '+table)
patched[matches[0]:matches[0]+16]=hashlib.md5(new).digest()
path=step/(table+'.component.json');save(path,dict(parent_root=parent_pin['root_md5'],fdid=fdid,original_decoded=dict(file=str(source),md5=ckey,sha256=sha(source)),after_decoded=dict(file=str(dest),md5=hashlib.md5(new).hexdigest(),sha256=sha(dest))))
specs.append(dict(type='wdc_enus',file=str(path),sha256=sha(path)))
assets=[]
for row in load(root/'candidate/assets.json')['assets']:
if row['fdid'] in cells:raise ValueError('Reserved icon FDID now occupied')
assets.append(dict(file_data_id=row['fdid'],file=row['asset'],sha256=row['sha256'],ckey=row['content_key'],path='interface/icons/gwhybrid_'+row['sha256']+'.blp',kind='BLP'))
path=step/'icons.component.json';save(path,dict(parent_root=parent_pin['root_md5'],assets=assets));specs.append(dict(type='art',file=str(path),sha256=sha(path)))
save(step/'components.json',specs);save(step/'selected-root.json',dict(parent_root=parent_pin['root_md5'],parent_build=parent_pin['build_key'],decoded_root_sha256=hashlib.sha256(patched).hexdigest()))
compose_prepared(root,step,parent,a.client,parent_pin)
def compose_prepared(root,step,parent,client,parent_pin):
if sha(client/'.build.info')!=parent_pin['build_info_sha256'] or sha(parent/'.build.info.candidate')!=parent_pin['build_info_sha256']:raise ValueError('Prepared content parent changed')
recipe=OPS/'content-icons-20261126';frozen=module('frozen_store',recipe/'frozen_store.py');frozen.PARENT=parent;frozen.BUILD=parent_pin['build_key'];frozen.ROOT=parent_pin['root_md5'];frozen.HERE=step;frozen.CLIENT=client/'Data/data'
plan=load(parent/'stage-plan.json');segments=[int(Path(r['target']).suffix[1:]) for r in plan['forward']['copy_verified_files'] if '/data.' in r['target']]
if len(segments)!=1:raise ValueError('Expected one parent archive segment')
segment=max(segments[0],max(int(p.suffix[1:]) for p in (client/'Data/data').glob('data.*')))+1
if segment<=segments[0]:raise ValueError('Fresh segment allocation')
composer=module('compose',recipe/'compose.py');composer.main()
packager=module('source_authority_package',recipe/'package.py');packager.PARENT_SEGMENT=segments[0];packager.NEW_SEGMENT=segment;packager.metadata();packager.physical()
final=step/'candidate/stage-plan.json';candidate=load(final)
if candidate['native_runtime_verified'] or candidate['publication']!='HOLD':raise ValueError('Candidate must remain staged only')
if sha(client/'.build.info')!=parent_pin['build_info_sha256']:raise ValueError('LOCAL parent changed while staging')
save(root/'physical-content.json',dict(stage_plan=str(final),stage_plan_sha256=sha(final),parent=parent_pin,segment=segment,build_key=candidate['candidate_build_key'],root=candidate['candidate_root'],installed=False))
print('Staged physical content candidate',candidate['candidate_build_key'],'segment',segment)
if __name__=='__main__':
p=argparse.ArgumentParser(description=__doc__)
for name in ['root','parent','client','listfile']:p.add_argument('--'+name,type=Path,required=True)
compose(p.parse_args())