#!/usr/bin/env python3 # SPDX-License-Identifier: GPL-2.0-or-later """Subtractive copy of Bureau Libre Free-EOS 1.2-1, using ready7-Zip/PyCdlib. No Windows executable is run. Original bytes are immutable, output revisions unique. """ from pathlib import Path import argparse, hashlib, io, json, os, re, shutil, subprocess, zipfile from datetime import datetime, timezone from urllib.parse import unquote, urlsplit import pycdlib from bs4 import BeautifulSoup DOC = Path(__file__).resolve().parent CACHE = Path.home() / '.cache/svits/original-media/bureau-libre12-cleaned' INPUTS = json.loads((DOC/'inputs.json').read_text()) SHA = lambda path: hashlib.sha256(Path(path).read_bytes()).hexdigest() def write_json(path, value): Path(path).write_text(json.dumps(value, ensure_ascii=False, indent=2)+'\n', encoding='utf8') def main(): parser=argparse.ArgumentParser();parser.add_argument('--revision', required=True);args=parser.parse_args() if not re.fullmatch('[A-Za-z0-9_-]+',args.revision):raise ValueError('Invalid revision') out=CACHE/args.revision out.mkdir(exist_ok=False) tree=out/'tree';tree.mkdir() for record in INPUTS['files']+INPUTS['reference']+[INPUTS['extractor']]: if Path(record['localFile']).stat().st_size!=record['bytes'] or SHA(record['localFile'])!=record['sha256']: raise ValueError('Input mismatch: '+record['localFile']) original=Path(INPUTS['files'][0]['localFile']) inventory=json.loads((DOC/'original-inventory.json').read_text())['files'] iso=pycdlib.PyCdlib();iso.open(str(original)) original_menu=out/'original-menu';extracted=out/'extracted';retained=[];deleted=[];modified=[] def from_iso(path,target): target.parent.mkdir(parents=True,exist_ok=True);iso.get_file_from_iso(str(target),joliet_path=path) for record in inventory: path=record['path'] if path.startswith('/interface_html/'): from_iso(path,original_menu/path.removeprefix('/interface_html/')) original_installers={ 'abiword':'/abiword/abiword-setup-2.4.1.exe', 'sevenzip':'/sevenzip/7z431.exe', 'virtualdub':'/virtualdub/VirtualDub-1.6.11.exe', } for name,path in original_installers.items(): installer=out/'input-installers'/Path(path).name;from_iso(path,installer) subprocess.run([INPUTS['extractor']['localFile'],'x','-y','-o'+str(extracted/name),str(installer)],check=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) if SHA(out/'input-installers/abiword-setup-2.4.1.exe')!=INPUTS['abiwordExactInstallerSha256']:raise ValueError('AbiWord identity') def copy_embedded(app,relative): source=extracted/app/relative;target=tree/app/relative;target.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(source,target) retained.append({'originalPath':original_installers[app]+'!'+relative,'outputPath':'/'+app+'/'+relative,'bytes':target.stat().st_size,'sha256':SHA(target),'change':'unchanged embedded bytes; outer installer omitted'}) for record in json.loads((DOC/'abiword-allowlist.json').read_text()): rel=record['outputPath'].removeprefix('/programs/abiword/') if SHA(extracted/'abiword'/rel)!=record['sha256']:raise ValueError('AbiWord allowlist mismatch '+rel) copy_embedded('abiword',rel) for source in sorted(p for p in (extracted/'sevenzip').rglob('*') if p.is_file()): relative=source.relative_to(extracted/'sevenzip').as_posix() if relative.startswith('$PLUGINSDIR/') or relative=='Uninstall.exe':continue copy_embedded('sevenzip',relative) reference=zipfile.ZipFile(INPUTS['reference'][0]['localFile']) matching={} for source in sorted(p for p in (extracted/'virtualdub').rglob('*') if p.is_file()): rel=source.relative_to(extracted/'virtualdub').as_posix() official=next((n for n in reference.namelist() if n.lower()==rel.lower()),None) if official and source.read_bytes()==reference.read(official):matching[rel]=official;copy_embedded('virtualdub',rel) assert all(name in matching for name in ['VirtualDub.exe','vdub.exe','vdremote.dll','vdicmdrv.dll','vdsvrlnk.dll','auxsetup.exe','VirtualDub.vdhelp','copying']) reference.close() # Native editable presentation is CC BY-SA 2.0 France; keep its frame layout, # artwork, two original application categories, authors and licence footer. # Remove omitted applications and their documentation, not merely menu links. selected_pages={ 'culture_numerique/abiword.htm','culture_numerique/virtualdub.htm', 'pour_aller_plus_loin/7-zip.htm', } for p in sorted(p for p in original_menu.rglob('*') if p.is_file()): rel=p.relative_to(original_menu).as_posix() keep=rel=='index.htm' or rel.startswith(('structure/','images/','presentation/','res/')) or rel in selected_pages or (rel.startswith(('culture_numerique/','pour_aller_plus_loin/')) and p.name in ['menu.js','menu1.htm','menu1r.htm','introtheme.htm']) if 'CreativeCommonsDeed-by-nc-sa' in rel or rel in ['presentation/correspondances.htm']:keep=False if not keep:continue target=tree/'interface_html'/rel;target.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(p,target) # Keep original category positions/identifiers; blank categories disappear in # the existing menu renderer. No replacement menu framework or Windows helper. menu=tree/'interface_html';config=menu/'structure/config.js';s=config.read_text(encoding='cp1252') for key in ['theme1','theme4']:s=re.sub(r'^'+key+r'\s*=.*$',key+' = ""',s,flags=re.M) config.write_text(s,encoding='cp1252');modified.append('/interface_html/structure/config.js') category_keep={'culture_numerique':{7,12},'pour_aller_plus_loin':{5},'presentation':{1,2,3,5,6}} for category,keep in category_keep.items(): p=menu/category/'menu.js';s=p.read_text(encoding='cp1252') for match in list(re.finditer(r'^smenu([15])_(\d+)\s*=.*$',s,re.M)): if int(match.group(2)) and int(match.group(2)) not in keep: s=s.replace(match.group(0),f'smenu{match.group(1)}_{match.group(2)} = ""') p.write_text(s,encoding='cp1252');modified.append('/interface_html/'+category+'/menu.js') def html_edit(rel,fn): p=menu/rel;soup=BeautifulSoup(p.read_bytes(),'html.parser');fn(soup) p.write_text(soup.decode(formatter='html'),encoding='cp1252',errors='xmlcharrefreplace');modified.append('/interface_html/'+rel) notice='Copie modifiee et reduite, 22 octobre 2026. Derived from Bureau Libre - Free-EOS 1.2-1; not the complete original release. Presentation: ville de Brest et contributeurs, CC BY-SA 2.0 France.' def add_notice(soup): body=soup.body if body: p=soup.new_tag('p',style='font:12px Arial,sans-serif;color:#263b48;background:#f1f1df;padding:8px;border:1px solid #c5c9b9;') p.string=notice;body.insert(0,p) # Content pages identify the modification; navigation frames and the original # licence deed stay verbatim, preserving the original frame geometry. for p in menu.rglob('*'): rel=p.relative_to(menu).as_posix() if p.suffix.lower() in ['.htm','.html'] and rel!='index.htm' and not rel.startswith('structure/') and not p.name.startswith('menu1'): html_edit(rel,add_notice) def title_change(soup):soup.title.string='Cleaned applications - Bureau Libre 1.2-1 derivative' html_edit('index.htm',title_change) def replace_body(rel,title,paragraph): def change(soup): soup.body.clear();add_notice(soup);h=soup.new_tag('h2');h.string=title;soup.body.append(h) p=soup.new_tag('p');p.string=paragraph;soup.body.append(p) html_edit(rel,change) replace_body('culture_numerique/introtheme.htm','Culture numerique','Cette copie conserve AbiWord 2.4.1 et VirtualDub 1.6.11 de la collection originale. Choisissez le logiciel dans le menu de gauche. Les autres applications de cette rubrique sont absentes.') replace_body('pour_aller_plus_loin/introtheme.htm','Pour aller plus loin','Cette copie conserve 7-Zip 4.31 de la collection originale. Les autres applications de cette rubrique sont absentes.') replace_body('presentation/install.htm','Utiliser cette copie','Open the portable application from its folder on the CD. No collection installer, font installer or dictionary package is included. See README.txt for exact paths and SOURCES.txt for complete corresponding sources. This derivative retains only three applications; the original collection is archived separately.') launches={'culture_numerique/abiword.htm':'../../abiword/AbiWord/bin/AbiWord.exe','culture_numerique/virtualdub.htm':'../../virtualdub/VirtualDub.exe','pour_aller_plus_loin/7-zip.htm':'../../sevenzip/7zFM.exe'} for page,href in launches.items(): def add_launch(soup,href=href): for a in soup.select('a[href]'): if 'tutoriels/' in a['href']:a.replace_with(a.get_text()) p=soup.new_tag('p');a=soup.new_tag('a',href=href,target='_blank');a.string='Open portable application';p.append(a);soup.body.append(p) if 'abiword' in href: p=soup.new_tag('p');p.string='This copy omits the optional Dingbats font, spellchecking dictionary and external plugins. It uses the fonts already installed in Windows.';soup.body.append(p) html_edit(page,add_launch) # No original mass installer or unaudited tutorial is silently carried over. for name in ['BureauLibreFree-EOS.nsi','versions.nsi','tutoriels.nsi','licence-gnugpl.txt']: target=tree/'upstream-source'/name;from_iso('/'+name,target) iso.close() sources=[] for rec in INPUTS['files'][1:]: target=tree/'sources'/rec['filename'];target.parent.mkdir(exist_ok=True);shutil.copy2(rec['localFile'],target);sources.append({**rec,'outputPath':'/sources/'+rec['filename']}) notices=tree/'notices';notices.mkdir() shutil.copy2(extracted/'sevenzip/License.txt',notices/'7zip-License.txt');shutil.copy2(extracted/'sevenzip/copying.txt',notices/'7zip-LGPL.txt');shutil.copy2(extracted/'virtualdub/copying',notices/'VirtualDub-GPL.txt') # Extract original unRAR restriction verbatim from exact source, no relabeling. import tarfile with tarfile.open(INPUTS['files'][1]['localFile']) as t: for member in t.getmembers(): if member.name.endswith('/unRarLicense.txt') or member.name=='DOC/unRarLicense.txt': (notices/'7zip-unRAR.txt').write_bytes(t.extractfile(member).read());break else:raise ValueError('unRAR notice missing') source_text='Complete corresponding source archives supplied on this same disc.\r\n\r\n'+'\r\n\r\n'.join(r['filename']+'\r\n'+r['originURL']+'\r\nSHA256 '+r['sha256']+'\r\n'+r['role'] for r in sources)+'\r\n' (tree/'SOURCES.txt').write_bytes(source_text.encode('ascii')) readme='''CLEANED APPLICATIONS - BUREAU LIBRE1.2-1 DERIVATIVE Modified copy,22 October 2026. Not the complete original release. Retained unchanged application bytes from the original CD: abiword/AbiWord/bin/AbiWord.exe AbiWord 2.4.1 sevenzip/7zFM.exe 7-Zip 4.31 virtualdub/VirtualDub.exe VirtualDub 1.6.11 Open interface_html/index.htm to use the original French presentation, with omitted entries removed and direct links to these portable apps. The root original NSIS mass-installer and all unreviewed applications, plugins, dictionaries, fonts, Java/PDFCreator bundles and tutorials are absent. Optional AbiWord Dingbats and compiled spellchecking dictionary are absent. VirtualDub's external French help/wrapper is absent; its unchanged original built-in English help remains. No application executable has been patched or newly compiled. Presentation/artwork: Bureau Libre, ville de Brest et contributeurs. The native footer grants CC BY-SA 2.0 France, retained in interface_html. This modified presentation is licensed under those same terms: https://creativecommons.org/licenses/by-sa/2.0/fr/ Original cover art describes the original full release, not this copy. The original NSIS script by Fabien ILLIDE is GPL 2-or-later and remains in upstream-source, with its notice. No original compiled launcher is included. This is an independently modified copy, not upstream endorsed. AbiWord 2.4.1: GPL 2-or-later; original copying/readme/component notices and exact corresponding source are included. Unused font/dictionary blobs were removed from that source with an explicit modification list; no application source code changed. Actual zlib1.dll is version 1.2.2, so its exact separate source is included as well. 7-Zip 4.31: LGPL 2.1-or-later. Exact complete source and native notices are included, plus the unRAR restrictions unchanged: RAR decoding may be distributed free of charge; no RAR-compressor recreation is allowed. VirtualDub 1.6.11: GPL 2-or-later. All 6 retained EXE/DLLs match the official 1.6.11 release ZIP byte-for-byte. Its complete source/build/help is on this same disc. Copyright 1998-2005 Avery Lee and component notices remain. SOURCES.txt lists source archives, primary URLs and SHA256. MODIFICATIONS.json and DELETED.json record this subtractive copy. source-build/build.py is the build source; nothing in this ISO modifies Windows. Native Windows 2000 launch/read/eject verification is still pending. ''' (tree/'README.txt').write_bytes(readme.replace('\n','\r\n').encode('ascii')) output_original_paths={'/interface_html/'+p.relative_to(menu).as_posix() for p in menu.rglob('*') if p.is_file()} output_original_paths.update('/'+n for n in ['BureauLibreFree-EOS.nsi','versions.nsi','tutoriels.nsi','licence-gnugpl.txt']) for row in inventory: if row['path'] not in output_original_paths: if row['path'] in original_installers.values():reason='Outer installer omitted; selected unchanged embedded portable files retained separately' elif row['path'].startswith(('/abiword/','/virtualdub/','/sevenzip/')):reason='Additional plugin/font/dictionary/codec or wrapper absent; exact independent closure not completed' else:reason='Entire non-selected application/tutorial/installer absent in this revision; no assertion that ordinary free-software terms prohibit it' deleted.append({**row,'reason':reason}) mods={'modified':datetime.now(timezone.utc).isoformat(),'authorization':'Owner: take everything cleared; remove the rest; preserve original separately','original':INPUTS['files'][0], 'retained':['AbiWord 2.4.1','7-Zip 4.31','VirtualDub 1.6.11'],'presentationLicense':'CC-BY-SA-2.0-FR','nativeInstallerSourceLicense':'GPL-2.0-or-later','menuChanges':sorted(set(modified)),'newCollectionName':'Cleaned applications - Bureau Libre 1.2-1 derivative','payloadCodeChanges':False,'missingProofIsNotProhibition':True,'guestFlow':'pending','exactSources':sources} write_json(tree/'MODIFICATIONS.json',mods);write_json(tree/'DELETED.json',deleted) (tree/'source-build').mkdir() for name in ['build.py','inputs.json','abiword-allowlist.json','original-inventory.json','requirements.txt']: shutil.copy2(DOC/name,tree/'source-build'/name) write_json(DOC/'retained-manifest.json',retained);write_json(DOC/'deleted-manifest.json',deleted);write_json(DOC/'source-files.json',sources);write_json(DOC/'clearance-and-modifications.json',mods) result=[];iso=pycdlib.PyCdlib();iso.new(interchange_level=3,joliet=3,rock_ridge='1.09',vol_ident='BUREAU12_CLEAN') def primary(rel):return '/'+ '/'.join(re.sub('[^A-Z0-9_]','_',part.upper()) for part in rel.split('/')) for p in sorted((p for p in tree.rglob('*') if p.is_dir()),key=lambda p:(len(p.parts),str(p))): rel=p.relative_to(tree).as_posix();iso.add_directory(iso_path=primary(rel),joliet_path='/'+rel,rr_name=p.name) for p in sorted(p for p in tree.rglob('*') if p.is_file()): rel=p.relative_to(tree).as_posix();parent=p.parent.relative_to(tree).as_posix();stem,dot,ext=p.name.rpartition('.');name=re.sub('[^A-Z0-9_]','_',(stem if dot else ext).upper()) if dot:name+='.'+re.sub('[^A-Z0-9_]','_',ext.upper()) ip=(primary(parent) if parent!='.' else '')+'/'+name+';1';iso.add_file(str(p),iso_path=ip,joliet_path='/'+rel,rr_name=p.name) result.append({'path':'/'+rel,'bytes':p.stat().st_size,'sha256':SHA(p)}) destination=out/'BureauLibre12-cleaned.iso';iso.write(str(destination));iso.close();verify=pycdlib.PyCdlib();verify.open(str(destination)) for row in result: b=io.BytesIO();verify.get_file_from_iso_fp(b,joliet_path=row['path']) if hashlib.sha256(b.getvalue()).hexdigest()!=row['sha256']:raise ValueError('Readback mismatch: '+row['path']) verify.close();write_json(DOC/'output-inventory.json',result) proof={'created':datetime.now(timezone.utc).isoformat(),'status':'complete-bytes-readback-pass-guest-pending','original':INPUTS['files'][0],'output':{'localFile':str(destination),'bytes':destination.stat().st_size,'sha256':SHA(destination),'volume':'BUREAU12_CLEAN'},'tree':str(tree),'retainedApplications':mods['retained'],'fileCount':len(result),'embeddedFiles':len(retained),'sourceArchives':len(sources),'sourceBytes':sum(r['bytes'] for r in sources),'readback':'Every file read from final ISO via Joliet and SHA256 matched','originalUntouched':SHA(original)==INPUTS['files'][0]['sha256'],'providerAndCatalog':'not changed; no Insert enabled','guest':'pending exclusive window through media-owner'} write_json(DOC/'ready-artifact.json',proof);print(json.dumps(proof,ensure_ascii=False,indent=2)) if __name__=='__main__':main()