FROM reg.cadoles.com/proxy_cache/library/golang:1.22.0 AS BUILD

RUN apt-get update \
    && apt-get install -y make

ARG YQ_VERSION=4.34.1

RUN mkdir -p /usr/local/bin \
    && wget -O /usr/local/bin/yq https://github.com/mikefarah/yq/releases/download/v${YQ_VERSION}/yq_linux_amd64 \
    && chmod +x /usr/local/bin/yq

WORKDIR /src

COPY go.mod .
COPY go.sum .

RUN go mod download

COPY . /src

RUN make GORELEASER_ARGS='build --rm-dist --single-target --snapshot' goreleaser

# Patch config
RUN /src/dist/bouncer_linux_amd64_v1/bouncer -c '' config dump > /src/dist/bouncer_linux_amd64_v1/config.yml \
    && yq -i '.layers.queue.templateDir = "/usr/share/bouncer/layers/queue/templates"' /src/dist/bouncer_linux_amd64_v1/config.yml \
    && yq -i '.layers.authn.templateDir = "/usr/share/bouncer/layers/authn/templates"' /src/dist/bouncer_linux_amd64_v1/config.yml \
    && yq -i '.admin.auth.privateKey = "/etc/bouncer/admin-key.json"' /src/dist/bouncer_linux_amd64_v1/config.yml \
    && yq -i '.redis.adresses = ["redis:6379"]' /src/dist/bouncer_linux_amd64_v1/config.yml \
    && yq -i '.redis.writeTimeout = "30s"' /src/dist/bouncer_linux_amd64_v1/config.yml \
    && yq -i '.redis.readTimeout = "30s"' /src/dist/bouncer_linux_amd64_v1/config.yml \
    && yq -i '.redis.dialTimeout = "30s"' /src/dist/bouncer_linux_amd64_v1/config.yml \
    && yq -i '.bootstrap.lockTimeout = "30s"' /src/dist/bouncer_linux_amd64_v1/config.yml \
    && yq -i '.integrations.kubernetes.lockTimeout = "30s"' /src/dist/bouncer_linux_amd64_v1/config.yml

FROM reg.cadoles.com/proxy_cache/library/alpine:3.19.1 AS RUNTIME

RUN apk add --no-cache ca-certificates dumb-init

ENTRYPOINT ["/usr/bin/dumb-init", "--"]

RUN mkdir -p /usr/local/bin /usr/share/bouncer/bin /etc/bouncer

COPY --from=BUILD /src/dist/bouncer_linux_amd64_v1/bouncer /usr/share/bouncer/bin/bouncer
COPY --from=BUILD /src/layers /usr/share/bouncer/layers
COPY --from=BUILD /src/dist/bouncer_linux_amd64_v1/config.yml /etc/bouncer/config.yml

RUN ln -s /usr/share/bouncer/bin/bouncer /usr/local/bin/bouncer

EXPOSE 8080
EXPOSE 8081
EXPOSE 8082

RUN adduser -D -H bouncer

ENV BOUNCER_CONFIG=/etc/bouncer/config.yml

USER bouncer

CMD ["bouncer"]