FROM ubuntu:24.04

ENV DEBIAN_FRONTEND=noninteractive

# Install pi-gen dependencies
RUN apt-get update && apt-get install -y \
  git coreutils quilt parted \
  debootstrap zerofree zip dosfstools \
  libarchive-tools libcap2-bin grep rsync xz-utils \
  file binfmt-support qemu-user-static \
  pigz arch-test \
  curl bc xxd kmod \
  && rm -rf /var/lib/apt/lists/*

WORKDIR /build

# Clone pi-gen (bookworm branch for Raspberry Pi OS stable)
RUN git clone --depth 1 --branch bookworm https://github.com/RPi-Distro/pi-gen.git /build/pi-gen

# Copy config and stage
COPY config /build/pi-gen/config
COPY stage3/ /build/pi-gen/stage3/

# Skip stage2 image export (we export from stage3)
RUN touch /build/pi-gen/stage2/SKIP_IMAGES

# Patch pi-gen for Docker compatibility:
# 1. Remove setarch linux32 calls (fails on some Docker setups)
# 2. Remove qemu-user-binfmt from dependency check (conflicts with qemu-user-static)
RUN find /build/pi-gen -name "*.sh" -exec sed -i 's/setarch linux32 //g' {} + 2>/dev/null || true \
  && sed -i '/qemu-user-binfmt/d' /build/pi-gen/depends

COPY entrypoint.sh /build/entrypoint.sh
RUN chmod +x /build/entrypoint.sh

CMD ["/build/entrypoint.sh"]
