#!/usr/bin/env bash
# Copy libheif-js's browser build into js/vendor/libheif-js-<version>/, the way the committed copy was made.
# libheif-bundle.mjs is libheif compiled to WebAssembly (LGPL-3.0), with the .wasm embedded. It stays a
# separate file that js/tools/images.js imports only when a HEIC photo arrives, so it can be replaced.
#
# Source for this build:
#   libheif-js 1.23.5          https://github.com/catdad-experiments/libheif-js/tree/1.23.5
#   libheif-emscripten v1.23.5 https://github.com/catdad-experiments/libheif-emscripten/tree/v1.23.5
#   libheif v1.23.5            https://github.com/strukturag/libheif/tree/v1.23.5
#
# Usage: scripts/vendor_libheif.sh [version]   (default 1.23.5)
# After changing the version, update the "heif" path in scripts/tool_content.py and the links above.
set -euo pipefail

VERSION="${1:-1.23.5}"
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
OUT="$ROOT/js/vendor/libheif-js-$VERSION"
WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT

cd "$WORK"
npm init -y > /dev/null
npm install --no-audit --no-fund "libheif-js@$VERSION" > /dev/null

rm -rf "$OUT"
mkdir -p "$OUT"
cp node_modules/libheif-js/libheif-wasm/libheif-bundle.mjs "$OUT/libheif-bundle.mjs"
cp node_modules/libheif-js/LICENSE "$OUT/LICENSE.txt"
cp node_modules/libheif-js/libheif-wasm/LICENSE "$OUT/libheif-LICENSE.txt"
echo "Wrote $OUT"
