# syntax=docker/dockerfile:1.7

# Stage 1: Build the Flutter web app
FROM ghcr.io/cirruslabs/flutter:stable AS build

WORKDIR /app
ENV PUB_CACHE=/root/.pub-cache

# Copy pubspec files and get dependencies
COPY pubspec.yaml pubspec.lock ./
RUN --mount=type=cache,target=/root/.pub-cache \
    flutter pub get

# Copy the rest of the app
COPY . .

# Build web app
RUN --mount=type=cache,target=/root/.pub-cache \
    flutter build web --release

# Create app-version.json if it doesnt exist
RUN test -f app-version.json || echo '{"version":"__BUILD_PUBLISHED_AT__"}' > app-version.json

# Stage 2: Serve with nginx
FROM nginx:alpine
ARG PUBLISHED_AT

# Copy the built web app from build stage
COPY --from=build /app/build/web /usr/share/nginx/html
# Copy runtime update manifest outside Flutter asset pre-cache.
COPY --from=build /app/app-version.json /usr/share/nginx/html/app-version.json

# Fill published_at at image build time (UTC), unless explicitly provided.
RUN set -eu; \
    published_at="${PUBLISHED_AT:-$(date -u +%Y-%m-%dT%H:%M:%SZ)}"; \
    sed "s|__BUILD_PUBLISHED_AT__|${published_at}|g" /usr/share/nginx/html/app-version.json > /tmp/app-version.json; \
    mv /tmp/app-version.json /usr/share/nginx/html/app-version.json

# Copy custom nginx config
COPY nginx.conf /etc/nginx/conf.d/default.conf

# Expose port
EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]
