# Build stage
FROM rust:1.93.1-bookworm AS builder

WORKDIR /app

RUN apt-get update \
    && apt-get install -y --no-install-recommends libssl-dev pkg-config \
    && rm -rf /var/lib/apt/lists/*

COPY Cargo.toml Cargo.lock ./
COPY crates ./crates
COPY src ./src
COPY sql ./sql
RUN test -f /app/sql/provision.sql

RUN cargo build --locked --release --bin server --features server

# Runtime stage
FROM debian:bookworm-slim

ARG APP_NAME=athena-auth-server
ARG APP_VERSION=1.11.0
ARG APP_DESCRIPTION="Athena Auth Rust server"
ARG ATHENA_AUTH_CONFIG_FILE=/app/config.yaml
ARG APP_UID=10001

LABEL org.opencontainers.image.title="${APP_NAME}" \
    org.opencontainers.image.version="${APP_VERSION}" \
    org.opencontainers.image.description="${APP_DESCRIPTION}" \
    org.opencontainers.image.source="https://github.com/xylex-group/athena-auth"

WORKDIR /app

RUN apt-get update \
    && apt-get install -y --no-install-recommends ca-certificates libssl3 \
    && rm -rf /var/lib/apt/lists/* \
    && groupadd --system --gid "${APP_UID}" athena \
    && useradd --system --uid "${APP_UID}" --gid athena --home-dir /nonexistent --shell /usr/sbin/nologin athena \
    && mkdir -p /app/sql \
    && chown -R athena:athena /app

ENV APP_NAME=${APP_NAME}
ENV APP_VERSION=${APP_VERSION}
ENV HOST=0.0.0.0
ENV PORT=4000
ENV RUST_LOG=info
ENV ATHENA_AUTH_CONFIG_FILE=${ATHENA_AUTH_CONFIG_FILE}

COPY --from=builder --chown=athena:athena /app/target/release/server /usr/local/bin/server
COPY --from=builder --chown=athena:athena /app/sql/provision.sql /app/sql/provision.sql
COPY --chown=athena:athena ops/docker/config.yaml /app/config.yaml

USER athena

EXPOSE 4000

CMD ["/usr/local/bin/server"]

