#!/usr/bin/env bash
#
# Generate the bindings.
#
# This script encapsulates the commands used to generate the bindings. It is
# also used in CI to ensure that the checked-in bindings are the same as what
# would be generated by this script.

# Get the path to the repo root.
# https://stackoverflow.com/questions/59895/how-do-i-get-the-directory-where-a-bash-script-is-located-from-within-the-script
ROOT=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )

# Generate a dummy nghttp2ver.h for bindgen.
# The build script will create a proper version at compile time.
cp "${ROOT}"/nghttp2/lib/includes/nghttp2/nghttp2ver.h{.in,}
sed -i "s/@PACKAGE_VERSION@/0.0.0/" "${ROOT}/nghttp2/lib/includes/nghttp2/nghttp2ver.h"
sed -i "s/@PACKAGE_VERSION_NUM@/0x000000/" "${ROOT}/nghttp2/lib/includes/nghttp2/nghttp2ver.h"

# Generate the bindings.
bindgen \
  "${ROOT}/nghttp2/lib/includes/nghttp2/nghttp2.h" \
  -o "${ROOT}/src/lib.rs" \
  --no-layout-tests \
  --distrust-clang-mangling \
  --no-prepend-enum-name \
  --allowlist-function 'nghttp2.*' \
  --allowlist-type 'nghttp2.*' \
  --allowlist-var 'nghttp2.*' \
  --allowlist-item 'nghttp2.*' \
  --blocklist-type=va_list \
  --blocklist-type=__builtin_va_list \
  --blocklist-type=__va_list_tag \
  --blocklist-type=nghttp2_debug_vprintf_callback \
  --blocklist-function=nghttp2_set_debug_vprintf_callback \
  -- \
  -I "${ROOT}/nghttp2/lib/includes"

# Disable lints for the generated bindings
sed -i '1i#![allow(bad_style)]' "${ROOT}/src/lib.rs"
sed -i '2i#![allow(rustdoc::bare_urls)]' "${ROOT}/src/lib.rs"
