# syntax=docker/dockerfile:1
#
# Authelia + Authelia-API combined container
# ===========================================
# Runs both Authelia (auth portal, port 9091) and Authelia-API
# (user management + policy management API, port 8080) in a single container.
#
# Build:
#   docker build -t git24hcom/authelia-api:latest .
#
# Volumes:
#   /config  — Authelia config + user DB + notification templates
#   /data    — Authelia-API SQLite DB
#   /certs   — TLS certificates (optional)
#

# --- Stage 1: fetch Authelia binary ---
FROM alpine:3.21 AS authelia-dl

ARG AUTHELIA_VERSION=4.39.20
ARG TARGETARCH=amd64

WORKDIR /tmp
ADD https://github.com/authelia/authelia/releases/download/v${AUTHELIA_VERSION}/authelia-v${AUTHELIA_VERSION}-linux-${TARGETARCH}.tar.gz /tmp/authelia.tar.gz
RUN tar -xzf /tmp/authelia.tar.gz && \
    mv authelia /usr/local/bin/authelia && \
    chmod +x /usr/local/bin/authelia

# --- Stage 2: build Authelia-API from source ---
FROM golang:1.22-bookworm AS go-build

WORKDIR /build
COPY src/ .
RUN go mod download && \
    CGO_ENABLED=0 go build -ldflags="-s -w" -o authelia-api ./cmd/server

# --- Stage 3: runtime image ---
FROM debian:bookworm-slim

RUN apt-get update && apt-get install -y --no-install-recommends \
    ca-certificates \
    tzdata \
    libsqlite3-0 \
    netcat-openbsd \
    && rm -rf /var/lib/apt/lists/*

# Copy binaries from build stages
COPY --from=authelia-dl /usr/local/bin/authelia /usr/local/bin/authelia
COPY --from=go-build /build/authelia-api /usr/local/bin/authelia-api

# Create directories
RUN mkdir -p /config /data /certs && \
    chmod 755 /config /data /certs

# Add non-root user
RUN groupadd -r authelia && \
    useradd -r -g authelia -d /config -s /sbin/nologin authelia && \
    chown authelia:authelia /config /data /certs

# Entrypoint
COPY docker/entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh

EXPOSE 9091 8080

VOLUME ["/config", "/data", "/certs"]

ENTRYPOINT ["/entrypoint.sh"]
