FROM archlinux:base-devel

# Update system and install required packages
RUN pacman -Syu --noconfirm && \
    pacman -S --noconfirm --needed \
        git \
        fakeroot \
        binutils \
        debugedit \
        sudo

# Create build user with proper permissions
RUN useradd -m -s /bin/bash builder && \
    echo "builder ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers.d/builder && \
    chmod 440 /etc/sudoers.d/builder

# Initialize pacman keyring
RUN pacman-key --init && \
    pacman-key --populate archlinux

# Configure makepkg for parallel builds and output location
RUN sed -i 's/^#MAKEFLAGS=.*/MAKEFLAGS="-j$(nproc)"/' /etc/makepkg.conf && \
    sed -i 's|^#PKGDEST=.*|PKGDEST=/pkgdest|' /etc/makepkg.conf && \
    sed -i 's|^#SRCDEST=.*|SRCDEST=/build/sources|' /etc/makepkg.conf

# Configure pacman for non-interactive use (NoProgressBar shows text output instead of terminal progress bars)
RUN sed -i '/^\[options\]/a NoProgressBar' /etc/pacman.conf && \
    sed -i '/^\[options\]/a VerbosePkgLists' /etc/pacman.conf

# Add local repository to pacman.conf (for AUR dependencies we've already built)
RUN echo -e "\n[aur]\nSigLevel = Optional TrustAll\nServer = file:///repo" >> /etc/pacman.conf

# Create directories
RUN mkdir -p /build /build/sources /pkgdest /repo && \
    chown -R builder:builder /build /pkgdest

USER builder
WORKDIR /build

# Default command: sync repos and build
CMD ["bash", "-c", "sudo pacman -Sy --noconfirm && makepkg -s --noconfirm --needed"]
