#!/bin/bash

set -e

GO_PKG=google.golang.org/grpc

# grpc_testingv3/testv3.pb.go is not re-generated because it was intentionally
# generated by an older version of protoc-gen-go. Comments from upstream in
# reflection/serverreflection_test.go.
EXCLUDE='reflection/grpc_testingv3'

# Fix import paths.
SEDPROG='
s,"google/protobuf/any.proto","github.com/golang/protobuf/ptypes/any/any.proto",;
s,"google/protobuf/duration.proto","github.com/golang/protobuf/ptypes/duration/duration.proto",;
s,"google/protobuf/empty.proto","github.com/golang/protobuf/ptypes/empty/empty.proto",;
s,"google/protobuf/struct.proto","github.com/golang/protobuf/ptypes/struct/struct.proto",;
s,"google/protobuf/timestamp.proto","github.com/golang/protobuf/ptypes/timestamp/timestamp.proto",;
s,"google/protobuf/wrappers.proto","github.com/golang/protobuf/ptypes/wrappers/wrappers.proto",;
s,"google/protobuf/descriptor.proto","github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto",;
'

proto_pkgs() {
    find "$1" -type f -name \*.proto | \
    sed 's,\(.*\)/.*,\1,' | sort -u | grep -v "${EXCLUDE}"
}

test -n "${BUILDDIR}"
cp -a debian/proto "${BUILDDIR}"
#sed -i "${SEDPROG}" $(find "${BUILDDIR}"/proto -type f -name \*.proto)

PBGO=$(find "${BUILDDIR}/src/${GO_PKG}" -type f -name \*.pb.go | \
    egrep -v "${EXCLUDE}")
rm -v -f ${PBGO}

for proto in $(find "${BUILDDIR}"/proto -type f -name \*.proto); do
    echo "# ${proto}"
    INCLUDE="${BUILDDIR}/proto:${BUILDDIR}/src"
    protoc --go_out=plugins=grpc:"${BUILDDIR}/src" \
        -I"${INCLUDE}" "${proto}"
done
for dir in $(proto_pkgs "${BUILDDIR}/src/${GO_PKG}"); do
    echo "# ${dir}"
    INCLUDE="${dir}"
    protoc --go_out=plugins=grpc,paths=source_relative:"${dir}" \
        -I"${INCLUDE}" "${dir}"/*.proto
done
