# mpq-packager — build image for the Gitea Action.
#
# Stage 1 builds StormLib (the MoPaQ library MPQEditor itself is built on) and
# our small `mpqpack` binary against it. Stage 2 is a slim runtime carrying the
# binary plus Python for the orchestration layer.

FROM debian:bookworm-slim AS build
RUN apt-get update && apt-get install -y --no-install-recommends \
        git cmake g++ make zlib1g-dev libbz2-dev ca-certificates \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /build
# Pin StormLib to a known-good tag for reproducible builds.
ARG STORMLIB_REF=v9.25
RUN git clone --depth 1 --branch "${STORMLIB_REF}" \
        https://github.com/ladislav-zezula/StormLib.git
RUN cmake -S StormLib -B StormLib/build \
        -DCMAKE_BUILD_TYPE=Release \
        -DBUILD_SHARED_LIBS=OFF \
        -DWITH_LIBTOMCRYPT=OFF \
    && cmake --build StormLib/build --target storm -j "$(nproc)" \
    && cmake --install StormLib/build

COPY src/mpqpack.c .
# StormLib installs headers to /usr/local/include and libstorm.a to
# /usr/local/lib. Link zlib/bz2 for sector (de)compression.
RUN g++ -O2 -std=c++17 -o /usr/local/bin/mpqpack mpqpack.c \
        -I/usr/local/include -lstorm -lz -lbz2 \
    && /usr/local/bin/mpqpack 2>/dev/null; \
    test -x /usr/local/bin/mpqpack

FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y --no-install-recommends \
        python3 python3-yaml zlib1g libbz2-1.0 ca-certificates \
    && rm -rf /var/lib/apt/lists/*

COPY --from=build /usr/local/bin/mpqpack /usr/local/bin/mpqpack
COPY package.py /opt/mpq-packager/package.py
COPY entrypoint.sh /opt/mpq-packager/entrypoint.sh
# Strip any CRLF (Windows checkouts) so the shebang and bash parse correctly.
RUN sed -i 's/\r$//' /opt/mpq-packager/entrypoint.sh /opt/mpq-packager/package.py \
    && chmod +x /opt/mpq-packager/entrypoint.sh

ENTRYPOINT ["/opt/mpq-packager/entrypoint.sh"]
