# Builds RedCore for Linux with headless Godot, after a smoke test that runs both scenes
# headless and fails on script errors. Copy the binary into ./build with:
#   docker build --target test -t redcore-build .
#   id=$(docker create redcore-build) && docker cp $id:/project/build/RedCore.x86_64 build/ && docker rm $id
# With BuildKit, `docker build --output build .` does the same in one step.

FROM debian:bookworm-slim AS godot
ARG GODOT_VERSION=4.7.2
ARG GODOT_URL=https://github.com/godotengine/godot/releases/download/${GODOT_VERSION}-stable
RUN apt-get update \
 && apt-get install -y --no-install-recommends ca-certificates wget unzip libfontconfig1 \
 && rm -rf /var/lib/apt/lists/*
WORKDIR /tmp/godot
RUN wget -q ${GODOT_URL}/Godot_v${GODOT_VERSION}-stable_linux.x86_64.zip \
 && unzip -q Godot_*.zip \
 && mv Godot_v${GODOT_VERSION}-stable_linux.x86_64 /usr/local/bin/godot \
 && rm -rf /tmp/godot/*
# Only the Linux export templates are kept from the archive.
RUN wget -q ${GODOT_URL}/Godot_v${GODOT_VERSION}-stable_export_templates.tpz \
 && unzip -q Godot_*.tpz 'templates/linux_*' 'templates/version.txt' \
 && mkdir -p /root/.local/share/godot/export_templates/${GODOT_VERSION}.stable \
 && mv templates/* /root/.local/share/godot/export_templates/${GODOT_VERSION}.stable/ \
 && rm -rf /tmp/godot/*

FROM godot AS build
WORKDIR /project
COPY . .
RUN godot --headless --import \
 && mkdir -p build \
 && godot --headless --export-release "Linux" build/RedCore.x86_64

FROM build AS test
# Quitting while a sound plays makes Godot report that sound as "still in use at exit";
# that one shutdown message is ignored, every other error fails the build.
RUN for scene in title game; do \
      timeout 60 godot --headless --path . res://scenes/$scene.tscn --quit-after 1200 2>&1 | tee -a /tmp/run.log; \
    done \
 && ! grep -E "SCRIPT ERROR|^ERROR" /tmp/run.log | grep -v "resources still in use at exit"

FROM scratch
COPY --from=build /project/build/ /
