# tools and packages from base image
FROM ${build_registry}/build/golang:${version}-alpine3.18${kafka} AS builder

<% if(module_property.kafka) { println "ENV GOPROXY=${go_proxy},direct CGO_ENABLED=1 GOOS=linux"} else { println "ENV GOPROXY=${go_proxy},direct CGO_ENABLED=0 GOOS=linux"} %>

# Following steps will help in downloading dependencies for the project
COPY id_github_jenkins /root/.ssh/id_rsa

RUN chmod 600 /root/.ssh/id_rsa && \
ssh-keyscan github.com >> /root/.ssh/known_hosts && \
git config --global url."git@github.com:".insteadOf "https://github.com/"

# The tar file contains only the go.mod and go.sum files, it is generated as part of Jenkins build.
ADD only-mods.tar /app/

# directory inside container and default destination for all subsequent commands
<% if (base_dir) { println "WORKDIR /app/${base_dir}"}  else { println "WORKDIR /app/"} %>

# downloading all the dependencies
RUN --mount=type=cache,target=/go/pkg/mod,id=${repo_name} \
    --mount=type=cache,target=/root/.cache/go-build,id=${repo_name}-build \
    go env -w GOPRIVATE=github.com/Meesho/* && go mod download

# copying the source code
COPY . /app/

# building the code for linux OS
RUN --mount=type=cache,target=/go/pkg/mod,id=${repo_name} \
    --mount=type=cache,target=/root/.cache/go-build,id=${repo_name}-build \
    go mod tidy && go build -tags musl --ldflags "-extldflags -static" -v -o /app/server cmd/${module}/main.go

# deploy multistage
FROM ${build_registry}/build/debian:10-slim-v1

# install an up-to-date, properly rehashed CA trust store in the runtime image
# instead of copying the stale Alpine builder bundle (DEVOPS-30300)
RUN apt-get update \
    && apt-get install -y --no-install-recommends ca-certificates \
    && update-ca-certificates \
    && rm -rf /var/lib/apt/lists/*

# copy the binary to the production image from the builder stage.
COPY --from=builder /app/server /app/server
<% if (copy_file) { print "COPY copied_files/* $copy_target" } %>
<% add_files.each { print "COPY ${it.path} ${it.target}\n" } %>
# running the binary
CMD ["/app/server"]
