# Cross image for Rust target m68k-unknown-linux-gnu (glibc, static)
FROM debian:trixie-slim

# Pull unstable repos.
RUN echo 'deb [trusted=yes] http://ftp.debian.org/debian sid main' > /etc/apt/sources.list.d/sid.list && \
    echo 'deb [trusted=yes] http://ftp.ports.debian.org/debian-ports sid main' > /etc/apt/sources.list.d/ports.list

# Base toolchain & build utils
RUN apt-get update && apt-get install -y --no-install-recommends \
    ca-certificates gnupg curl wget file rsync git pkg-config gperf bc \
    build-essential make gettext gawk bison flex texinfo autoconf automake libtool \
    python3 \
    binutils-m68k-linux-gnu gcc-m68k-linux-gnu \
    linux-libc-dev-m68k-cross \
 && rm -rf /var/lib/apt/lists/*

# Private sysroot where we install a *static*, generic glibc (no ifunc/asm fast paths)
ENV SYSROOT=/opt/m68k-generic
RUN mkdir -p ${SYSROOT}/usr/include && rsync -a /usr/m68k-linux-gnu/include/ ${SYSROOT}/usr/include/

WORKDIR /tmp

# Get glibc latest stable release.
ENV GLIBC_VER=2.42
RUN wget https://ftp.gnu.org/gnu/libc/glibc-${GLIBC_VER}.tar.xz && \
    tar -xf glibc-${GLIBC_VER}.tar.xz && \
    mkdir -p /tmp/glibc-build

WORKDIR /tmp/glibc-build

# Configure for cross, make sure host helpers use host compilers
# Disable multi-arch/ifunc to avoid arch-specific memcpy/memmove
RUN cat >/tmp/glibc-build/configparms <<'EOF'
CC_FOR_BUILD = gcc
CXX_FOR_BUILD = g++
BUILD_CC = gcc
BUILD_CXX = g++
CXX =
GLIBC_CFLAGS = -O0 -pipe -mstrict-align -fno-builtin -fno-lto
EOF

RUN CC=m68k-linux-gnu-gcc \
    AR=m68k-linux-gnu-ar \
    RANLIB=m68k-linux-gnu-ranlib \
    AS=m68k-linux-gnu-as \
    LD=m68k-linux-gnu-ld.bfd \
    ../glibc-${GLIBC_VER}/configure \
      --host=m68k-linux-gnu \
      --build=$(../glibc-${GLIBC_VER}/scripts/config.guess) \
      --prefix=/usr \
      --with-headers=${SYSROOT}/usr/include \
      --disable-werror \
      --disable-multi-arch \
      --disable-ifunc \
      --enable-kernel=3.2.0

# Build glibc.
RUN make -j$(nproc) && make install DESTDIR=${SYSROOT}

# libseccomp (static) against cross toolchain.
WORKDIR /tmp
RUN wget https://github.com/seccomp/libseccomp/releases/download/v2.6.0/libseccomp-2.6.0.tar.gz
RUN tar -xzf libseccomp-2.6.0.tar.gz && \
    cd libseccomp-2.6.0 && \
    env \
      CC=m68k-linux-gnu-gcc \
      AR=m68k-linux-gnu-ar \
      RANLIB=m68k-linux-gnu-ranlib \
      CFLAGS="--sysroot=${SYSROOT} -O0 -pipe -mstrict-align -fno-builtin -fno-lto" \
      LDFLAGS="--sysroot=${SYSROOT} -static" \
      ./configure --host=m68k-linux-gnu --prefix=/usr/m68k-linux-gnu && \
    make -j$(nproc) && \
    make install DESTDIR="${SYSROOT}"
