#!/usr/bin/env bash
# Fetch a prebuilt PDFium dynamic library into .pdfium/ for local development.
#
# pdf-untangle's `backend-pdfium` feature loads libpdfium at RUNTIME (no build
# step needs it). This script downloads a prebuilt binary from the
# bblanchon/pdfium-binaries project (https://github.com/bblanchon/pdfium-binaries)
# and unpacks the library into a git-ignored .pdfium/ directory, which the
# crate searches automatically (after the PDFIUM_DYNAMIC_LIB_PATH env var).
#
# Usage:
#   scripts/fetch-pdfium.sh [platform]
#
# `platform` defaults to the current machine; known values include
# mac-arm64, mac-x64, linux-x64, linux-arm64, win-x64.
set -euo pipefail

cd "$(dirname "$0")/.."

platform="${1:-}"
if [[ -z "$platform" ]]; then
  case "$(uname -s)-$(uname -m)" in
    Darwin-arm64) platform=mac-arm64 ;;
    Darwin-x86_64) platform=mac-x64 ;;
    Linux-x86_64) platform=linux-x64 ;;
    Linux-aarch64) platform=linux-arm64 ;;
    *)
      echo "error: unrecognized platform '$(uname -s)-$(uname -m)'; pass one explicitly" >&2
      exit 1
      ;;
  esac
fi

url="https://github.com/bblanchon/pdfium-binaries/releases/latest/download/pdfium-${platform}.tgz"
mkdir -p .pdfium
echo "fetching ${url}"
curl -fsSL "$url" -o .pdfium/pdfium.tgz
tar -xzf .pdfium/pdfium.tgz -C .pdfium
rm .pdfium/pdfium.tgz

# The archive unpacks to bin/ include/ lib/; the dynamic library lives in lib/.
lib="$(find .pdfium/lib -name 'libpdfium.*' -o -name 'pdfium.dll' | head -n1)"
if [[ -z "$lib" ]]; then
  echo "error: no pdfium library found in the downloaded archive" >&2
  exit 1
fi
cp "$lib" .pdfium/
echo "installed $(basename "$lib") into .pdfium/ — the backend will find it automatically"
echo "(or set PDFIUM_DYNAMIC_LIB_PATH=$PWD/.pdfium explicitly)"
