#!/bin/bash
set -x

PROTO_MODULES="services subscriptions event_streams targets feature_flags audit_logs"
OUTPUT_DIR=src/generated/controlplane
export GOPATH=${GOPATH:=$(go env GOPATH)}

[[ ! -d '../controlplane' ]] && \
    echo "ERROR: you must have the controlplane repo checked out alongside this repo" && \
    echo "try `go get -u code.justin.tv/eventbus/controlplane` and try again" && \
    exit 1

PROTO_FILES=""
for module in $PROTO_MODULES; do
    PROTO_FILES="$PROTO_FILES code.justin.tv/eventbus/controlplane/rpc/${module}.proto"
    PROTO_FILES="$PROTO_FILES code.justin.tv/eventbus/controlplane/infrastructure/rpc/infrastructure.proto"

    OUTFILE="$OUTPUT_DIR/twirp/${module}.pb.ts"
    echo "// this file is an auto-generated shim" > "$OUTFILE"
    echo "export { code } from '../controlplane.pb'" >> "$OUTFILE"
done

# use pinned version of generator
go install ./vendor/go.larrymyers.com/protoc-gen-twirp_typescript

# Make output directory
mkdir -p $OUTPUT_DIR

# Generate base JavaScript code
pbjs -t static-module -w commonjs -o $OUTPUT_DIR/controlplane.pb.js -p ../controlplane/vendor ../controlplane/rpc/*.proto ../controlplane/infrastructure/rpc/*.proto
# Generate TypeScript definitions
pbts -o $OUTPUT_DIR/controlplane.pb.d.ts $OUTPUT_DIR/controlplane.pb.js
# Generate wrapper to consume the package from the rest of the codebase easily
protoc --twirp_typescript_out=library=pbjs:$OUTPUT_DIR/twirp -I $GOPATH/src/code.justin.tv/eventbus/controlplane/vendor:$GOPATH/src $PROTO_FILES
