# ========================================
# ===== Build image for the frontend =====
# ========================================
FROM node:14-alpine AS builder-frontend

WORKDIR /node/src/app
COPY web .

# Install the dependencies and build
RUN yarn install --frozen-lockfile && INLINE_RUNTIME_CHUNK=false yarn build

# =======================================
# ===== Build image for the backend =====
# =======================================
FROM golang:1.14.6-alpine AS builder-backend

ARG BUILD_TAG
ARG BUILD_COMMIT
ARG CC_VERSION="v15"

# gcc cross-compiler is required for building go-sqlite3
RUN apk --no-cache add curl && \
    curl -Lfs -o /tmp/gcc-9.2.0-aarch64-linux-musl.tar.xz "https://github.com/just-containers/musl-cross-make/releases/download/${CC_VERSION}/gcc-9.2.0-aarch64-linux-musl.tar.xz" && \
    tar xf /tmp/gcc-9.2.0-aarch64-linux-musl.tar.xz -C /

WORKDIR /go/src/app

COPY go.mod go.sum config.template.yml ./
COPY --from=builder-frontend /node/src/app/build public_html

RUN go mod download

COPY cmd cmd
COPY internal internal

# Prepare static files to be embedded in Go binary
RUN go get -u aletheia.icu/broccoli && \
cd internal/configuration && \
go generate . && \
cd ../server && \
go generate .

# Set the build version and time
RUN echo "Write tag ${BUILD_TAG} and commit ${BUILD_COMMIT} in binary." && \
    sed -i "s/__BUILD_TAG__/${BUILD_TAG}/" cmd/authelia/constants.go && \
    sed -i "s/__BUILD_COMMIT__/${BUILD_COMMIT}/" cmd/authelia/constants.go

# CGO_ENABLED=1 is mandatory for building go-sqlite3
RUN cd cmd/authelia && \
GOOS=linux GOARCH=arm64 CGO_ENABLED=1 CC=aarch64-linux-musl-gcc go build -tags netgo -ldflags '-s -w -linkmode external -extldflags -static' -trimpath -o authelia

# ===================================
# ===== Authelia official image =====
# ===================================
FROM arm64v8/alpine:3.12.0

COPY ./qemu-aarch64-static /usr/bin/qemu-aarch64-static

RUN apk --no-cache add ca-certificates tzdata && \
    rm /usr/bin/qemu-aarch64-static

WORKDIR /app

COPY --from=builder-backend /go/src/app/cmd/authelia/authelia ./

EXPOSE 9091

VOLUME /config

ENV PATH="/app:${PATH}"

CMD ["authelia", "--config", "/config/configuration.yml"]
