#!/usr/bin/env python3
"""Link lameenc dynamically to our LAME build in the candidate runtime only."""
import json
import shutil
import subprocess
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
BUILD = ROOT / 'build/legal-runtime'
RUNTIME = BUILD / 'Runtime'
SITE = RUNTIME / 'site-packages'
SOURCE = next(BUILD.glob('lameenc-*'))
LIBRARY = BUILD / 'lame-install/lib/libmp3lame.0.dylib'
DESTINATION = SITE / 'lameenc-libs'
OLD = next(SITE.glob('lameenc*.so'))
BACKUP = BUILD / ('original-' + OLD.name)
if BACKUP.exists():
    raise SystemExit('A previous build exists; preserve it before rebuilding.')
DESTINATION.mkdir(exist_ok=True)
shutil.copy2(LIBRARY.resolve(), DESTINATION / LIBRARY.name)
subprocess.run(['install_name_tool', '-id', '@loader_path/lameenc-libs/' + LIBRARY.name,
                str(DESTINATION / LIBRARY.name)], check=True)
subprocess.run(['codesign', '--force', '--sign', '-', str(DESTINATION / LIBRARY.name)], check=True)
output = BUILD / OLD.name
command = ['xcrun', 'clang', '-arch', 'arm64', '-mmacosx-version-min=14.0', '-O2', '-fPIC',
           '-bundle', '-undefined', 'dynamic_lookup', '-I' + str(RUNTIME / 'include/python3.11'),
           '-I' + str(BUILD / 'lame-4.0/include'), str(SOURCE / 'lameenc.c'),
           str(DESTINATION / LIBRARY.name), '-o', str(output)]
subprocess.run(command, check=True)
subprocess.run(['codesign', '--force', '--sign', '-', str(output)], check=True)
OLD.rename(BACKUP)
shutil.copy2(output, OLD)
(BUILD / 'lame-link-command.json').write_text(json.dumps(command, indent=2) + '\n')
print('lameenc now links to a separate replaceable libmp3lame.0.dylib.')
