# syntax=docker/dockerfile:1.4
FROM golang:1.19.2-bullseye AS build
WORKDIR /tmp
RUN git clone --depth 1 --branch cmd/protoc-gen-go-grpc/v1.2.0 https://github.com/grpc/grpc-go.git
WORKDIR /tmp/grpc-go
RUN git apply <<'EOF'
diff --git a/cmd/protoc-gen-go-grpc/grpc.go b/cmd/protoc-gen-go-grpc/grpc.go
index a21a97ac..9f114eab 100644
--- a/cmd/protoc-gen-go-grpc/grpc.go
+++ b/cmd/protoc-gen-go-grpc/grpc.go
@@ -20,6 +20,7 @@ package main
 
 import (
 	"fmt"
+	"path"
 	"strconv"
 	"strings"
 
@@ -109,8 +110,27 @@ func generateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated
 	if len(file.Services) == 0 {
 		return nil
 	}
-	filename := file.GeneratedFilenamePrefix + "_grpc.pb.go"
-	g := gen.NewGeneratedFile(filename, file.GoImportPath)
+	var g *protogen.GeneratedFile
+	if !*separatePackage {
+		filename := file.GeneratedFilenamePrefix + "_grpc.pb.go"
+		g = gen.NewGeneratedFile(filename, file.GoImportPath)
+	} else {
+		file.GoPackageName += "grpc"
+		dir := path.Dir(file.GeneratedFilenamePrefix)
+		base := path.Base(file.GeneratedFilenamePrefix)
+		file.GeneratedFilenamePrefix = path.Join(
+			dir,
+			string(file.GoPackageName),
+			base,
+		)
+		g = gen.NewGeneratedFile(
+			file.GeneratedFilenamePrefix+"_grpc.pb.go",
+			protogen.GoImportPath(path.Join(
+				string(file.GoImportPath),
+				string(file.GoPackageName),
+			)),
+		)
+	}
 	g.P("// Code generated by protoc-gen-go-grpc. DO NOT EDIT.")
 	g.P("// versions:")
 	g.P("// - protoc-gen-go-grpc v", version)
diff --git a/cmd/protoc-gen-go-grpc/main.go b/cmd/protoc-gen-go-grpc/main.go
index 58cde2eb..6395661b 100644
--- a/cmd/protoc-gen-go-grpc/main.go
+++ b/cmd/protoc-gen-go-grpc/main.go
@@ -41,6 +41,7 @@ import (
 const version = "1.2.0"
 
 var requireUnimplemented *bool
+var separatePackage *bool
 
 func main() {
 	showVersion := flag.Bool("version", false, "print the version and exit")
@@ -52,6 +53,7 @@ func main() {
 
 	var flags flag.FlagSet
 	requireUnimplemented = flags.Bool("require_unimplemented_servers", true, "set to false to match legacy behavior")
+	separatePackage = flags.Bool("separate_package", false, "set to true to write generated files to a separate grpc package")
 
 	protogen.Options{
 		ParamFunc: flags.Set,
EOF
WORKDIR /tmp/grpc-go/cmd/protoc-gen-go-grpc
RUN --mount=type=cache,target=/go/pkg/mod \
    CGO_ENABLED=0 \
    go build -ldflags "-s -w" -trimpath

FROM scratch
COPY --from=build --link /etc/passwd /etc/passwd
COPY --from=build --link --chown=root:root /tmp/grpc-go/cmd/protoc-gen-go-grpc .
USER nobody
ENTRYPOINT [ "/protoc-gen-go-grpc" ]
