#!/bin/bash
# Copyright 2026 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

set -euo pipefail

# Resolve the directory containing this script.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
STARLARK_DIR="${SCRIPT_DIR}/../starlark"
LOCAL_BIN_DIR="${SCRIPT_DIR}/.bin"

if [ ! -f "${LOCAL_BIN_DIR}/bin/cxxbridge" ]; then
  echo "Fetching cargo dependencies to ensure cxx is in cache..."
  cargo fetch --manifest-path "${STARLARK_DIR}/Cargo.toml"

  echo "Locating cxxbridge source in cargo cache..."
  CMD_DIR=$(find "${HOME}/.cargo/git/checkouts" -type d -path "*/cxx-*/bridge/cmd" 2>/dev/null | head -n 1)

  if [ -z "${CMD_DIR}" ]; then
    echo "Error: Could not find cxx checkout under ~/.cargo/git/checkouts/" >&2
    exit 1
  fi

  echo "Compiling cxxbridge tool from cargo cache..."
  cargo install --path "${CMD_DIR}" --root "${LOCAL_BIN_DIR}"
fi

(
  echo "// This file is generated by src/gn/ffi/update_bridge.sh. Do not edit manually."
  echo "// Source: cxxbridge --header"
  "${LOCAL_BIN_DIR}/bin/cxxbridge" --header
) > "${SCRIPT_DIR}/../starlark/vendor/cxx/include/cxx.h"

(
  echo "// This file is generated by src/gn/ffi/update_bridge.sh. Do not edit manually."
  echo "// Source: src/gn/ffi/starlark/crates/ffi/src/bridge.rs"
  "${LOCAL_BIN_DIR}/bin/cxxbridge" "${SCRIPT_DIR}/../starlark/crates/ffi/src/bridge.rs" --header
) > "${SCRIPT_DIR}/bridge.h"

(
  echo "// This file is generated by src/gn/ffi/update_bridge.sh. Do not edit manually."
  echo "// Source: src/gn/ffi/starlark/crates/ffi/src/bridge.rs"
  "${LOCAL_BIN_DIR}/bin/cxxbridge" "${SCRIPT_DIR}/../starlark/crates/ffi/src/bridge.rs"
) > "${SCRIPT_DIR}/bridge.cc"
