#!/usr/bin/env bash
# Builds the LGPL ffmpeg + ffprobe the Mac app embeds: universal (arm64 + x86_64),
# macOS 13+, VideoToolbox/AudioToolbox encoders.
#
#   scripts/lib/ffmpeg/build-macos.sh [out-dir]    (default build/ffmpeg/darwin)
#
# Needs Xcode command line tools and nasm (brew install nasm) for the x86_64 half.
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
ROOT="$(cd "$HERE/../../.." && pwd)"
source "$HERE/config.sh"
source "$HERE/fetch.sh"
OUT="${1:-$ROOT/build/ffmpeg/darwin}"
command -v nasm >/dev/null || { echo "nasm not found: brew install nasm" >&2; exit 1; }
WORK="$(mktemp -d "${TMPDIR:-/tmp}/rp-ffmpeg-XXXXXX")"
trap 'rm -rf "$WORK"' EXIT
fetch_ffmpeg "$WORK"
SRC="$WORK/ffmpeg-$FFMPEG_VERSION"
JOBS="$(sysctl -n hw.ncpu)"

for arch in arm64 x86_64; do
  b="$WORK/build-$arch"
  mkdir -p "$b"
  flags="-arch $arch -mmacosx-version-min=13.0"
  extra=()
  [[ "$arch" != "$(uname -m)" ]] && extra+=(--enable-cross-compile)
  (cd "$b" && "$SRC/configure" --prefix="$b/out" --arch="$arch" --target-os=darwin --cc=clang \
    --extra-cflags="$flags" --extra-ldflags="$flags" ${extra[@]+"${extra[@]}"} \
    "${FFMPEG_COMMON[@]}" \
    --enable-videotoolbox --enable-audiotoolbox \
    --enable-encoder=h264_videotoolbox,hevc_videotoolbox,aac_at \
    >"$b/configure.log" 2>&1) || { tail -30 "$b/configure.log" >&2; exit 1; }
  grep -q "^License: LGPL" "$b/configure.log" || grep -q "License: LGPL" "$b/ffbuild/config.log" 2>/dev/null ||
    (cd "$b" && grep -q 'CONFIG_GPL 0' config.h) || { echo "not an LGPL configuration" >&2; exit 1; }
  make -C "$b" -j"$JOBS" ffmpeg ffprobe >"$b/make.log" 2>&1 || { tail -30 "$b/make.log" >&2; exit 1; }
done

mkdir -p "$OUT"
for tool in ffmpeg ffprobe; do
  lipo -create "$WORK/build-arm64/$tool" "$WORK/build-x86_64/$tool" -output "$OUT/$tool"
  strip -x "$OUT/$tool"
done
"$OUT/ffmpeg" -hide_banner -buildconf | grep -q -- --enable-gpl && { echo "GPL build!" >&2; exit 1; }
"$OUT/ffmpeg" -hide_banner -L | grep -q "Lesser General Public" || { echo "ffmpeg -L does not say LGPL" >&2; exit 1; }
echo "$FFMPEG_VERSION" > "$OUT/VERSION"
ls -la "$OUT"
