# syntax=docker/dockerfile:1
FROM listmonk/listmonk:v6.2.0@sha256:f535d59e14991337a9f2d570273685378ae86b0d7698c3e00da444e3bc205286 AS upstream
FROM --platform=$BUILDPLATFORM golang:1.26.1-alpine@sha256:2389ebfa5b7f43eeafbd6be0c3700cc46690ef842ad962f6c5bd6be49ed82039 AS build
ARG TARGETARCH
RUN apk add --no-cache git unzip
WORKDIR /source
RUN git clone --depth 1 --branch v6.2.0 https://github.com/knadh/listmonk.git . \
    && test "$(git rev-parse HEAD)" = ef0a75872463f10a4848af6c547d1c057405453a
COPY scoped-optin.patch /build/scoped-optin.patch
RUN git apply --check /build/scoped-optin.patch && git apply /build/scoped-optin.patch
RUN --mount=type=cache,target=/go/pkg/mod go mod download \
    && go install github.com/knadh/stuffbin/stuffbin@v1.3.0
# Keep the official, unchanged compiled Vue/editor assets. Only add the source offer.
COPY --from=upstream /listmonk/listmonk /upstream-listmonk
RUN stuffbin -a unstuff -in /upstream-listmonk -out /assets.zip \
    && (unzip -q /assets.zip -d /assets || test "$?" = 1) \
    && cp static/public/templates/index.html /assets/public/templates/index.html \
    && sed -i 's@</body>@<p style="text-align: center"><a href="/public/static/rai-listmonk-source.tar.gz">Quellcode dieser Version (AGPLv3)</a></p></body>@' /assets/admin/index.html
COPY Dockerfile README.md /source/rai-build/
COPY scoped-optin.patch /source/rai-build/
# Only upstream source and this patch/build recipe, never the private platform repo.
RUN tar --exclude=.git -czf /assets/public/static/rai-listmonk-source.tar.gz .
RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build \
    go test ./... \
    && CGO_ENABLED=0 GOOS=linux GOARCH=$TARGETARCH go build -o /patched-listmonk \
       -ldflags="-s -w -X main.versionString=v6.2.0-rai.1 -X main.buildString=v6.2.0-rai.1-scoped-optin" ./cmd
RUN stuffbin -a stuff -in /patched-listmonk -out /patched-listmonk /assets:/
FROM upstream
LABEL org.opencontainers.image.version="v6.2.0-rai.1" \
      org.opencontainers.image.licenses="AGPL-3.0-only" \
      org.opencontainers.image.description="Listmonk 6.2.0 with scoped public double-opt-in; source included"
COPY --from=build /patched-listmonk /listmonk/listmonk
