# syntax=docker/dockerfile:1

FROM --platform=$BUILDPLATFORM node:24-alpine AS frontend
WORKDIR /source
COPY web/package.json web/package-lock.json ./web/
RUN npm --prefix web ci
COPY web/ ./web/
RUN npm --prefix web run build

FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:10.0-alpine AS build
ARG TARGETARCH
WORKDIR /source
COPY global.json ./
COPY .env.example ./
COPY src/Jiaowu.Api/Jiaowu.Api.csproj ./src/Jiaowu.Api/
RUN dotnet restore ./src/Jiaowu.Api/Jiaowu.Api.csproj --arch "$TARGETARCH"
COPY src/Jiaowu.Api/ ./src/Jiaowu.Api/
COPY --from=frontend /source/src/Jiaowu.Api/wwwroot/ ./src/Jiaowu.Api/wwwroot/
RUN dotnet publish ./src/Jiaowu.Api/Jiaowu.Api.csproj \
    --configuration Release \
    --arch "$TARGETARCH" \
    --no-restore \
    --no-self-contained \
    --output /app/publish \
    -p:BuildFrontendOnPublish=false \
    -p:DebugSymbols=false \
    -p:DebugType=None

FROM mcr.microsoft.com/dotnet/aspnet:10.0-alpine AS final
WORKDIR /app
ENV ASPNETCORE_ENVIRONMENT=Production \
    ASPNETCORE_HTTP_PORTS=8080 \
    DOTNET_EnableDiagnostics=0 \
    Operations__BackupDirectory=/var/lib/jiaowu/backups \
    Operations__MySqlDumpPath=mariadb-dump \
    Operations__MySqlClientPath=mariadb
EXPOSE 8080
COPY --from=build /app/publish/ ./
ARG UID=10001
RUN apk add --no-cache font-noto-cjk mariadb-client
RUN adduser \
    --disabled-password \
    --gecos "" \
    --home "/nonexistent" \
    --shell "/sbin/nologin" \
    --no-create-home \
    --uid "${UID}" \
    appuser
RUN mkdir -p /var/lib/jiaowu/backups \
    && chown appuser:appuser /var/lib/jiaowu/backups \
    && chmod 700 /var/lib/jiaowu/backups
VOLUME ["/var/lib/jiaowu/backups"]
USER appuser
ENTRYPOINT ["dotnet", "Jiaowu.Api.dll"]
