#!/usr/bin/env bash
set -e -o pipefail -u -x

cd -- "$(dirname -- "$0")"
cd ../../..
pwd

protoc \
	-I ./vendor \
	-I ./vendor/code.justin.tv/common/chitin/third_party \
	--gofast_out="plugins=grpc:./vendor" \
	./vendor/code.justin.tv/release/trace/api/api.proto \
	./vendor/code.justin.tv/release/trace/api/transaction.proto

eg -w -t /dev/stdin -- ./vendor/code.justin.tv/release/trace/api/*.pb.go <<EOF
package eg

import (
	"code.justin.tv/common/chitin/grpctrace"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
)

func before(ctx context.Context, method string, args, reply interface{}, cc *grpc.ClientConn, opts ...grpc.CallOption) error {
	return grpc.Invoke(ctx, method, args, reply, cc, opts...)
}

func after(ctx context.Context, method string, args, reply interface{}, cc *grpc.ClientConn, opts ...grpc.CallOption) error {
	return grpctrace.Invoke(ctx, method, args, reply, cc, opts...)
}
EOF

eg -w -t /dev/stdin -- ./vendor/code.justin.tv/release/trace/api/*.pb.go <<EOF
package eg

import (
	"code.justin.tv/common/chitin/grpctrace"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
)

func before(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, opts ...grpc.CallOption) (grpc.ClientStream, error) {
	return grpc.NewClientStream(ctx, desc, cc, method, opts...)
}

func after(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, opts ...grpc.CallOption) (grpc.ClientStream, error) {
	return grpctrace.NewClientStream(ctx, desc, cc, method, opts...)
}
EOF

eg -w -t /dev/stdin -- ./vendor/code.justin.tv/release/trace/api/*.pb.go <<EOF
package eg

import (
	"code.justin.tv/common/chitin/grpctrace"
	"google.golang.org/grpc"
)

func before(s *grpc.Server, sd *grpc.ServiceDesc, ss interface{}) {
	s.RegisterService(sd, ss)
}

func after(s *grpc.Server, sd *grpc.ServiceDesc, ss interface{}) {
	grpctrace.RegisterService(s, sd, ss)
}
EOF

for file in ./vendor/code.justin.tv/release/trace/api/*.pb.go ; do
	sed -i.tmp -e 's,"code.justin.tv/.*/vendor/,",' "$file"
	rm -- "$file".tmp || true
done

goimports -w -l -- ./vendor/code.justin.tv/release/trace/api/*.pb.go
