#!/bin/sh
# Builds the ffmpeg and ffprobe the Linux Media extension ships, per
# architecture, in an ubuntu:24.04 container (glibc 2.39, the Linux app's
# floor): LGPL only, static libav* and dav1d, --disable-autodetect so
# nothing the image happens to hold becomes a dependency, h264_vaapi with
# libva reached through Implib.so trampolines (the system's libva is loaded
# at the first va* call, so a machine without it runs everything but
# h264_vaapi, which then exits 69), and libopenh264 through a static loader
# that loads Cisco's binary from the path HYPERDROP_OPENH264 names. Cisco's
# binary itself is never fetched here: the Media extension downloads it on
# the person's computer (mediaext/openh264).
#
#   mediaext/ffmpeg/build-linux.sh [all|amd64|arm64]     # default all
#   mediaext/ffmpeg/build-linux.sh --cache-key
#   mediaext/ffmpeg/build-linux.sh --check-cache <amd64|arm64>
#
# Needs Docker (amd64 runs emulated on an Apple Silicon Mac) and, on the
# first run, the network. Versions and hashes: versions.env (ffmpeg, dav1d,
# shared with build.sh) then versions-linux.env (OpenH264 headers); every
# download is checked against its pin before use. Implib.so is vendored in
# linux/implib/ (MIT), copied from the archive IMPLIB_COMMIT and
# IMPLIB_SHA256 name, so no build fetches it.
# Output: mediaext/.build/ffmpeg-linux/<FFMPEG_VERSION>/<arch>/{ffmpeg,
# ffprobe,inventory.txt}, stamped with a hash of the whole recipe only once
# the container's checks pass: a root of its own, because build.sh removes
# mediaext/.build/ffmpeg/<version>/ whenever its own stamp differs. The
# source tarballs are shared with build.sh in mediaext/.build/ffmpeg/src/,
# which neither script ever removes. `all` fails unless both architectures finish
# and offer the same encoders, decoders and protocols.
set -eu

HERE="$(cd "$(dirname "$0")" && pwd)"          # mediaext/ffmpeg
MEDIAEXT="$(cd "$HERE/.." && pwd)"              # mediaext
. "$HERE/versions.env"
. "$HERE/versions-linux.env"
export FFMPEG_VERSION DAV1D_VERSION OPENH264_VERSION
SRC="$MEDIAEXT/.build/ffmpeg/src"
OUT="$MEDIAEXT/.build/ffmpeg-linux/$FFMPEG_VERSION"
IMAGE=ubuntu:24.04

sha256_stdin() {
  if command -v shasum >/dev/null 2>&1; then shasum -a 256 | awk '{print $1}'
  else sha256sum | awk '{print $1}'; fi
}
sha256_of() { sha256_stdin < "$1"; }

cache_key() {
  { cat "$HERE/versions.env" "$HERE/versions-linux.env" "$HERE/components.env" "$HERE/check-components.sh" "$HERE/build-linux.sh"
    find "$HERE/linux" -type f | LC_ALL=C sort | while IFS= read -r f; do cat "$f"; done
  } | sha256_stdin
}
KEY="$(cache_key)"

cached() {
  [ "$(cat "$OUT/$1/.recipe-sha256" 2>/dev/null || true)" = "$KEY" ] \
    && [ -x "$OUT/$1/ffmpeg" ] && [ -x "$OUT/$1/ffprobe" ]
}

case "${1:-all}" in
  --cache-key) echo "$KEY"; exit 0 ;;
  --check-cache)
    case "${2:-}" in amd64|arm64) ;; *) echo "usage: $0 --check-cache <amd64|arm64>" >&2; exit 2 ;; esac
    cached "$2" || { echo "the linux-$2 ffmpeg cache does not match the recipe; run $0 $2" >&2; exit 1; }
    exit 0 ;;
  all) ARCHES="amd64 arm64" ;;
  amd64|arm64) ARCHES="$1" ;;
  *) echo "usage: $0 [all|amd64|arm64|--cache-key|--check-cache <arch>]" >&2; exit 2 ;;
esac

command -v docker >/dev/null 2>&1 || { echo "build-linux.sh needs Docker" >&2; exit 1; }
mkdir -p "$SRC"

# pin NAME FILE: FILE against the reviewed pin NAME_SHA256.
pin() {
  expected="$(eval "echo \${${1}_SHA256}")"
  actual="$(sha256_of "$2")"
  printf '%s\n' "$expected" | LC_ALL=C grep -Eq '^[0-9a-f]{64}$' \
    || { echo "ERROR: ${1}_SHA256 must hold a reviewed SHA-256 pin" >&2; exit 1; }
  [ "$expected" = "$actual" ] || { echo "ERROR: $2 has SHA-256 $actual, the pin says $expected" >&2; exit 1; }
  echo "    $(basename "$2") matches its pin"
}

# fetch URL FILE NAME: downloads once, then pins.
fetch() {
  if [ ! -s "$2" ]; then
    echo "==> downloading $1"
    curl -fL --retry 3 -o "$2.tmp" "$1"
    mv "$2.tmp" "$2"
  fi
  pin "$3" "$2"
}

fetch "https://ffmpeg.org/releases/ffmpeg-$FFMPEG_VERSION.tar.xz" "$SRC/ffmpeg-$FFMPEG_VERSION.tar.xz" FFMPEG
fetch "https://downloads.videolan.org/pub/videolan/dav1d/$DAV1D_VERSION/dav1d-$DAV1D_VERSION.tar.xz" "$SRC/dav1d-$DAV1D_VERSION.tar.xz" DAV1D
fetch "https://github.com/cisco/openh264/archive/refs/tags/v$OPENH264_VERSION.tar.gz" "$SRC/openh264-$OPENH264_VERSION.tar.gz" OPENH264

build_arch() {
  arch="$1"
  dest="$OUT/$arch"
  if cached "$arch"; then echo "==> ffmpeg $FFMPEG_VERSION (linux/$arch) already built"; return 0; fi
  [ ! -L "$dest" ] || { echo "refusing to replace a symlinked build directory: $dest" >&2; exit 1; }
  rm -rf "$dest"
  mkdir -p "$dest"
  echo "==> ffmpeg $FFMPEG_VERSION (linux/$arch) in $IMAGE"
  docker run --rm --platform "linux/$arch" \
    -e FFMPEG_VERSION -e DAV1D_VERSION -e OPENH264_VERSION \
    -e HOST_UID="$(id -u)" -e HOST_GID="$(id -g)" \
    -v "$HERE:/recipe:ro" -v "$SRC:/src:ro" -v "$dest:/out" \
    "$IMAGE" /bin/sh /recipe/linux/build-inside.sh
  [ -x "$dest/ffmpeg" ] && [ -x "$dest/ffprobe" ] && [ -s "$dest/inventory.txt" ] \
    || { echo "linux/$arch did not produce both binaries and the inventory" >&2; exit 1; }
  printf '%s\n' "$KEY" > "$dest/.recipe-sha256"
}

for arch in $ARCHES; do build_arch "$arch"; done
if [ "$ARCHES" = "amd64 arm64" ]; then
  cmp -s "$OUT/amd64/inventory.txt" "$OUT/arm64/inventory.txt" \
    || { echo "ERROR: the amd64 and arm64 builds offer different encoders, decoders or protocols:" >&2
         diff "$OUT/amd64/inventory.txt" "$OUT/arm64/inventory.txt" >&2 || true; exit 1; }
fi
echo "built ffmpeg and ffprobe for linux ($ARCHES), ffmpeg $FFMPEG_VERSION, dav1d $DAV1D_VERSION, OpenH264 headers $OPENH264_VERSION"
