#!/bin/sh
# Upstream targets the browser, so exercise the module the way pdf.js loads it:
# instantiate the shipped WebAssembly from disk and decode a JPEG 2000 image.
set -eu

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

cat > "$work/check.mjs" <<'JS'
import fs from "node:fs"

const dir = "/usr/share/javascript/pdfjs-openjpeg"
const {default: OpenJPEG} = await import(dir + "/openjpeg.js")

// The glue is built with -s ENVIRONMENT=web and would fetch the payload;
// hand it the bytes instead.
const mod = await OpenJPEG({
  instantiateWasm(imports, success) {
    const instance = new WebAssembly.Instance(
      new WebAssembly.Module(fs.readFileSync(dir + "/openjpeg.wasm")), imports)
    success(instance)
    return instance.exports
  }
})

// 4x4 checkerboard, 241 bytes.
const jp2 = Buffer.from("AAAADGpQICANCocKAAAAFGZ0eXBqcDIgAAAAAGpwMiAAAAAtanAyaAAAABZpaGRyAAAABAAAAAQAAwcHAAAAAAAPY29scgEAAAAAABAAAACkanAyY/9P/1EALwAAAAAABAAAAAQAAAAAAAAAAAAAAAQAAAAEAAAAAAAAAAAAAwcBAQcBAQcBAf9SAAwAAAABAAIEBAAB/1wACkBASEhQSEhQ/2QAJQABQ3JlYXRlZCBieSBPcGVuSlBFRyB2ZXJzaW9uIDIuNS40/5AACgAAAAAAJgAB/5OA34AIB4CAgICT8wQByoscgJPzBAiCnxz/2Q==", "base64")
const ptr = mod._malloc(jp2.length)
mod.writeArrayToMemory(jp2, ptr)
const rc = mod._jp2_decode(ptr, jp2.length, 0, 0, 0, 0)
mod._free(ptr)
if (rc !== 0)
  throw new Error(`jp2_decode returned ${rc}: ${mod.errorMessages || ""}`)

if (mod.imageData.length !== 4 * 4 * 4)
  throw new Error(`unexpected image size ${mod.imageData.length}`)
const [r, g, b, a] = mod.imageData
if (r !== 255 || g !== 0 || b !== 0 || a !== 255)
  throw new Error(`unexpected first pixel ${r},${g},${b},${a}`)
console.log("decoded 4x4 JPEG 2000")
JS

node "$work/check.mjs"
