# Base image
FROM debian:bookworm-slim
ENV DEBIAN_FRONTEND=noninteractive
ENV LC_ALL=C.UTF-8
ENV LANG=C.UTF-8

# Arguments
ARG CONTAINER_USER=esp
ARG CONTAINER_GROUP=esp
ARG NIGHTLY_VERSION=nightly-2025-11-01

# Install dependencies
RUN apt-get update \
    && apt-get install -y \
        curl unzip git pkg-config gcc \
        libssl-dev libusb-1.0-0 libusb-1.0-0-dev libudev-dev \
        sudo \
    && apt-get clean -y \
    && rm -rf /var/lib/apt/lists/*

# Create non-root user
RUN adduser --disabled-password --gecos "" ${CONTAINER_USER}

# Allow esp to sync the dialout group GID at container start
RUN echo "${CONTAINER_USER} ALL=(root) NOPASSWD: /usr/sbin/groupadd, /usr/sbin/groupmod, /usr/sbin/usermod, /usr/bin/chmod" \
    >> /etc/sudoers.d/esp-dialout
USER ${CONTAINER_USER}
WORKDIR /home/${CONTAINER_USER}

# Install rustup + nightly toolchain with RISC-V target and rust-src component
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- \
    --default-toolchain ${NIGHTLY_VERSION} -y --profile minimal \
    --component rust-src,clippy,rustfmt \
    --target riscv32imac-unknown-none-elf

ENV PATH=${PATH}:$HOME/.cargo/bin

# Install espflash (flash + monitor tool)
RUN ARCH=$($HOME/.cargo/bin/rustup show | grep "Default host" | sed -e 's/.* //') && \
    curl -L "https://github.com/esp-rs/espflash/releases/latest/download/espflash-${ARCH}.zip" \
        -o "${HOME}/.cargo/bin/espflash.zip" && \
    unzip "${HOME}/.cargo/bin/espflash.zip" -d "${HOME}/.cargo/bin/" && \
    rm  "${HOME}/.cargo/bin/espflash.zip" && \
    chmod u+x "${HOME}/.cargo/bin/espflash"

# Install probe-rs (on-chip debugger, flashing, RTT)
RUN $HOME/.cargo/bin/cargo install probe-rs-tools --locked

CMD ["/bin/bash"]
