# QMK Firmware Build Environment
# Based on Ubuntu 22.04 for stability and compatibility

FROM ubuntu:22.04

# Set environment variables
ENV DEBIAN_FRONTEND=noninteractive
ENV QMK_HOME=/qmk_firmware
ENV PATH="/root/.local/bin:$PATH"

# Install system dependencies
RUN apt-get update && apt-get install -y \
    build-essential \
    clang-format \
    dfu-programmer \
    dfu-util \
    git \
    libnewlib-arm-none-eabi \
    nodejs \
    python3 \
    python3-pip \
    python3-setuptools \
    python3-wheel \
    wget \
    unzip \
    && rm -rf /var/lib/apt/lists/*

# Install ARM toolchain
RUN wget -qO- https://developer.arm.com/-/media/Files/downloads/gnu-rm/10.3-2021.10/gcc-arm-none-eabi-10.3-2021.10-x86_64-linux.tar.bz2 | tar xj -C /opt \
    && ln -s /opt/gcc-arm-none-eabi-10.3-2021.10/bin/* /usr/local/bin/

# Install AVR toolchain
RUN wget -qO- https://downloads.arduino.cc/arduino-1.8.19-linux64.tar.xz | tar xJ -C /opt \
    && ln -s /opt/arduino-1.8.19/hardware/tools/avr/bin/* /usr/local/bin/

# Set up QMK environment
WORKDIR /workspace
RUN git clone --depth 1 https://github.com/qmk/qmk_firmware.git $QMK_HOME

# Install QMK CLI and Python dependencies
RUN pip3 install --user qmk
RUN pip3 install --user -r $QMK_HOME/requirements.txt

# Set up QMK
RUN qmk setup --yes

# Create build directory
RUN mkdir -p /workspace/build

# Set working directory
WORKDIR /workspace

# Copy entrypoint script
COPY <<EOF /usr/local/bin/entrypoint.sh
#!/bin/bash
set -e

# Initialize git submodules if they exist
if [ -f ".gitmodules" ]; then
    git submodule update --init --recursive
fi

# Set up user keymaps
USER=\${USER:-dgvigil}

# Clean up old symlinks
rm -rf $QMK_HOME/keyboards/draculad/keymaps/\$USER 2>/dev/null || true
rm -rf $QMK_HOME/keyboards/keebio/iris/keymaps/\$USER 2>/dev/null || true
rm -rf $QMK_HOME/keyboards/handwired/scottokeebs/scottogame/keymaps/\$USER 2>/dev/null || true
rm -rf $QMK_HOME/keyboards/bluebell/swoop/keymaps/\$USER 2>/dev/null || true
rm -rf $QMK_HOME/keyboards/ferris/keymaps/\$USER 2>/dev/null || true
rm -rf $QMK_HOME/users/\$USER 2>/dev/null || true

# Create symlinks for keymaps
if [ -d "draculad" ]; then
    ln -s /workspace/draculad/ $QMK_HOME/keyboards/draculad/keymaps/\$USER
fi

if [ -d "iris" ]; then
    ln -s /workspace/iris/ $QMK_HOME/keyboards/keebio/iris/keymaps/\$USER
fi

if [ -d "sweep" ]; then
    ln -s /workspace/sweep/ $QMK_HOME/keyboards/ferris/keymaps/\$USER
fi

if [ -d "scottogame" ]; then
    ln -s /workspace/scottogame/ $QMK_HOME/keyboards/handwired/scottokeebs/scottogame/keymaps/\$USER
fi

if [ -d "swoop" ]; then
    ln -s /workspace/swoop/ $QMK_HOME/keyboards/bluebell/swoop/keymaps/\$USER
fi

if [ -d "user" ]; then
    ln -s /workspace/user/ $QMK_HOME/users/\$USER
fi

# Execute the command passed to the container
exec "\$@"
EOF

RUN chmod +x /usr/local/bin/entrypoint.sh

# Set entrypoint
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]

# Default command
CMD ["bash"] 