# SPDX-License-Identifier: GPL-2.0-or-later
"""Ready: pycdlib ISO authoring + BeautifulSoup HTML edits + stdlib archive reads.
7-Zip/innoextract/unar supplied frozen original embedded files; no Windows EXE runs.
No filesystem-format or installer-format parser is implemented here.
"""
from pathlib import Path
from datetime import datetime, timezone
from bs4 import BeautifulSoup
import argparse, hashlib, io, json, os, shutil, tarfile, zipfile
import pycdlib
HERE = Path(__file__).resolve().parent
def sha(path):
h = hashlib.sha256()
with path.open('rb') as f:
for block in iter(lambda: f.read(1024 * 1024), b''):
h.update(block)
return h.hexdigest()
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--out-dir', required=True, type=Path)
args = ap.parse_args()
if args.out_dir.exists():
raise ValueError('Use a new output directory; previous runs are immutable.')
config = json.loads((HERE / 'inputs.json').read_text())
embedded_path = HERE / config['embeddedManifest']
if sha(embedded_path) != config['embeddedManifestSha256']:
raise ValueError('Frozen embedded-file manifest changed')
embedded = {row['sourcePath']: row for row in json.loads(embedded_path.read_text())}
for path, row in embedded.items():
source = Path(path) if Path(path).is_absolute() else Path(config['workRoot']) / 'inspect' / path.lstrip('/')
if source.stat().st_size != row['bytes'] or sha(source) != row['sha256']:
raise ValueError('Original embedded bytes changed: ' + path)
work = Path(config['workRoot'])
original_path = Path(config['original']['file'])
if sha(original_path) != config['original']['hashes']['sha256']:
raise ValueError('Original ISO SHA mismatch')
for row in config['sources']:
if sha(Path(row['file'])) != row['sha256']:
raise ValueError('Source SHA mismatch: ' + row['name'])
args.out_dir.mkdir(parents=True)
tree = args.out_dir / 'tree'
tree.mkdir()
archive = args.out_dir.parent / 'archive'
archive.mkdir(exist_ok=True)
archived = archive / 'gnuwinII_bonus_November_30_2004-original.iso'
if not archived.exists():
os.link(original_path, archived)
if sha(archived) != config['original']['hashes']['sha256']:
raise ValueError('Archived original differs')
inventory = json.loads(Path('/tmp/svits-gnuwin-original-20261021/bonus-directory.json').read_text())['files']
apps = set(config['apps'])
original = pycdlib.PyCdlib()
original.open(str(original_path))
retained, deleted, added, modified = [], [], [], []
image_names = {'title.png', 'logosmall.gif', 'gwicon.png', 'bullet.gif', 'bulletanim.gif',
'gnuwinCD.jpg', 'gnuwinCD-small.jpg', 'legal.jpg', 'faq.jpg', 'install.jpg'}
languages = {'en', 'fr', 'de', 'it', 'es', 'pt', 'ct', 'hi', 'sv', 'hu'}
# Keep the original interface structure and reviewed application descriptions.
# All installers/archives are replaced by exact portable bytes below, not new applications.
for row in inventory:
p = row['path']
parts = Path(p).parts
keep = p in {'/index.html', '/autorun.inf'} or p.startswith('/gpl/')
if len(parts) > 2 and parts[1] == 'apps':
keep = (parts[2] in apps and '/install/' not in p and '/doc/' not in p) or parts[2] in languages
if len(parts) > 2 and parts[1] in languages:
keep = p.endswith('.html')
if p.startswith('/classes/'):
keep = p.endswith('.html')
if p.startswith('/images/'):
name = parts[-1]
keep = p.startswith('/images/border/') or name in image_names or name in {lang + suffix for lang in languages for suffix in ['.gif', '-small.gif']}
if p.startswith('/glossaire/'):
keep = p.endswith(('.html', '.gif', '.png'))
if keep:
target = tree / p.lstrip('/')
target.parent.mkdir(parents=True, exist_ok=True)
original.get_file_from_iso(str(target), joliet_path=p)
retained.append({'originalPath': p, 'outputPath': p, 'bytes': target.stat().st_size, 'sha256': sha(target)})
else:
reason = 'Outside this fully reviewed subset; omitted under owner cleanup instruction, not declared prohibited.'
if p.startswith('/apps/vidomi/'):
reason = 'Entire Vidomi package omitted: exact Product EULA is personal/nonredistributable except encoder.exe.'
elif '/install/' in p and len(parts) > 2 and parts[2] in apps:
reason = 'Original package omitted; reviewed byte-exact portable application parts retained separately.'
deleted.append({'originalPath': p, 'bytes': row['bytes'], 'reason': reason})
original.close()
targets = {}
def portable(app, source, excluded=()):
dest = tree / 'apps' / app / 'en' / 'install' / 'portable'
for p in sorted(x for x in source.rglob('*') if x.is_file()):
rel = p.relative_to(source)
if any(rel.as_posix() == item or rel.parts[0] == item for item in excluded) or p.name.startswith('_extract'):
continue
target = dest / rel
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(p, target)
added.append({'path': '/' + target.relative_to(tree).as_posix(), 'bytes': target.stat().st_size,
'sha256': sha(target), 'provenance': str(p), 'change': 'Exact embedded bytes; no binary patch'})
return dest
for item in config['portable']:
portable(item['id'], Path(item['directory']), item['excluded'])
targets[item['id']] = item['target']
source_rows = []
for row in config['sources']:
name = 'gnuwin-interface-2002-09-06.tar' if row['name'] == 'gnuwin2Source-2002-09-06.tar.gz' else row['name']
target = tree / 'sources' / name
target.parent.mkdir(exist_ok=True)
shutil.copy2(row['file'], target)
source_rows.append({**row, 'outputPath': '/sources/' + name})
notices = tree / 'notices'
notices.mkdir()
shutil.copy2(work / 'inspect/winpenguins/app/COPYING.TXT', notices / 'WinPenguins-GPL.txt')
shutil.copy2(work / 'inspect/winpenguins/app/README.txt', notices / 'WinPenguins-acknowledgements.txt')
shutil.copy2(work / 'inspect/blat/Readme.txt', notices / 'Blat-license-and-readme.txt')
for page in sorted(tree.rglob('*.html')):
# The historical multilingual pages use several declared encodings.
# Let the ready HTML decoder read their actual bytes before UTF-8 output.
soup = BeautifulSoup(page.read_bytes(), 'html.parser')
for a in list(soup.find_all(href=True)):
# Removing an omitted
also decomposes its other links, which
# remain in this snapshot of the original tree.
if a.attrs is None:
continue
href = a['href']
# urljoin supplies standard relative-path resolution; no custom HTML parser.
from urllib.parse import urljoin, urlsplit
resolved = urlsplit(urljoin('https://disc.invalid/' + page.relative_to(tree).as_posix(), href))
pp = Path(resolved.path).parts
if resolved.hostname == 'disc.invalid' and len(pp) > 2 and pp[1] == 'apps':
app = pp[2]
if app not in apps and app not in languages:
parent = a.find_parent('li')
(parent or a).decompose()
continue
if app in apps and ('/install/' in resolved.path or resolved.path.endswith('/install')):
a['href'] = os.path.relpath(tree / 'apps' / app / 'en/install/portable' / targets[app], page.parent).replace(os.sep, '/')
# Keep the native menu hierarchy, but do not leave links to omitted
# articles, docs or historical missing pages. No replacement app is added.
for el in list(soup.find_all(True)):
if el.attrs is None:
continue
for attr in ['href', 'src', 'background']:
href = el.get(attr)
if not href or href.startswith(('#', 'mailto:', 'javascript:')):
continue
resolved = urlsplit(urljoin('https://disc.invalid/' + page.relative_to(tree).as_posix(), href))
if resolved.hostname != 'disc.invalid':
continue
if resolved.path == '/gnuwin2Source-2002-09-06.tar.gz':
el[attr] = os.path.relpath(tree / 'sources/gnuwin-interface-2002-09-06.tar', page.parent).replace(os.sep, '/')
continue
from urllib.parse import unquote
destination = tree / unquote(resolved.path).lstrip('/')
if destination.exists():
continue
if el.name == 'area':
el.decompose()
break
if el.name == 'a':
el.unwrap()
break
if el.name in ['img', 'link', 'script']:
el.decompose()
break
del el[attr]
if soup.body:
notice = soup.new_tag('p')
notice['style'] = 'background:#fff2ba;color:#172a35;padding:8px;border:1px solid #b5a36a'
notice.string = f'MODIFIED COPY, 22 October 2026: unofficial cleaned GNUWin II selection; {len(apps)} reviewed applications. Original November 30, 2004 collection by GNU Generation/EPFL. See README.TXT and sources/.'
soup.body.insert(0, notice)
if '/apps/blat/' in page.as_posix():
condition = soup.new_tag('p')
condition.append('The original licence prohibits unsolicited commercial email; see the ')
licence_link = soup.new_tag('a', href=os.path.relpath(tree / 'notices/Blat-license-and-readme.txt', page.parent).replace(os.sep, '/'))
licence_link.string = 'included licence'
condition.append(licence_link)
condition.append('.')
soup.body.insert(1, condition)
page.write_text(str(soup), encoding='utf8')
modified.append({'path': '/' + page.relative_to(tree).as_posix(), 'change': 'Marked modified; omitted-application links removed; retained install links point to exact portable bytes'})
autorun = tree / 'autorun.inf'
autorun.write_text('[autorun]\r\nopen=explorer .\\index.html\r\nshell\\verb\\command=explorer .\\index.html\r\nshell\\verb=Cleaned GNUWin II selection\r\n', encoding='ascii')
modified.append({'path': '/autorun.inf', 'change': 'Native Explorer index entry retained; missing icon reference removed; modified-copy label'})
readme = ('CLEANED GNUWIN II BONUS WINDOWS SELECTION (2004)\n'
'Modified copy, 22 October 2026; not an official GNUWin/EPFL release.\n'
'Original collection/interface copyright2004 GNU Generation and GNUWin Team; GPL.\n'
'Original ISO archived unmodified. Original portable EXE/DLL unchanged.\n\n'
'Open index.html for the original multilingual menu.\n'
'WinPenguins0.5: apps/winpenguins/en/install/portable/winpenguins.exe\n'
'Blat1.9.4: apps/blat/en/install/portable/blat.exe (command-line utility).\n'
'Blat -h displays local help; no email is sent by disc insertion or menu browsing.\n\n'
'Complete sources and original licences accompany programs in sources/ and notices/.\n'
'WinPenguins is GPL; its original images and acknowledgements are retained.\n'
'Optional Microsoft MFC42.DLL is omitted; use the Windows system runtime.\n'
'Blat grants redistribution; its original no-unsolicited-commercial-email condition remains.\n'
'Other components with incomplete evidence were omitted, not declared prohibited.\n'
'No warranty. This is a derivative selection, not the complete original Bonus disc.\n')
(tree / 'README.TXT').write_text(readme, encoding='utf8', newline='\r\n')
for name, data in [('deleted-manifest.json', deleted), ('retained-original.json', retained),
('retained-embedded.json', added), ('modified-interface.json', modified), ('source-files.json', source_rows)]:
(args.out_dir / name).write_text(json.dumps(data, indent=2) + '\n')
if name in ['deleted-manifest.json', 'source-files.json']:
shutil.copy2(args.out_dir / name, tree / name)
modifications = tree / 'modifications'
modifications.mkdir()
for name in ['build.py', 'inputs.json', 'embedded-inputs.json', 'requirements.txt', 'clearance-and-modifications.json']:
shutil.copy2(HERE / name, modifications / name)
iso = pycdlib.PyCdlib()
iso.new(interchange_level=3, joliet=3, rock_ridge='1.09', vol_ident='GNUW2_BONUS_CL')
dirs = {Path('.'): ''}
for i, directory in enumerate(sorted((p for p in tree.rglob('*') if p.is_dir()), key=lambda p: (len(p.parts), str(p))), 1):
rel = directory.relative_to(tree)
ident = dirs[rel.parent] + '/D' + str(i).zfill(7)
dirs[rel] = ident
iso.add_directory(iso_path=ident, joliet_path='/' + rel.as_posix(), rr_name=directory.name)
output_inventory = []
for i, p in enumerate(sorted(p for p in tree.rglob('*') if p.is_file()), 1):
rel = p.relative_to(tree)
ident = dirs[rel.parent] + '/F' + str(i).zfill(7) + ';1'
iso.add_file(str(p), iso_path=ident, joliet_path='/' + rel.as_posix(), rr_name=p.name)
output_inventory.append({'path': '/' + rel.as_posix(), 'bytes': p.stat().st_size, 'sha256': sha(p)})
output = args.out_dir / 'GNUWinII-bonus-cleaned.iso'
iso.write(str(output))
iso.close()
verify = pycdlib.PyCdlib()
verify.open(str(output))
for row in output_inventory:
body = io.BytesIO()
verify.get_file_from_iso_fp(body, joliet_path=row['path'])
if hashlib.sha256(body.getvalue()).hexdigest() != row['sha256']:
raise ValueError('Readback failed: ' + row['path'])
verify.close()
(args.out_dir / 'output-inventory.json').write_text(json.dumps(output_inventory, indent=2) + '\n')
proof = {'created': datetime.now(timezone.utc).isoformat(), 'status': 'bytes verified; source/clearance peer review and guest gate pending',
'title': config['title'], 'original': config['original'], 'originalArchive': str(archived),
'output': {'file': str(output), 'bytes': output.stat().st_size, 'sha256': sha(output)},
'applications': sorted(apps), 'sourceArchives': len(source_rows), 'sourceBytes': sum(r['bytes'] for r in source_rows),
'allOutputFilesReadBack': len(output_inventory), 'originalDeletedFiles': len(deleted),
'nativeGuestTest': False, 'providerConfigured': False, 'shelfInsertEnabled': False,
'noWindowsGuestBytes': True, 'noRuntimeChange': True}
(args.out_dir / 'ready-artifact.json').write_text(json.dumps(proof, indent=2) + '\n')
print(json.dumps(proof, indent=2))
if __name__ == '__main__':
main()