# This is a modified copy of https://github.com/msys2/msys2-docker
# Changes:
# - Re-enabled MSYS2 signature checks
FROM ghcr.io/msys2/msys2-docker-build-base AS build

# Install MSYS2
RUN apt update && apt install -y zstd curl
RUN mkdir -p /tmp/msys64
RUN curl --fail -L 'https://github.com/msys2/msys2-installer/releases/download/nightly-x86_64/msys2-base-x86_64-latest.tar.zst' | tar -x --zstd -C /tmp/ --no-same-owner

FROM debian:bookworm

# Copy over wine and install the runtime deps
RUN apt update \
    && apt install -y --no-install-recommends xvfb wine64 xauth \
    && apt remove -y wine64 libwine \
    && rm -rf /var/lib/apt/lists/*
COPY --from=build /wine /
RUN ldconfig

# XXX: otherwise things hang
RUN winecfg

# Copy over MSYS2
COPY --from=build /tmp/msys64 /root/.wine/drive_c/msys64

RUN echo 'Server = https://repo.msys2.org/msys/$arch/' > /root/.wine/drive_c/msys64/etc/pacman.d/mirrorlist.msys
RUN echo 'Server = https://repo.msys2.org/mingw/$repo/' > /root/.wine/drive_c/msys64/etc/pacman.d/mirrorlist.mingw

# Disable space checks to speed up package installation
RUN sed -i /root/.wine/drive_c/msys64/etc/pacman.conf -e 's/^CheckSpace/#CheckSpace/g'

COPY containers/windows/x86_64/msys2 /usr/bin/msys2
RUN chmod +x /usr/bin/msys2

# Run for the first time
RUN msys2 -c " "

WORKDIR /root/.wine/drive_c/msys64/home/root
CMD ["msys2"]

# Wonderful toolchain additions
## Install dependencies
RUN msys2 -c "pacman.exe -Sy --noconfirm mingw-w64-ucrt-x86_64-ca-certificates mingw-w64-ucrt-x86_64-python mingw-w64-ucrt-x86_64-python-uv autoconf autoconf-archive automake base-devel bison flex git libtool lld mingw-w64-ucrt-x86_64-autotools mingw-w64-ucrt-x86_64-cmake mingw-w64-ucrt-x86_64-lua-luarocks mingw-w64-ucrt-x86_64-meson mingw-w64-ucrt-x86_64-toolchain nasm ninja"
## Configure package build environment
COPY misc/windows/makepkg.conf /root/.wine/drive_c/msys64/etc
RUN ln -s /wf /root/.wine/drive_c/msys64/wf
RUN sed -E -i -e "s/-pacman/-\/opt\/wonderful\/bin\/wf-pacman.exe/g" /root/.wine/drive_c/msys64/usr/bin/makepkg
## Install Wonderful
RUN mkdir -p /root/.wine/drive_c/msys64/opt/wonderful/
ADD https://wonderful.asie.pl/bootstrap/wf-bootstrap-windows-x86_64.tar.gz /root/.wine/drive_c/msys64/opt/wonderful/
RUN cd /root/.wine/drive_c/msys64/opt/wonderful/ && \
    tar xzf wf-bootstrap-windows-x86_64.tar.gz --no-same-owner && \
    rm wf-bootstrap-windows-x86_64.tar.gz
RUN msys2 -c "/opt/wonderful/bin/wf-pacman.exe -Syu --noconfirm"
