#!/usr/bin/env bash
#
# Build a minimal, static, LGPL FFmpeg for ChopShop's optional
# extended-format-support download.
#
#   Output:  ChopShop/build/ffmpeg/ffmpeg
#   License: LGPL v3 only (no GPL components, no libx264, no nonfree)
#   Purpose: decode MKV / OGG / WebM / FLAC on import and remux to a
#            .mov / .m4a container that AVFoundation can read. Re-
#            encoding (when needed) uses Apple's VideoToolbox and
#            AudioToolbox encoders so we don't pull in libx264 etc.
#
# Usage:
#   bash scripts/build-ffmpeg.sh                  # arm64-only (fast smoke)
#   ARCHS="arm64 x86_64" bash scripts/build-ffmpeg.sh   # universal
#
# After build:
#   build/ffmpeg/ffmpeg  -- the binary to sign + notarize + host

set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
BUILD="$ROOT/build"
SRC="$BUILD/ffmpeg-src"
OUT="$BUILD/ffmpeg"
FFMPEG_TAG="${FFMPEG_TAG:-n7.1.2}"
ARCHS="${ARCHS:-arm64}"
MIN_MACOS="${MIN_MACOS:-12.0}"

mkdir -p "$BUILD" "$OUT"

# ---- source ----
if [[ ! -d "$SRC/.git" ]]; then
  echo "==> Cloning FFmpeg $FFMPEG_TAG"
  git clone --depth 1 --branch "$FFMPEG_TAG" \
    https://github.com/FFmpeg/FFmpeg.git "$SRC"
fi

# ---- configure flags ----
# Start from --disable-everything and opt in only what we use, to keep
# the binary small (~10-15 MB instead of ~80 MB).
COMMON_CFG=(
  --disable-everything
  --disable-doc --disable-htmlpages --disable-manpages
  --disable-podpages --disable-txtpages
  --disable-debug
  --disable-network
  --disable-shared --enable-static
  --enable-pthreads
  --enable-version3                    # LGPL v3 (allows audiotoolbox/aac_at)
  --disable-gpl --disable-nonfree

  --disable-programs --enable-ffmpeg   # we only need the ffmpeg CLI
  --enable-avcodec --enable-avformat --enable-avutil
  --enable-swresample --enable-swscale

  # Containers we read
  --enable-demuxer=matroska,ogg,flac,wav,aiff,mp3,mov,aac,m4a

  # Parsers
  --enable-parser=vp8,vp9,vorbis,opus,flac,h264,hevc,aac,mpegaudio,av1

  # Video decoders
  --enable-decoder=vp8,vp9,theora,av1,h264,hevc,mpeg4,mjpeg,prores

  # Audio decoders
  --enable-decoder=vorbis,opus,flac,mp3,aac,alac
  --enable-decoder=pcm_s16le,pcm_s24le,pcm_s32le,pcm_f32le

  # Containers we write (AVFoundation-friendly)
  --enable-muxer=mov,ipod,mp4

  # Apple-native encoders (no GPL pull-ins)
  --enable-videotoolbox --enable-audiotoolbox
  --enable-encoder=h264_videotoolbox,hevc_videotoolbox,aac_at,alac_at,pcm_s16le

  # Protocols
  --enable-protocol=file,pipe

  # Bitstream filters for passthrough remux
  --enable-bsf=h264_mp4toannexb,hevc_mp4toannexb,vp9_superframe
  --enable-bsf=vp9_metadata,av1_metadata,extract_extradata,aac_adtstoasc

  # Minimal filters
  --enable-filter=aresample,scale,format,aformat,anull,null,copy
)

build_arch() {
  local arch="$1"
  local prefix="$BUILD/install-$arch"
  echo
  echo "==================================================================="
  echo "==> Building FFmpeg for $arch"
  echo "==================================================================="
  rm -rf "$prefix"
  mkdir -p "$prefix"

  pushd "$SRC" >/dev/null
  make distclean >/dev/null 2>&1 || true

  local cflags="-arch $arch -mmacosx-version-min=$MIN_MACOS -Os"
  local ldflags="-arch $arch -mmacosx-version-min=$MIN_MACOS"
  local cross=()
  if [[ "$arch" != "$(uname -m)" ]]; then
    cross+=(--enable-cross-compile --arch="$arch" --target-os=darwin)
  fi
  # nasm is x86-only; arm64 uses clang's built-in assembler.
  local asm=()
  if [[ "$arch" == "arm64" ]]; then
    asm+=(--disable-x86asm)
  fi

  ./configure \
    --prefix="$prefix" \
    --extra-cflags="$cflags" \
    --extra-ldflags="$ldflags" \
    ${cross[@]+"${cross[@]}"} \
    ${asm[@]+"${asm[@]}"} \
    "${COMMON_CFG[@]}"

  make -j"$(sysctl -n hw.ncpu)"
  make install
  popd >/dev/null
}

for a in $ARCHS; do
  build_arch "$a"
done

# ---- lipo ----
bins=()
for a in $ARCHS; do bins+=("$BUILD/install-$a/bin/ffmpeg"); done

if [[ ${#bins[@]} -gt 1 ]]; then
  lipo -create "${bins[@]}" -output "$OUT/ffmpeg"
else
  cp "${bins[0]}" "$OUT/ffmpeg"
fi
strip -S -x "$OUT/ffmpeg" || true

echo
echo "==> Done."
file "$OUT/ffmpeg"
ls -lh "$OUT/ffmpeg"
"$OUT/ffmpeg" -version | head -3
