#!/usr/bin/env bash

set -Eeuo pipefail

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

required_tools=(protoc protoc-gen-go protoc-gen-go-grpc protoc-gen-grpc-gateway)
if [[ "${GENERATE_SLC:-1}" == "1" ]]; then
  required_tools+=(protoc-gen-slc)
fi

for tool in "${required_tools[@]}"; do
  if ! command -v "${tool}" >/dev/null 2>&1; then
    echo "error: ${tool} was not found in PATH" >&2
    exit 1
  fi
done

cd -- "${WORKSPACE_ROOT}"

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 \
    --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[@]}"

  if [[ "${GENERATE_SLC:-1}" == "1" ]]; then
    (
      cd -- "${module_dir}"
      protoc \
        --proto_path="${WORKSPACE_ROOT}" \
        --slc_out=./ \
        --slc_opt="path=${module_dir}" \
        "${proto_files[@]}"
    )
  fi
done < <(find "${WORKSPACE_ROOT}/module" -type f -name go.mod -print0 | sort -z)

echo "Protobuf generation completed successfully."
