#!/bin/bash
# Builds an LGPL-only ffmpeg (no GPL or non-free parts: no x264/x265) with Apple VideoToolbox, AudioToolbox,
# freetype (drawtext) and TLS (rtmps), as a self-contained static binary at vendor/ffmpeg/ffmpeg.
# Usage: scripts/build-ffmpeg.sh [version]
set -euo pipefail
VER="${1:-6.0.1}"
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
WORK="${FFMPEG_WORK:-$ROOT/vendor/ffmpeg-build}"
OUT="$ROOT/vendor/ffmpeg"
mkdir -p "$WORK" "$OUT"
cd "$WORK"
[ -f "ffmpeg-$VER.tar.xz" ] || curl -fL -o "ffmpeg-$VER.tar.xz" "https://ffmpeg.org/releases/ffmpeg-$VER.tar.xz"
rm -rf "ffmpeg-$VER" && tar xf "ffmpeg-$VER.tar.xz"

# Static-only copies of the dependency libraries, so the linker cannot pick dylibs.
STATIC="$WORK/static"; rm -rf "$STATIC"; mkdir -p "$STATIC/lib" "$STATIC/include"
BREW="$(brew --prefix)"
for lib in freetype libpng16 brotlidec brotlicommon ssl crypto; do
  f="$(ls "$BREW"/opt/*/lib/lib${lib#lib}.a "$BREW"/lib/lib${lib#lib}.a 2>/dev/null | head -1 || true)"
  [ -z "$f" ] && echo "WARNING: static lib${lib#lib}.a not found"
  [ -n "$f" ] && ln -sf "$f" "$STATIC/lib/$(basename "$f")"
done

# pkg-config is not installed here, so answer the one question configure asks.
cat > "$WORK/pkg-config-shim" <<SHIM
#!/bin/bash
case "\$*" in
  *--exists*|*--modversion*) exit 0 ;;
  *--cflags*) echo "-I$BREW/include/freetype2 -I$BREW/include" ;;
  *--libs*) echo "-L$STATIC/lib -lfreetype -lpng16 -lbrotlidec -lbrotlicommon -lbz2 -lz" ;;
esac
SHIM
chmod +x "$WORK/pkg-config-shim"

cd "ffmpeg-$VER"
# OpenSSL 3 (Apache-2.0) linked statically; --enable-version3 keeps the build LGPLv3.
TLS="--enable-openssl --enable-version3 --extra-cflags=-I$BREW/opt/openssl@3/include --extra-ldflags=-L$STATIC/lib"
./configure --prefix="$OUT/prefix" --pkg-config="$WORK/pkg-config-shim" --cc=clang \
  --disable-gpl --disable-nonfree --disable-doc --disable-ffplay --disable-ffprobe --disable-debug \
  --disable-shared --enable-static --enable-pthreads --enable-zlib \
  --enable-videotoolbox --enable-audiotoolbox --enable-libfreetype $TLS \
  --disable-autodetect --enable-avfoundation --enable-coreimage --enable-appkit 2>&1 | tail -15
make -j"$(sysctl -n hw.ncpu)" 2>&1 | tail -5
cp ffmpeg "$OUT/ffmpeg"
strip -x "$OUT/ffmpeg" 2>/dev/null || true
echo "built: $OUT/ffmpeg"; "$OUT/ffmpeg" -hide_banner -version | head -3
