#!/bin/bash
set -e
set -x

# Remove documentation generated from the swagger-codegen-cli
rm -rf gen/pb-go/flyteidl/service/flyteadmin/docs
rm -rf gen/pb_python/flyteidl/service/flyteadmin/docs


# Unfortunately, the `--grpc-gateway-out` plugin doesn’t yet support the `source_relative` option. Until it does, we need to move the files from the autogenerated location to the source_relative location.
cp -r gen/pb-go/github.com/flyteorg/flyteidl/gen/* gen/
rm -rf gen/pb-go/github.com

# Copy the validate.py protos.
mkdir -p gen/pb_python/validate
cp -r validate/* gen/pb_python/validate/

# Update the service code manually because the code generated by protoc is incorrect
# More detail, check https://github.com/flyteorg/flyteidl/pull/303#discussion_r1002151053
sed -i -e 's/protoReq.Id.ResourceType = ResourceType(e)/protoReq.Id.ResourceType = core.ResourceType(e)/g' gen/pb-go/flyteidl/service/admin.pb.gw.go
rm -f gen/pb-go/flyteidl/service/admin.pb.gw.go-e


DIRTY=$(git status --porcelain)
if [ -n "$DIRTY" ]; then
  echo "FAILED: Protos updated without committing generated code."
  echo "Ensure make generate has run and all changes are committed."
  DIFF=$(git diff)
  echo "diff detected: $DIFF"
  DIFF=$(git diff --name-only)
  echo "files different: $DIFF"
  exit 1
else
  echo "SUCCESS: Generated code is up to date."
fi
