#!/usr/bin/env bash
# Build GStreamer's Rust plugins that Ubuntu does not package, from gst-plugins-rs,
# and copy them into DIR:
#   libgstrstracers.so  the perf tracers (queue-levels, buffer-lateness, pad-push-timings)
#   libgstrswebrtc.so   webrtcsink and webrtcsrc, with their signalling server
# Needs cargo (Rust 1.92 or newer), git, a C toolchain, pkg-config and
# libgstreamer1.0-dev, libgstreamer-plugins-base1.0-dev and
# libgstreamer-plugins-bad1.0-dev already installed; this script installs nothing.
#
# Usage: scripts/build-rs-plugins DIR
set -euo pipefail

# Pinned to the version brew ships on the dev Mac, so the CSV formats the
# tracers write and the webrtc plugin are the same in CI and locally.
GST_PLUGINS_RS_TAG=0.15.4

dest=${1:?usage: scripts/build-rs-plugins DIR}

work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT

git clone --quiet --depth 1 --branch "$GST_PLUGINS_RS_TAG" \
  https://gitlab.freedesktop.org/gstreamer/gst-plugins-rs.git "$work/src"
cd "$work/src"

# Upstream bug: built alone, the crate lacks tokio's "time" feature (the full
# workspace normally supplies it). Fail loudly if the patch no longer applies,
# e.g. because upstream fixed it.
manifest=utils/tracers/Cargo.toml
old='features = ["macros", "rt-multi-thread"]'
new='features = ["macros", "rt-multi-thread", "time"]'
grep -qF "$old" "$manifest" || {
  echo "build-rs-plugins: cannot patch $manifest: '$old' not found (fixed upstream?)" >&2
  exit 1
}
sed -i.bak "s/features = \[\"macros\", \"rt-multi-thread\"\]/features = [\"macros\", \"rt-multi-thread\", \"time\"]/" "$manifest"
grep -qF "$new" "$manifest"

cargo build --release -p gst-plugin-tracers

# webrtc: no default features, which would add the janus, whip, whep and web server
# parts and the aws-lc crypto (needs cmake); rustls needs one provider, ring is pure Rust
# plus a C compiler.
cargo build --release -p gst-plugin-webrtc --no-default-features --features rustls-ring

mkdir -p "$dest"
for name in rstracers rswebrtc; do
  lib=target/release/libgst$name.so
  strip "$lib"
  cp "$lib" "$dest/"
  echo "build-rs-plugins: installed $dest/libgst$name.so"
done
