#!/usr/bin/env bash

set -Eeuo pipefail

readonly SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
readonly WORKSPACE_ROOT="$(cd -- "${SCRIPT_DIR}/.." && pwd)"
readonly TOOL_ROOT="${WORKSPACE_ROOT}/.tools"

protoc_bin="${TOOL_ROOT}/protoc/bin/protoc"
plugin_dir="${TOOL_ROOT}/bin"

if [[ "${OS:-}" == "Windows_NT" ]]; then
  protoc_bin="${protoc_bin}.exe"
fi

if [[ ! -x "${protoc_bin}" ]]; then
  protoc_bin="$(command -v protoc || true)"
fi

if [[ -z "${protoc_bin}" ]]; then
  echo "error: protoc was not found; install it or place it under .tools/protoc" >&2
  exit 1
fi

export PATH="${plugin_dir}:${PATH}"

for plugin in protoc-gen-go protoc-gen-go-grpc protoc-gen-grpc-gateway; do
  if ! command -v "${plugin}" >/dev/null 2>&1; then
    echo "error: ${plugin} was not found in PATH or .tools/bin" >&2
    exit 1
  fi
done

cd -- "${WORKSPACE_ROOT}"

echo "==> protobuf/blocks.proto"
"${protoc_bin}" \
  --proto_path="${WORKSPACE_ROOT}" \
  --go_out="${WORKSPACE_ROOT}/protobuf" \
  --go_opt=module=bsm/full/protobuf \
  protobuf/blocks.proto

while IFS= read -r -d '' go_mod; do
  module_dir="$(dirname -- "${go_mod}")"
  proto_dir="${module_dir}/proto"
  [[ -d "${proto_dir}" ]] || continue

  module_path="$(awk '$1 == "module" { print $2; exit }' "${go_mod}")"
  module_path="${module_path//$'\r'/}"
  output_dir="${module_dir}/pb"

  mkdir -p "${output_dir}"
  find "${output_dir}" -maxdepth 1 -type f \
    \( -name '*.pb.go' -o -name '*_grpc.pb.go' -o -name '*.pb.gw.go' \) -delete

  mapfile -d '' proto_files < <(find "${proto_dir}" -maxdepth 1 -type f -name '*.proto' -print0 | sort -z)
  (( ${#proto_files[@]} > 0 )) || continue

  echo "==> ${module_path} (${#proto_files[@]} files)"
  "${protoc_bin}" \
    --proto_path="${WORKSPACE_ROOT}" \
    --go_out="${module_dir}" \
    --go_opt="module=${module_path}" \
    --go-grpc_out="${module_dir}" \
    --go-grpc_opt="module=${module_path},require_unimplemented_servers=false" \
    --grpc-gateway_out="${module_dir}" \
    --grpc-gateway_opt="module=${module_path},generate_unbound_methods=true" \
    "${proto_files[@]}"
done < <(find "${WORKSPACE_ROOT}/module" -type f -name go.mod -print0 | sort -z)

echo "Protobuf generation completed successfully."
