#!/bin/bash

: "${PCRE2SYS_HEADER:=/usr/include/pcre2.h}"
: "${PCRE2SYS_BINDINGS:=./src/bindings.rs}"

if ! command -V bindgen > /dev/null 2>&1; then
    echo "bindgen must be installed" >&2
    echo "to install: cargo install bindgen-cli" >&2
    exit 1
fi
if ! [ -f "$PCRE2SYS_HEADER" ]; then
    echo "PCRE2 header file at $PCRE2SYS_HEADER does not exist" >&2
    echo "Use the PCRE2SYS_HEADER environment variable to override path" >&2
    exit 1
fi

if [ -z "$PCRE2_CODE_UNIT_WIDTH" ]; then
    echo "The PCRE2_CODE_UNIT_WIDTH environment variable must be set" >&2
    echo "Valid values are 8, 16, and 32" >&2
    exit 1
fi

bindgen \
    "$PCRE2SYS_HEADER" \
    --ctypes-prefix '::libc' \
    --allowlist-function '^pcre2_.*' \
    --allowlist-type '^pcre2_.*' \
    --allowlist-var '^PCRE2_.*' \
    --blocklist-function '^.*_callout_.*' \
    --blocklist-type '^.*_callout_.*' \
    -- -DPCRE2_CODE_UNIT_WIDTH=${PCRE2_CODE_UNIT_WIDTH} > "$PCRE2SYS_BINDINGS"
