#!/usr/bin/env python3
"""Use the pinned Homebrew bottle's GCC runtime, preserving a relocation record."""
import json
import shutil
import subprocess
from pathlib import Path
from collect_licenses import sha256

ROOT = Path(__file__).resolve().parents[1]
BUILD = ROOT / 'build/legal-runtime'
LEGAL = ROOT / 'public/downloads/timbrai/legal'
PROVENANCE = LEGAL / 'build-scripts/gcc13/provenance.json'
provenance = json.loads(PROVENANCE.read_text())
assert sha256(BUILD / 'gcc13-arm64-sonoma.tar.gz') == provenance['bottle']['sha256']
assert sha256(LEGAL / 'sources/gcc-13.4.0.tar.xz') == provenance['source']['checksum']
patch = provenance['bottle_source_patch']
assert sha256(PROVENANCE.parent / patch['file']) == patch['sha256']
target = BUILD / 'Runtime/site-packages/scipy/.dylibs'
backup = BUILD / 'original-scipy-gcc-libraries'
if backup.exists():
    raise SystemExit('Backup exists; preserve the prior build before repeating.')
backup.mkdir()
names = ['libgfortran.5.dylib', 'libgcc_s.1.1.dylib', 'libquadmath.0.dylib']
records = []
for name in names:
    source = BUILD / 'gcc13-bottle' / name
    (target / name).rename(backup / name)
    shutil.copy2(source, target / name)
    path = target / name
    subprocess.run(['install_name_tool', '-id', '@loader_path/' + name, str(path)], check=True)
    changes = []
    for line in subprocess.check_output(['otool', '-L', str(path)], text=True).splitlines()[1:]:
        old = line.strip().split(' (')[0]
        if Path(old).name in names and not old.startswith('@loader_path/'):
            new = '@loader_path/' + Path(old).name
            subprocess.run(['install_name_tool', '-change', old, new, str(path)], check=True)
            changes.append(dict(old=old, new=new))
    subprocess.run(['codesign', '--force', '--sign', '-', str(path)], check=True)
    records.append(dict(file=name, source_sha256=sha256(source), installed_sha256=sha256(path),
                        changes=changes, code_changes='None; Mach-O paths and ad-hoc signature only.'))
(PROVENANCE.parent / 'installed-libraries.json').write_text(json.dumps(records, indent=2) + '\n')
print('Installed three GCC libraries from the documented bottle.')
