FROM debian:trixie AS base

# build-deps for gcc & pypy
RUN apt update && \
    apt upgrade -y && \
    apt install -y \
        build-essential libgmp-dev libisl-dev libmpc-dev libmpfr-dev \
        pkgconf libffi-dev

# headers for libc stuff (so compiled programs can use them)
# (libstdc++ not needed, that's built by gcc)
# and runtime deps for gcc/pypy inside the chroot
RUN mkdir /chroot /work /work/debs
WORKDIR /work/debs
RUN apt download libc6 libc6-dev linux-libc-dev libgmp10 libisl23 libmpc3 libmpfr6 libffi8 && \
    for x in *.deb; do dpkg-deb -x $x /chroot; done
# dpkg-deb explicitly warns against doing this, but i checked and the postinst
# scripts don't do anything important for these packages :)


RUN mkdir /work/gccsrc /work/gccobj
WORKDIR /work/gccsrc
RUN --mount=source=tarballs,dst=/tarballs \
    tar xf /tarballs/binutils-*.tar.xz --strip-components=1 && \
    rm -r gprof gprofng && \
    tar xf /tarballs/gcc-*.tar.xz --strip-components=1

WORKDIR /work/gccobj
RUN ../gccsrc/configure \
    --disable-bootstrap \
    --without-zstd --without-debuginfod \
    --enable-languages=c,c++ \
    --disable-lto --disable-multilib \
    --disable-libsanitizer --disable-libgomp --disable-gcov \
    --disable-nls \
    --enable-shared=libstdc++,libgcc \
    --disable-install-libbfd

RUN make -j4
RUN make DESTDIR=/chroot install-strip

COPY <<EOF /chroot/etc/ld.so.conf
include /etc/ld.so.conf.d/*.conf
/usr/local/lib64
EOF
RUN ldconfig -r /chroot

RUN rm -r /chroot/usr/local/share/man /chroot/usr/local/share/info


RUN --mount=source=tarballs,dst=/tarballs \
    tar xf /tarballs/pypy2.7-*-linux64.tar.gz --one-top-level=/work/pypy2 --strip-components=1 && \
    tar xf /tarballs/pypy*-src.tar.gz --one-top-level=/work/pypysrc --strip-components=1

WORKDIR /work/pypysrc/pypy/goal
# bz2 and zlib we want to get rid of; _minimal_curses and pyexpat are just
# useless and i didn't bother grabbing their build-deps
RUN /work/pypy2/bin/pypy ../../rpython/bin/rpython --opt=jit targetpypystandalone.py \
    --withoutmod-bz2 --withoutmod-zlib --withoutmod-_minimal_curses --withoutmod-pyexpat
# without-cffi is fine; the previous step already precompiled all the cffi that
# actually works, and package.py still installs those
RUN /work/pypy2/bin/pypy ../tool/release/package.py \
    --without-cffi --no-keep-debug \
    --archive-name pypy --targetdir . && \
    mkdir /chroot/pypy && \
    tar xf pypy.tar.gz -C /chroot/pypy --strip-components=1

# remove some cruft
WORKDIR /chroot/pypy/lib/pypy3.11
RUN rm -r test ensurepip _pypy_openssl.c */test */tests

RUN ln -s ../../../pypy/bin/pypy /chroot/usr/local/bin/pypy3


# setup some of a merged-usr system
RUN ln -s usr/lib64 /chroot/lib64 && \
    ln -s usr/lib /chroot/lib

FROM scratch
COPY --from=base /chroot /
