############################
# 1) Go-Build
############################
FROM golang:1.26-alpine AS build

WORKDIR /app

# git wird für private/selbst gehostete Module benötigt.
RUN apk add --no-cache git ca-certificates

COPY go.mod go.sum* ./
RUN go mod download

COPY . .

# modernc.org/sqlite läuft ohne CGO.
# Dadurch brauchen wir keine gcc/libsqlite3-dev Pakete und bekommen ein schlankes Binary.
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags="-s -w" -o /blog .


############################
# 2) Content-Clone Stage
############################
FROM alpine/git AS content

ARG CONTENT_REPO=https://git.send.nrw/sendnrw/blogcontenttemplate.git
ARG CONTENT_REF=main

RUN git clone --depth 1 --branch ${CONTENT_REF} ${CONTENT_REPO} /src

# Zielstruktur:
#   /out/content    Artikel: .md und .html
#   /out/static     CSS, Bilder, JS
#   /out/pages      statische Seiten: .md und .html
#   /out/templates  Templates
RUN mkdir -p /out/content /out/static /out/pages /out/templates

RUN if [ -d /src/articles ]; then \
      find /src/articles \( -name '*.md' -o -name '*.html' \) -exec cp {} /out/content/ \; ; \
    fi

RUN if [ -d /src/static ]; then \
      cp -r /src/static/. /out/static/ ; \
    fi

RUN if [ -d /src/pages ]; then \
      find /src/pages \( -name '*.md' -o -name '*.html' \) -exec cp {} /out/pages/ \; ; \
    fi

RUN if [ -d /src/templates ]; then \
      cp -r /src/templates/. /out/templates/ ; \
    fi


############################
# 3) Runtime-Image
############################
FROM alpine:3.23

RUN apk add --no-cache ca-certificates git tzdata

RUN mkdir -p \
      /content \
      /static \
      /pages \
      /templates \
      /data \
      /git-temp

COPY --from=build /blog /usr/local/bin/blog

COPY --from=content /out/content /content
COPY --from=content /out/static /static
COPY --from=content /out/pages /pages
COPY --from=content /out/templates /templates

ENV BLOG_CONTENT_DIR=/content
ENV BLOG_STATIC_DIR=/static
ENV BLOG_PAGES_DIR=/pages
ENV BLOG_TEMPLATES_DIR=/templates
ENV BLOG_DATA_DIR=/data
ENV BLOG_TRUSTED_HTML=true

ENV GIT_ENABLE=false
ENV GIT_REPO=null
ENV GIT_BRANCH=main
ENV GIT_DIR=/git-temp
ENV GIT_INTERVAL=10

EXPOSE 8080

CMD ["blog"]
