#!/usr/bin/env bash
#
# Baut ffmpeg und ffprobe als statische LGPL-Binaries (nur Apple Silicon, macOS 15+)
# für die Einbettung in die App (Mac App Store).
#
# Enthaltene Encoder: h264_videotoolbox, hevc_videotoolbox, libvpx_vp9, libopus, aac
# Lizenz:             LGPL v2.1+ (kein --enable-gpl, kein --enable-nonfree, kein x264/x265)
#
# Aufruf:  tools/build-ffmpeg.sh
# Ergebnis: tools/build/dist/ffmpeg, tools/build/dist/ffprobe, tools/build/dist/LIZENZEN.txt
#
# Voraussetzungen: Xcode Command Line Tools, pkg-config (brew install pkgconf)
#
set -euo pipefail

# --- Versionen und Prüfsummen ---
# Die SHA-256-Werte wurden beim ersten Download selbst berechnet (Trust-on-first-use) und
# nicht mit den veröffentlichten Werten der Projekte abgeglichen. Bei Versionswechsel neu ermitteln.
FFMPEG_VERSION="9.0.2"
FFMPEG_URL="https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz"
FFMPEG_SHA256="8c3850283eb25fa026482078a04051e0be17347b09ef81a0849bec15a96e002e"

LIBVPX_VERSION="1.17.0"
LIBVPX_URL="https://github.com/webmproject/libvpx/archive/refs/tags/v${LIBVPX_VERSION}.tar.gz"
LIBVPX_SHA256="1020f184046187baa2985dbde38e0691f49c44088bca7a1842b0236c6081dc0a"

OPUS_VERSION="1.6.1"
OPUS_URL="https://downloads.xiph.org/releases/opus/opus-${OPUS_VERSION}.tar.gz"
OPUS_SHA256="6ffcb593207be92584df15b32466ed64bbec99109f007c82205f0194572411a1"

MIN_MACOS="15.0"
# libvpx kennt nur Darwin-Targets: macOS 15 = Darwin 24
LIBVPX_TARGET="arm64-darwin24-gcc"

# --- Pfade ---
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BUILD="$ROOT/build"
DOWNLOADS="$BUILD/downloads"
SRC="$BUILD/src"
PREFIX="$BUILD/prefix"
DIST="$BUILD/dist"
JOBS="$(sysctl -n hw.ncpu)"

export MACOSX_DEPLOYMENT_TARGET="$MIN_MACOS"
export PKG_CONFIG_PATH="$PREFIX/lib/pkgconfig"
# Nur die eigenen Bibliotheken verwenden, nichts aus Homebrew
export PKG_CONFIG_LIBDIR="$PREFIX/lib/pkgconfig"
CFLAGS_COMMON="-arch arm64 -mmacosx-version-min=${MIN_MACOS} -O2"

die() { echo "FEHLER: $*" >&2; exit 1; }

[[ "$(uname -m)" == "arm64" ]] || die "Dieses Skript baut nur für Apple Silicon (arm64)."
command -v pkg-config >/dev/null || die "pkg-config fehlt. Installieren mit: brew install pkgconf"
command -v clang >/dev/null || die "clang fehlt. Installieren mit: xcode-select --install"

mkdir -p "$DOWNLOADS" "$SRC" "$PREFIX" "$DIST"

fetch() { # name url sha256 dateiname
  local name="$1" url="$2" sha="$3" file="$DOWNLOADS/$4"
  if [[ ! -f "$file" ]]; then
    echo "==> Lade $name"
    curl -fsSL --retry 3 --connect-timeout 20 -o "$file.part" "$url"
    mv "$file.part" "$file"
  fi
  local actual
  actual="$(shasum -a 256 "$file" | awk '{print $1}')"
  [[ "$actual" == "$sha" ]] || { rm -f "$file"; die "Prüfsumme für $name stimmt nicht (erwartet $sha, erhalten $actual). Datei gelöscht."; }
}

extract() { # dateiname zielordner
  rm -rf "$SRC/$2"
  mkdir -p "$SRC/$2"
  tar -xf "$DOWNLOADS/$1" -C "$SRC/$2" --strip-components=1
}

fetch "ffmpeg ${FFMPEG_VERSION}" "$FFMPEG_URL" "$FFMPEG_SHA256" "ffmpeg-${FFMPEG_VERSION}.tar.xz"
fetch "libvpx ${LIBVPX_VERSION}" "$LIBVPX_URL" "$LIBVPX_SHA256" "libvpx-${LIBVPX_VERSION}.tar.gz"
fetch "opus ${OPUS_VERSION}"     "$OPUS_URL"   "$OPUS_SHA256"   "opus-${OPUS_VERSION}.tar.gz"

# --- Opus ---
echo "==> Baue opus"
extract "opus-${OPUS_VERSION}.tar.gz" opus
( cd "$SRC/opus"
  CFLAGS="$CFLAGS_COMMON" ./configure --prefix="$PREFIX" \
    --disable-shared --enable-static --disable-doc --disable-extra-programs
  make -j"$JOBS" && make install )

# --- libvpx (VP9) ---
echo "==> Baue libvpx"
extract "libvpx-${LIBVPX_VERSION}.tar.gz" libvpx
( cd "$SRC/libvpx"
  ./configure --prefix="$PREFIX" --target="$LIBVPX_TARGET" \
    --enable-vp8 --enable-vp9 --enable-pic --enable-runtime-cpu-detect \
    --disable-shared --enable-static \
    --disable-examples --disable-tools --disable-docs --disable-unit-tests
  make -j"$JOBS" && make install )

# --- ffmpeg ---
echo "==> Baue ffmpeg ${FFMPEG_VERSION} (LGPL)"
extract "ffmpeg-${FFMPEG_VERSION}.tar.xz" ffmpeg
( cd "$SRC/ffmpeg"
  # --disable-autodetect: keine Bibliotheken aus Homebrew einbinden
  # Encoder nur die benötigten, Decoder/Demuxer/Filter bleiben vollständig (beliebige Eingabedateien)
  ./configure \
    --prefix="$PREFIX/ffmpeg" \
    --arch=arm64 --enable-neon \
    --cc=clang \
    --extra-cflags="$CFLAGS_COMMON -I$PREFIX/include" \
    --extra-ldflags="-arch arm64 -mmacosx-version-min=${MIN_MACOS} -L$PREFIX/lib" \
    --extra-libs="-liconv" \
    --enable-static --disable-shared \
    --disable-gpl --disable-nonfree --disable-autodetect \
    --disable-debug --disable-doc --disable-ffplay \
    --enable-ffmpeg --enable-ffprobe \
    --enable-videotoolbox --enable-audiotoolbox \
    --enable-zlib --enable-bzlib --enable-iconv \
    --enable-libvpx --enable-libopus \
    --disable-encoders \
    --enable-encoder=h264_videotoolbox,hevc_videotoolbox,libvpx_vp9,libopus,aac
  make -j"$JOBS"
  make install )

cp "$PREFIX/ffmpeg/bin/ffmpeg"  "$DIST/ffmpeg"
cp "$PREFIX/ffmpeg/bin/ffprobe" "$DIST/ffprobe"
strip -x "$DIST/ffmpeg" "$DIST/ffprobe"

cat > "$DIST/LIZENZEN.txt" <<EOF
Diese Binaries enthalten:
- FFmpeg ${FFMPEG_VERSION}  (LGPL v2.1 oder neuer)  https://ffmpeg.org  Quelle: ${FFMPEG_URL}
- libvpx ${LIBVPX_VERSION}  (BSD 3-Clause)          https://www.webmproject.org  Quelle: ${LIBVPX_URL}
- Opus ${OPUS_VERSION}      (BSD 3-Clause)          https://opus-codec.org  Quelle: ${OPUS_URL}

Build: tools/build-ffmpeg.sh (ohne --enable-gpl und ohne --enable-nonfree).
EOF

# --- Prüfungen ---
echo "==> Prüfe Ergebnis"
fail=0
cfg="$("$DIST/ffmpeg" -version | grep '^configuration:')"
if grep -qE -- '--enable-(gpl|nonfree|version3)' <<<"$cfg"; then echo "FEHLER: GPL/nonfree in der Konfiguration: $cfg"; fail=1; fi
for bin in ffmpeg ffprobe; do
  echo "--- otool -L $bin"
  otool -L "$DIST/$bin" | tail -n +2
  if otool -L "$DIST/$bin" | tail -n +2 | grep -vE '^\s+(/usr/lib/|/System/Library/)' | grep -q .; then
    echo "FEHLER: $bin hängt von Bibliotheken außerhalb des Systems ab"; fail=1
  fi
  lipo -archs "$DIST/$bin" | grep -qx arm64 || { echo "FEHLER: $bin ist nicht arm64"; fail=1; }
done
encoders="$("$DIST/ffmpeg" -hide_banner -encoders)"
for e in h264_videotoolbox hevc_videotoolbox libvpx-vp9 libopus aac; do
  grep -qE "^ [VAS][.A-Z]+ $e " <<<"$encoders" || { echo "FEHLER: Encoder $e fehlt"; fail=1; }
done
if grep -qE "libx26[45]" <<<"$encoders"; then echo "FEHLER: x264/x265 enthalten"; fail=1; fi

[[ $fail -eq 0 ]] || die "Prüfungen fehlgeschlagen."
echo "==> Fertig: $DIST/ffmpeg und $DIST/ffprobe"
