#!/usr/bin/env bash
# Rebuild the video tools' libraries in js/vendor/, the way the committed copies were made.
#
#   mediabunny-<version>/mediabunny.js  Mediabunny (MPL-2.0), trimmed to the parts the video tools use:
#                                       reading MP4, MOV, WebM, and MKV, writing MP4, conversion, and frame
#                                       extraction. The source map carries the original source of each file.
#                                       https://github.com/Vanilagy/mediabunny
#   gifenc-<version>/gifenc.js          gifenc (MIT), copied as published. https://github.com/mattdesl/gifenc
#
# Both are imported by js/tools/video.js only after a video arrives.
# Usage: scripts/vendor_video.sh [mediabunny version] [gifenc version]   (defaults 1.61.3 and 1.0.3)
# After changing a version, update the "video_libs" paths in scripts/tool_content.py.
set -euo pipefail

MEDIABUNNY="${1:-1.61.3}"
GIFENC="${2:-1.0.3}"
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT

cd "$WORK"
npm init -y > /dev/null
npm install --no-audit --no-fund "mediabunny@$MEDIABUNNY" "gifenc@$GIFENC" esbuild@0.25 > /dev/null

cat > entry.mjs <<'EOF'
export {
  Input, Output, Conversion, ConversionCanceledError, BlobSource, BufferTarget, Mp4OutputFormat, CanvasSink,
  MP4, QTFF, WEBM, MATROSKA, QUALITY_HIGH, QUALITY_MEDIUM, canEncodeVideo, canEncodeAudio
} from 'mediabunny';
EOF
OUT="$ROOT/js/vendor/mediabunny-$MEDIABUNNY"
rm -rf "$OUT"
mkdir -p "$OUT"
npx esbuild entry.mjs --bundle --format=esm --minify --sourcemap --sources-content=true --legal-comments=linked \
  --platform=browser --target=es2020 --outfile="$OUT/mediabunny.js"
cp node_modules/mediabunny/LICENSE "$OUT/LICENSE.txt"

OUT="$ROOT/js/vendor/gifenc-$GIFENC"
rm -rf "$OUT"
mkdir -p "$OUT"
cp node_modules/gifenc/dist/gifenc.esm.js "$OUT/gifenc.js"
cp node_modules/gifenc/LICENSE.md "$OUT/LICENSE.md" 2>/dev/null || cp node_modules/gifenc/LICENSE* "$OUT/"
echo "Wrote js/vendor/mediabunny-$MEDIABUNNY and js/vendor/gifenc-$GIFENC"
