ARG DEB_VERS
ARG DPKG_ARCH=""
ARG DOSBOX_APT_LIST=/debian-apt-list.txt
FROM debian:${DEB_VERS}-slim
ARG DEB_VERS
ARG DPKG_ARCH
ARG DOSBOX_APT_LIST

# Enable cross compile architecture. Abort if not set correctly
RUN case "$DPKG_ARCH" in \
        arm64|armhf|ppc64el) dpkg --add-architecture $DPKG_ARCH ;; \
        *)  echo "DPKG_ARCH not set!" && exit 1 ;; \
    esac

ENV DEBIAN_FRONTEND=noninteractive
# Install common base package
RUN apt-get update && apt-get -y install --no-install-recommends \
        ca-certificates \
        git \
        ninja-build \
        python3-pip \
        pkg-config \
        build-essential \
        qemu-user-static \
    && rm -rf /var/lib/apt/lists/*

# Meson cross file location if cross compiling
ARG MESON_CROSS_FILE=/usr/local/share/meson/cross/dosbox-cross

RUN echo "Debian version is ${DEB_VERS}"

COPY ./debian-${DEB_VERS}-docker-apt.txt ${DOSBOX_APT_LIST}

# Install cross toolchain and generate meson 
# cross file using debcrossgen
RUN  mkdir -p $(dirname ${MESON_CROSS_FILE}) \
    && apt-get update \
    && apt-get -y install --no-install-recommends \
        meson \
        crossbuild-essential-${DPKG_ARCH} \
    && /usr/share/meson/debcrossgen --arch ${DPKG_ARCH} -o ${MESON_CROSS_FILE} \
    && apt-get -y remove meson \
    && apt-get -y autoremove \
    && rm -rf /var/lib/apt/lists/*

# Install DOSBox Staging dependencies using the appropriate architecture
RUN apt-get update \
    && apt-get -y install --no-install-recommends \
        $(sed 's/$/':${DPKG_ARCH}'/g' ${DOSBOX_APT_LIST}) \
    && rm -rf /var/lib/apt/lists/*

# Use the PyPI version of Meson instead of the potentially way out of date Debian version
RUN pip3 install meson

# Perform a couple of fixups
RUN DPKG_TRIPLET=$(dpkg-architecture -A ${DPKG_ARCH} -q DEB_TARGET_MULTIARCH); \
    QEMU_TRIPLET=$(echo $DPKG_TRIPLET | sed s/powerpc/ppc/g); \
    # Fixup meson cross file for qemu-user-static
    sed -i "2i exe_wrapper = '/usr/bin/qemu-${QEMU_TRIPLET%%-*}-static'" ${MESON_CROSS_FILE} \
    # Fix opusfile pkgconfig
    && sed 's@libdir=\${exec_prefix}/lib@libdir=\${prefix}/lib/'"${DPKG_TRIPLET}@g" \
        /usr/lib/pkgconfig/opusfile.pc > /usr/lib/${DPKG_TRIPLET}/pkgconfig/opusfile.pc

CMD [ "/bin/bash" ]
