#!/bin/bash
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"
SOURCE="$ROOT/vendor/sources/ffmpeg-9.0.2.tar.xz"
BUILD="$ROOT/.build/media/ffmpeg-9.0.2"
MEDIA="$ROOT/vendor/media"
RESUME="${1:-}"
MEDIA_JOBS="${SPOKEN_MEDIA_JOBS:-2}"
MEDIA_LOAD="${SPOKEN_MEDIA_LOAD_LIMIT:-8}"
case "$MEDIA_JOBS:$MEDIA_LOAD" in *[!0-9:]*) echo 'Build job/load limits must be positive integers.' >&2; exit 1;; esac
test "$MEDIA_JOBS" -ge 1; test "$MEDIA_LOAD" -ge 1
if [ "$(uname -m)" != arm64 ]; then echo 'This build recipe currently targets Apple Silicon only.' >&2; exit 1; fi
python3 - <<'PY'
from pathlib import Path
import hashlib,json
p=Path('vendor/sources/ffmpeg-9.0.2.tar.xz')
v=json.loads(Path('vendor/sources/verification.json').read_text())
assert v['signatureVerified'] and hashlib.sha256(p.read_bytes()).hexdigest()==v['sourceSHA256']
assert not Path('vendor/media/manifest.json').exists(), 'Preserve existing tools; build a new candidate directory for a rebuild'
PY
mkdir -p "$ROOT/.build/media" "$MEDIA/bin" "$MEDIA/licenses"
if [ -e "$BUILD" ] && [ "$RESUME" != --resume ]; then
  echo 'Partial build retained. Inspect it and use --resume to continue the same configuration.' >&2; exit 1
fi
if [ "$RESUME" = --resume ]; then
  test -f "$BUILD/config.h"
  python3 - "$BUILD" <<'PY'
from pathlib import Path
import sys
b=Path(sys.argv[1]);assert (b/'VERSION').read_text().strip()=='9.0.2'
c=(b/'config.h').read_text()
for f in ['CONFIG_GPL','CONFIG_VERSION3','CONFIG_NONFREE','CONFIG_NETWORK']:
 assert '#define '+f+' 0' in c,f
PY
  cd "$BUILD"
else
  tar -xf "$SOURCE" -C "$ROOT/.build/media"
  cd "$BUILD"
# In-source build avoids make's unquoted installation-prefix paths. We do not
# install into /usr/local or Homebrew. All non-system third-party autodetection
# is disabled; keep the native codec/filter set instead of narrowing formats.
./configure --prefix=/ffmpeg-source-build --cc=clang --arch=arm64 --target-os=darwin \
  --pkg-config=/usr/bin/false --extra-cflags=-mmacosx-version-min=14.0 --extra-ldflags=-mmacosx-version-min=14.0 \
  --disable-autodetect --disable-network --disable-doc --disable-debug \
  --disable-shared --enable-static --enable-small --disable-gpl --disable-version3 --disable-nonfree \
  --disable-ffplay --disable-avdevice --enable-ffmpeg --enable-ffprobe \
  --enable-pthreads --enable-videotoolbox --enable-audiotoolbox --enable-zlib
fi
make -j"$MEDIA_JOBS" -l"$MEDIA_LOAD" ffmpeg ffprobe
cp ffmpeg ffprobe "$MEDIA/bin/"
/usr/bin/strip -x "$MEDIA/bin/ffmpeg" "$MEDIA/bin/ffprobe"
for name in ffmpeg ffprobe; do
  codesign --force --sign - --identifier "local.spokencut.$name" "$MEDIA/bin/$name"
done
cp COPYING.LGPLv2.1 "$MEDIA/licenses/FFmpeg-LGPL-2.1.txt"
cp LICENSE.md "$MEDIA/licenses/FFmpeg-LICENSE.md"
cp ffbuild/config.log "$MEDIA/ffmpeg-config.log"
cp config.h "$MEDIA/ffmpeg-config.h"
"$MEDIA/bin/ffmpeg" -version > "$MEDIA/ffmpeg-version.txt"
"$MEDIA/bin/ffmpeg" -L > "$MEDIA/ffmpeg-license.txt" 2>&1
cd "$ROOT"
python3 - <<'PY'
from pathlib import Path
from datetime import datetime,timezone
import hashlib,json,subprocess
r=Path('.');m=r/'vendor/media'
h=lambda p:hashlib.sha256(p.read_bytes()).hexdigest()
config=(m/'ffmpeg-config.h').read_text()
for flag in ['CONFIG_GPL','CONFIG_VERSION3','CONFIG_NONFREE','CONFIG_NETWORK']:
 assert '#define '+flag+' 0' in config,flag
for name in ['ffmpeg','ffprobe']:
 text=subprocess.check_output(['otool','-L',str(m/'bin'/name)],text=True)
 dependencies=[line.strip().split(' (')[0] for line in text.splitlines()[1:]]
 assert all(d.startswith('/usr/lib/') or d.startswith('/System/Library/') for d in dependencies),dependencies
 (m/(name+'-dependencies.txt')).write_text(text)
 assert 'arm64' in subprocess.check_output(['file',str(m/'bin'/name)],text=True)
files=[p for p in m.rglob('*') if p.is_file()]
report=dict(recordedAt=datetime.now(timezone.utc).isoformat(),version='9.0.2',architecture='arm64',
 minOSDeclared='14.0',physicalMacOS14Tested=False,license='LGPL-2.1-or-later',
 sourceSHA256=h(r/'vendor/sources/ffmpeg-9.0.2.tar.xz'),recipeSHA256=h(r/'scripts/build-media-tools.sh'),
 gplEnabled=False,nonfreeEnabled=False,externalLibraries='System frameworks and /usr/lib only; no packaged external third-party codec libraries',
 files={str(p.relative_to(m)):h(p) for p in files})
(m/'manifest.json').write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps({k:report[k] for k in ['version','architecture','license','gplEnabled']},indent=2))
PY
