#!/usr/bin/env bash
# ffmpeg LGPL, DÉCODAGE SEUL, pour « WebDiffusion Virtual Webcam » (docs/RD/VIRTUAL_WEBCAM.md §13 : LGPL, aucun
# composant GPL ni nonfree — l'app ne fait que lire le programme du pcr : RTSP → H.264/HEVC (VideoToolbox) + Opus/AAC
# → NV12 brut + PCM f32 sur deux sockets locales). Aucune bibliothèque tierce : tout est natif à ffmpeg.
#
#   apps/wds-virtualcam/scripts/build-ffmpeg-lgpl.sh            # build (~3 min sur M4 Pro)
#   apps/wds-virtualcam/scripts/build-ffmpeg-lgpl.sh --check    # vérifie le binaire présent
#
# Sortie : apps/wds-virtualcam/build/ffmpeg/{ffmpeg,ffprobe} (+ THIRD-PARTY-LICENSES/ : LGPL v2.1 + SOURCES.txt), embarqué
# dans l'app par scripts/build.sh. Obligation LGPL : texte de licence + sources correspondantes publiées
# (même lot que le pcr : scripts/package/publish-ffmpeg-sources.sh, docs/DEPLOYMENT.md § Licences tierces).
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
OUT="$ROOT/build/ffmpeg"
WORK="$ROOT/build/ffmpeg-build"
JOBS="$(sysctl -n hw.ncpu)"
FFMPEG_VERSION="${FFMPEG_VERSION:-8.1.1}"   # = version du pcr (scripts/package/build-ffmpeg-mac.sh)
SRC_FFMPEG="https://ffmpeg.org/releases/ffmpeg-$FFMPEG_VERSION.tar.xz"
# Les archives sont partagées avec le build du pcr quand elles existent déjà (même version).
PCR_CACHE="$ROOT/../../resources/pack/.cache/ffmpeg-build/src"

step() { echo "=== $(date +%H:%M:%S) $*"; }

check_binary() {
  local bin="$OUT/ffmpeg"
  [ -x "$bin" ] || { echo "✗ $bin absent"; return 1; }
  [ -x "$OUT/ffprobe" ] || { echo "✗ ffprobe absent (la sonde de l'app l'utilise)"; return 1; }
  local lic; lic="$("$bin" -hide_banner -L 2>&1 | tr '\n' ' ')"
  echo "licence : $(echo "$lic" | grep -oi "GNU Lesser General Public License[^;]*; either version [0-9.]*" | head -1)"
  echo "$lic" | grep -qi "Lesser General Public License" || { echo "✗ pas LGPL"; return 1; }
  local conf; conf="$("$bin" -hide_banner -buildconf 2>&1)"
  echo "$conf" | grep -q -- "--enable-gpl" && { echo "✗ GPL activé"; return 1; }
  echo "$conf" | grep -q -- "--enable-nonfree" && { echo "✗ nonfree activé"; return 1; }
  local missing=0 decs encs protos fmts filts hw
  decs="$("$bin" -hide_banner -decoders 2>/dev/null)"; encs="$("$bin" -hide_banner -encoders 2>/dev/null)"
  protos="$("$bin" -hide_banner -protocols 2>/dev/null)"; fmts="$("$bin" -hide_banner -formats 2>/dev/null)"
  filts="$("$bin" -hide_banner -filters 2>/dev/null)"; hw="$("$bin" -hide_banner -hwaccels 2>/dev/null)"
  for dec in h264 hevc aac opus; do grep -q " $dec " <<<"$decs" || { echo "✗ décodeur manquant : $dec"; missing=1; }; done
  for enc in rawvideo pcm_f32le; do grep -q " $enc " <<<"$encs" || { echo "✗ encodeur manquant : $enc"; missing=1; }; done
  grep -q "libx264\|libsrt\|libopus" <<<"$encs$conf" && { echo "✗ bibliothèque tierce présente"; missing=1; }
  for pr in tcp rtp pipe; do grep -q " $pr " <<<" $protos " || grep -q "$pr" <<<"$protos" || { echo "✗ protocole manquant : $pr"; missing=1; }; done
  for mux in rtsp rawvideo f32le; do grep -qE "^ +[DEd ]+ +$mux( |$)" <<<"$fmts" || { echo "✗ format manquant : $mux"; missing=1; }; done
  for f in scale format aresample fps; do grep -q " $f " <<<"$filts" || { echo "✗ filtre manquant : $f"; missing=1; }; done
  grep -q "videotoolbox" <<<"$hw" || { echo "✗ hwaccel videotoolbox manquant"; missing=1; }
  if otool -L "$bin" | grep -qvE "^$bin:|/usr/lib/|/System/Library/"; then echo "⚠ dépendances hors système :"; otool -L "$bin" | grep -vE "^$bin:|/usr/lib/|/System/Library/"; missing=1; else echo "liaison : système seulement ✓"; fi
  [ "$missing" = 0 ] && echo "✓ ffmpeg $FFMPEG_VERSION LGPL décodage seul ($(du -h "$bin" | cut -f1))"
  return $missing
}
if [ "${1:-}" = "--check" ]; then check_binary; exit $?; fi

mkdir -p "$WORK/src" "$OUT"
export MACOSX_DEPLOYMENT_TARGET="${MACOSX_DEPLOYMENT_TARGET:-13.0}"   # = l'app (extension caméra)
ARCHIVE="$WORK/src/ffmpeg-$FFMPEG_VERSION.tar.xz"
if [ ! -f "$ARCHIVE" ]; then
  if [ -f "$PCR_CACHE/ffmpeg-$FFMPEG_VERSION.tar.xz" ]; then cp "$PCR_CACHE/ffmpeg-$FFMPEG_VERSION.tar.xz" "$ARCHIVE"; else
    step "téléchargement"; curl -fsSL --retry 3 -o "$ARCHIVE.part" "$SRC_FFMPEG" && mv "$ARCHIVE.part" "$ARCHIVE"; fi
fi
[ -d "$WORK/src/ffmpeg-$FFMPEG_VERSION" ] || tar xf "$ARCHIVE" -C "$WORK/src"

step "ffmpeg $FFMPEG_VERSION (LGPL, décodage seul)"
FFMPEG_CONFIGURE=(
  --prefix="$WORK/prefix"
  --enable-static --disable-shared --disable-debug --disable-doc --disable-ffplay
  --disable-everything
  --enable-protocol=tcp,udp,rtp,file,pipe   # RTSP = DEMUXER (rtsp), pas un protocole
  --enable-demuxer=rtsp,rtp,sdp,h264,hevc,aac,ogg,mov,mpegts
  --enable-parser=h264,hevc,aac,opus
  --enable-decoder=h264,hevc,aac,opus,pcm_s16le
  --enable-hwaccel=h264_videotoolbox,hevc_videotoolbox --enable-videotoolbox
  --enable-muxer=rawvideo,pcm_f32le,null   # (nom configure du muxer « f32le »)
  --enable-encoder=rawvideo,pcm_f32le
  --enable-filter=scale,format,aresample,fps,aformat,anull,null,setpts,asetpts
  --enable-bsf=h264_mp4toannexb,hevc_mp4toannexb,aac_adtstoasc
  --disable-sdl2 --disable-xlib --disable-libxcb --disable-vulkan --disable-audiotoolbox
  --enable-neon --enable-runtime-cpudetect
)
SRC="$WORK/src/ffmpeg-$FFMPEG_VERSION"
(cd "$SRC" && make distclean >/dev/null 2>&1 || true)
(cd "$SRC" && ./configure "${FFMPEG_CONFIGURE[@]}" > "$WORK/configure.log" 2>&1 || { tail -20 "$WORK/configure.log"; exit 1; })
(cd "$SRC" && make -j"$JOBS" > "$WORK/make.log" 2>&1 || { tail -30 "$WORK/make.log"; exit 1; })
for b in ffmpeg ffprobe; do cp "$SRC/$b" "$OUT/$b"; strip "$OUT/$b" 2>/dev/null || true; chmod +x "$OUT/$b"; done

step "licences"
LIC="$OUT/THIRD-PARTY-LICENSES"; rm -rf "$LIC"; mkdir -p "$LIC"
cp "$SRC/COPYING.LGPLv2.1" "$LIC/ffmpeg-COPYING.LGPLv2.1"
cp "$SRC/LICENSE.md" "$LIC/ffmpeg-LICENSE.md"
cat > "$LIC/SOURCES.txt" <<EOF
ffmpeg $FFMPEG_VERSION for WebDiffusion Virtual Webcam (macOS) — decode-only build, built $(date -u +%Y-%m-%dT%H:%M:%SZ)
by apps/wds-virtualcam/scripts/build-ffmpeg-lgpl.sh. License of this binary: GNU LGPL version 2.1 or later. No GPL,
no nonfree component, no third-party library.
Source: $SRC_FFMPEG — corresponding sources published next to the application updates (docs/DEPLOYMENT.md § Licences tierces).
ffmpeg configure: ${FFMPEG_CONFIGURE[*]}
EOF

step "vérification"
check_binary
