#!/bin/sh

set -e
set -x

root_import_path="github.com/humanlogio/api/go"

go_options=""

for file in $(find proto/ -name "*.proto" -printf "%P\n"); do
  package_version="$(basename $(dirname $file))"
  package_dir="$(basename $(dirname $(dirname $file)))"
  package_name="${package_dir}${package_version}"

  go_options="$go_options --go_opt=M${file}=${root_import_path}/$(dirname $file);${package_name}"
done

input_files=$(find proto/ -type f -name "*.proto")

protoc --proto_path=proto \
  --go_out=${BUILDDIR}/go \
  --go_opt=paths=source_relative \
  --connect-go_out=${BUILDDIR}/go \
  --connect-go_opt=paths=source_relative \
  $go_options \
  $input_files

# Fix broken import paths generated by protoc-gen-connect-go
sed -ri "s%\"(svc/|types/)%\"github.com/humanlogio/api/go/\1%g" \
  $(find $BUILDDIR -type f -name "*.connect.go")
