#!/usr/bin/env python3
"""Install our source-built PyAV and relocate its FFmpeg references."""
import os
import shutil
import subprocess
import zipfile
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
BUILD = ROOT / 'build/legal-runtime'
SITE = BUILD / 'Runtime/site-packages'
backup = BUILD / 'original-av-module'
if backup.exists():
    raise SystemExit('Previous build exists; do not overwrite it.')
(SITE / 'av').rename(backup)
wheel = next((BUILD / 'wheels').glob('av-*.whl'))
with zipfile.ZipFile(wheel) as archive:
    for member in archive.infolist():
        path = Path(member.filename)
        if path.is_absolute() or '..' in path.parts:
            raise ValueError(member.filename)
        archive.extract(member, SITE)
shutil.copytree(backup / '.dylibs', SITE / 'av/.dylibs', symlinks=True)
for path in (SITE / 'av').rglob('*.so'):
    dependencies = subprocess.check_output(['otool', '-L', str(path)], text=True).splitlines()[1:]
    for line in dependencies:
        old = line.strip().split(' (')[0]
        target = SITE / 'av/.dylibs' / Path(old).name
        if target.is_file():
            new = '@loader_path/' + os.path.relpath(target, path.parent)
            subprocess.run(['install_name_tool', '-change', old, new, str(path)], check=True)
    subprocess.run(['codesign', '--force', '--sign', '-', str(path)], check=True)
print('Installed PyAV built against the replacement LGPL FFmpeg.')
