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
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 stage-tipote/ /build/pi-gen/stage-tipote/

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

# Patch pi-gen for Docker Desktop compatibility:
# 1. Remove setarch linux32 calls (fails on Docker Desktop)
# 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

CMD ["bash", "-c", "modprobe binfmt_misc 2>/dev/null || true && mount -t binfmt_misc binfmt_misc /proc/sys/fs/binfmt_misc 2>/dev/null || true && cd /build/pi-gen && ./build.sh && mkdir -p /output && cp deploy/*.img.xz /output/ 2>/dev/null || cp deploy/*.img /output/ 2>/dev/null && ls -lh /output/"]
