#!/bin/bash
# Item 500: builds the ffmpeg + ffprobe that ship INSIDE Swale Cut.
#
# Why: customers don't have Homebrew's ffmpeg, and Homebrew's build includes
# GPL parts (x264/x265) that a closed-source paid app can't ship. This builds
# an LGPL-only ffmpeg for Apple Silicon with exactly what the app uses:
# VideoToolbox (hardware H.264/HEVC/ProRes encode + scale_vt), libass
# (burned-in subtitles, macOS CoreText fonts), FreeType/FriBidi/HarfBuzz
# (text shaping), Opus, LAME (MP3), libvpx (WebM) and dav1d (AV1 decoding). Everything is linked
# statically, so the result only depends on macOS itself.
#
# Run from the Swale Cut folder:   ./tools/build-ffmpeg-lgpl.sh
# Takes roughly 10-25 minutes. Needs Xcode (or its command-line tools) and:
#   brew install pkg-config nasm meson ninja cmake
# Output: src-tauri/binaries/ffmpeg-aarch64-apple-darwin,
#         src-tauri/binaries/ffprobe-aarch64-apple-darwin,
#         src-tauri/binaries/FFMPEG-BUILD.txt (licence + exact sources).
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
WORK="${SWALE_FFMPEG_WORK:-$HOME/Library/Caches/SwaleCut-ffmpeg-build}"
SRC="$WORK/src"
PREFIX="$WORK/prefix"
OUT="$ROOT/src-tauri/binaries"
LOG="$WORK/build.log"
MIN_MACOS="14.0"

FFMPEG_VERSION="7.1.1"
FREETYPE_VERSION="2.13.3"
FRIBIDI_VERSION="1.0.16"
HARFBUZZ_VERSION="10.1.0"
LIBASS_VERSION="0.17.3"
OPUS_VERSION="1.5.2"
LAME_VERSION="3.100"
LIBVPX_VERSION="1.14.1"
DAV1D_VERSION="1.5.0"

if [ "$(uname -s)" != "Darwin" ] || [ "$(uname -m)" != "arm64" ]; then
  echo "Run this on an Apple Silicon Mac."; exit 1
fi
missing=""
for tool in pkg-config nasm meson ninja cmake curl; do
  command -v "$tool" >/dev/null 2>&1 || missing="$missing $tool"
done
if [ -n "$missing" ]; then
  echo "Missing tools:$missing"
  echo "Install them with:  brew install pkg-config nasm meson ninja cmake"
  exit 1
fi

mkdir -p "$SRC" "$PREFIX" "$OUT"
: > "$LOG"
export MACOSX_DEPLOYMENT_TARGET="$MIN_MACOS"
export CFLAGS="-O2 -arch arm64 -mmacosx-version-min=$MIN_MACOS -I$PREFIX/include"
export CXXFLAGS="$CFLAGS"
export LDFLAGS="-arch arm64 -mmacosx-version-min=$MIN_MACOS -L$PREFIX/lib"
# Only our own static libraries - never Homebrew's (they'd make the result
# depend on /opt/homebrew, which customers don't have).
export PKG_CONFIG_LIBDIR="$PREFIX/lib/pkgconfig"
export PKG_CONFIG_PATH="$PREFIX/lib/pkgconfig"
JOBS="$(sysctl -n hw.ncpu)"

step() { echo; echo "==> $*"; echo "==> $*" >> "$LOG"; }

finish() {
  step "Checking the result"
  # (outputs captured first: piping into `grep -q` makes ffmpeg exit on a
  # closed pipe, which `set -o pipefail` reports as a failure)
  local buildconf filters encoders
  buildconf="$(./ffmpeg -hide_banner -buildconf 2>&1)"
  filters="$(./ffmpeg -hide_banner -filters 2>/dev/null)"
  encoders="$(./ffmpeg -hide_banner -encoders 2>/dev/null)"
  for bin in ffmpeg ffprobe; do
    local outside
    outside="$(otool -L "$bin" | tail -n +2 | grep -v -E "^[[:space:]]+(/usr/lib/|/System/Library/)" || true)"
    if [ -n "$outside" ]; then
      echo "$bin links to something outside macOS:"; otool -L "$bin"; exit 1
    fi
  done
  if grep -q -- "--enable-gpl" <<< "$buildconf"; then echo "GPL parts found - stopping."; exit 1; fi
  grep -qE "[[:space:]]ass[[:space:]]" <<< "$filters" || { echo "The ass (subtitles) filter is missing."; exit 1; }
  grep -qE "[[:space:]]scale_vt[[:space:]]" <<< "$filters" || { echo "The scale_vt (GPU scaling) filter is missing."; exit 1; }
  grep -q "h264_videotoolbox" <<< "$encoders" || { echo "The hardware H.264 encoder is missing."; exit 1; }

  cp ffmpeg "$OUT/ffmpeg-aarch64-apple-darwin"
  cp ffprobe "$OUT/ffprobe-aarch64-apple-darwin"
  chmod +x "$OUT"/ff*-aarch64-apple-darwin
  local vpx_note=""
  grep -q -- "--enable-libvpx" <<< "$buildconf" && vpx_note=", libvpx $LIBVPX_VERSION"
  {
    echo "Swale Cut bundled FFmpeg - built $(date -u +%Y-%m-%dT%H:%MZ) on macOS $(sw_vers -productVersion)"
    echo "Licence: LGPL v2.1 or later (no --enable-gpl, no --enable-nonfree)."
    echo "FFmpeg $FFMPEG_VERSION  https://ffmpeg.org/releases/ffmpeg-$FFMPEG_VERSION.tar.xz"
    echo "FreeType $FREETYPE_VERSION, FriBidi $FRIBIDI_VERSION, HarfBuzz $HARFBUZZ_VERSION, libass $LIBASS_VERSION, Opus $OPUS_VERSION, LAME $LAME_VERSION, dav1d $DAV1D_VERSION$vpx_note"
    echo "Built with tools/build-ffmpeg-lgpl.sh (unmodified upstream sources)."
    echo
    echo "configure:"
    echo "$buildconf"
  } > "$OUT/FFMPEG-BUILD.txt"

  echo
  echo "Done. Bundled ffmpeg is in src-tauri/binaries/:"
  ls -la "$OUT"
  ./ffmpeg -hide_banner -version | head -1
}


# `./tools/build-ffmpeg-lgpl.sh --finish` re-runs only the checks and copy,
# using the ffmpeg already built in the work folder.
if [ "${1:-}" = "--finish" ]; then
  [ -x "$SRC/ffmpeg/ffmpeg" ] || { echo "Nothing built yet - run the script without --finish."; exit 1; }
  cd "$SRC/ffmpeg"; finish; exit 0
fi
fetch() { # url file
  if [ ! -f "$SRC/$2" ]; then curl -fL --retry 3 -o "$SRC/$2.part" "$1" && mv "$SRC/$2.part" "$SRC/$2"; fi
}
unpack() { # file dir
  rm -rf "$SRC/$2"; mkdir -p "$SRC/$2"; tar -xf "$SRC/$1" -C "$SRC/$2" --strip-components 1
}
run() { "$@" >> "$LOG" 2>&1 || { echo "Failed: $* (last lines of $LOG below)"; tail -40 "$LOG"; exit 1; }; }
# A library already built into the prefix by an earlier run is kept.
have() { [ -f "$PREFIX/lib/$1" ] && echo "(already built - kept)"; }

step "FreeType $FREETYPE_VERSION"
if ! have pkgconfig/freetype2.pc; then
fetch "https://download.savannah.gnu.org/releases/freetype/freetype-$FREETYPE_VERSION.tar.xz" freetype.tar.xz
unpack freetype.tar.xz freetype
cd "$SRC/freetype"
run ./configure --prefix="$PREFIX" --enable-static --disable-shared --with-harfbuzz=no --with-png=no --with-bzip2=no --with-brotli=no --with-zlib=no
run make -j"$JOBS"; run make install
fi

step "FriBidi $FRIBIDI_VERSION"
if ! have pkgconfig/fribidi.pc; then
fetch "https://github.com/fribidi/fribidi/releases/download/v$FRIBIDI_VERSION/fribidi-$FRIBIDI_VERSION.tar.xz" fribidi.tar.xz
unpack fribidi.tar.xz fribidi
cd "$SRC/fribidi"
run meson setup build --prefix="$PREFIX" --libdir=lib --buildtype=release --default-library=static -Ddocs=false -Dtests=false -Dbin=false
run ninja -C build install
fi

step "HarfBuzz $HARFBUZZ_VERSION"
if ! have pkgconfig/harfbuzz.pc; then
fetch "https://github.com/harfbuzz/harfbuzz/releases/download/$HARFBUZZ_VERSION/harfbuzz-$HARFBUZZ_VERSION.tar.xz" harfbuzz.tar.xz
unpack harfbuzz.tar.xz harfbuzz
cd "$SRC/harfbuzz"
run meson setup build --prefix="$PREFIX" --libdir=lib --buildtype=release --default-library=static -Dfreetype=enabled -Dglib=disabled -Dgobject=disabled -Dcairo=disabled -Dicu=disabled -Dtests=disabled -Ddocs=disabled
run ninja -C build install
fi

step "libass $LIBASS_VERSION (CoreText fonts)"
if ! have pkgconfig/libass.pc; then
fetch "https://github.com/libass/libass/releases/download/$LIBASS_VERSION/libass-$LIBASS_VERSION.tar.xz" libass.tar.xz
unpack libass.tar.xz libass
cd "$SRC/libass"
run ./configure --prefix="$PREFIX" --enable-static --disable-shared --disable-fontconfig --enable-coretext --disable-require-system-font-provider
run make -j"$JOBS"; run make install
fi

step "Opus $OPUS_VERSION"
if ! have pkgconfig/opus.pc; then
fetch "https://downloads.xiph.org/releases/opus/opus-$OPUS_VERSION.tar.gz" opus.tar.gz
unpack opus.tar.gz opus
cd "$SRC/opus"
run ./configure --prefix="$PREFIX" --enable-static --disable-shared --disable-doc --disable-extra-programs
run make -j"$JOBS"; run make install
fi

step "LAME $LAME_VERSION"
if ! have libmp3lame.a; then
fetch "https://downloads.sourceforge.net/project/lame/lame/$LAME_VERSION/lame-$LAME_VERSION.tar.gz" lame.tar.gz
unpack lame.tar.gz lame
cd "$SRC/lame"
run ./configure --prefix="$PREFIX" --enable-static --disable-shared --disable-frontend --disable-gtktest
run make -j"$JOBS"; run make install
fi

ENABLE_VPX="--enable-libvpx"
step "libvpx $LIBVPX_VERSION (WebM export)"
if have pkgconfig/vpx.pc; then :; else
fetch "https://github.com/webmproject/libvpx/archive/refs/tags/v$LIBVPX_VERSION.tar.gz" libvpx.tar.gz
unpack libvpx.tar.gz libvpx
cd "$SRC/libvpx"
if ./configure --prefix="$PREFIX" --target=arm64-darwin22-gcc --enable-static --disable-shared --disable-examples --disable-tools --disable-docs --disable-unit-tests --enable-vp9-highbitdepth >> "$LOG" 2>&1 \
   && make -j"$JOBS" >> "$LOG" 2>&1 && make install >> "$LOG" 2>&1; then
  echo "libvpx built."
else
  echo "libvpx didn't build - continuing without WebM (VP9) export."
  ENABLE_VPX=""
fi
fi

DAV1D_VERSION_LINE=""
step "dav1d $DAV1D_VERSION (AV1 decoding)"
if ! have pkgconfig/dav1d.pc; then
fetch "https://code.videolan.org/videolan/dav1d/-/archive/$DAV1D_VERSION/dav1d-$DAV1D_VERSION.tar.bz2" dav1d.tar.bz2
unpack dav1d.tar.bz2 dav1d
cd "$SRC/dav1d"
run meson setup build --prefix="$PREFIX" --libdir=lib --buildtype=release --default-library=static -Denable_tools=false -Denable_tests=false
run ninja -C build install
fi

step "FFmpeg $FFMPEG_VERSION (LGPL)"
fetch "https://ffmpeg.org/releases/ffmpeg-$FFMPEG_VERSION.tar.xz" ffmpeg.tar.xz
unpack ffmpeg.tar.xz ffmpeg
cd "$SRC/ffmpeg"
CONFIGURE_FLAGS=(
  --prefix="$PREFIX"
  --pkg-config-flags=--static
  --extra-cflags="-I$PREFIX/include -mmacosx-version-min=$MIN_MACOS"
  --extra-ldflags="-L$PREFIX/lib -mmacosx-version-min=$MIN_MACOS"
  --disable-autodetect
  --disable-debug --disable-doc --disable-ffplay
  --disable-shared --enable-static
  --enable-videotoolbox --enable-audiotoolbox
  --enable-zlib --enable-bzlib --enable-iconv
  --enable-libfreetype --enable-libfribidi --enable-libharfbuzz --enable-libass
  --enable-libopus --enable-libmp3lame --enable-libdav1d
)
[ -n "$ENABLE_VPX" ] && CONFIGURE_FLAGS+=("$ENABLE_VPX")
run ./configure "${CONFIGURE_FLAGS[@]}"
run make -j"$JOBS"


finish
