FROM node:16.15.1-alpine AS frontend-deps

ENV CI=true

WORKDIR /srv/frontend

COPY ./frontend/package.json ./frontend/pnpm-lock.yaml ./frontend/pnpm-workspace.yaml /srv/frontend/
COPY ./frontend/apps/remark42/package.json /srv/frontend/apps/remark42/package.json

RUN apk add --no-cache --update git && npm i -g pnpm@7
RUN --mount=type=cache,id=pnpm,target=/root/.pnpm-store/v3 pnpm i

FROM frontend-deps AS build-frontend

ENV NODE_ENV=production
ENV CI=true

WORKDIR /srv/frontend/apps/remark42/
COPY ./frontend/apps/remark42/ /srv/frontend/apps/remark42/
RUN pnpm build

FROM umputun/baseimage:buildgo-v1.9.2 as build-backend

ARG GITHUB_TOKEN
ARG GITHUB_REF
ARG GITHUB_SHA

WORKDIR /build/backend
ADD backend /build/backend
ADD README.md /build/
ADD LICENSE /build/

COPY --from=build-frontend /srv/frontend/apps/remark42/public/ /build/backend/app/cmd/web/

RUN find /build/backend/app/cmd/web/ -regex '.*\.\(html\|js\|mjs\)$' -print -exec sed -i "s|{% REMARK_URL %}|http://127.0.0.1:8080|g" {} \;

RUN \
  version=$("/script/version.sh") && echo "version=${version}" && \
    GOOS=linux GOARCH=amd64 go build -o remark42.linux-amd64 -ldflags "-X main.revision=${version} -s -w" ./app && \
    GOOS=linux GOARCH=386 go build -o remark42.linux-386 -ldflags "-X main.revision=${version} -s -w" ./app && \
    GOOS=linux GOARCH=arm go build -o remark42.linux-arm -ldflags "-X main.revision=${version} -s -w" ./app && \
    GOOS=linux GOARCH=arm64 go build -o remark42.linux-arm64 -ldflags "-X main.revision=${version} -s -w" ./app && \
    GOOS=windows GOARCH=amd64 go build -o remark42.windows-amd64.exe -ldflags "-X main.revision=${version} -s -w" ./app && \
    GOOS=darwin GOARCH=amd64 go build -o remark42.darwin-amd64 -ldflags "-X main.revision=${version} -s -w" ./app && \
    GOOS=darwin GOARCH=arm64 go build -o remark42.darwin-arm64 -ldflags "-X main.revision=${version} -s -w" ./app && \
    GOOS=freebsd GOARCH=amd64 go build -o remark42.freebsd-amd64 -ldflags "-X main.revision=${version} -s -w" ./app

RUN \
    apk add --no-cache --update zip && \
    cp ../LICENSE ./LICENSE && cp ../README.md ./README.md && \
    tar cvzf remark42.linux-amd64.tar.gz remark42.linux-amd64 LICENSE README.md && \
    tar cvzf remark42.linux-386.tar.gz remark42.linux-386 LICENSE README.md && \
    tar cvzf remark42.linux-arm.tar.gz remark42.linux-arm LICENSE README.md && \
    tar cvzf remark42.linux-arm64.tar.gz remark42.linux-arm64 LICENSE README.md && \
    tar cvzf remark42.darwin-amd64.tar.gz remark42.darwin-amd64 LICENSE README.md && \
    tar cvzf remark42.darwin-arm64.tar.gz remark42.darwin-arm64 LICENSE README.md && \
    tar cvzf remark42.freebsd-amd64.tar.gz remark42.freebsd-amd64 LICENSE README.md && \
    zip remark42.windows-amd64.zip remark42.windows-amd64.exe LICENSE README.md


FROM alpine
COPY --from=build-backend /build/backend/remark42.* /artifacts/
RUN ls -la /artifacts/*
CMD ["sleep", "100"]
