FROM ubuntu:22.04

ARG     user=igib
ENV     TERM xterm-256color

        # Setup frontend as non-interactive.
RUN     ln -snf /usr/share/zoneinfo/Europe/Zurich /etc/localtime && \
        echo Europe/Zurich > /etc/timezone &&   \
        echo 'debconf debconf/frontend select Noninteractive' | debconf-set-selections

        # Install dependencies for Zephyr OS build system
RUN     apt-get update && apt-get install --no-install-recommends -y git cmake ninja-build gperf tar \
        ccache dfu-util device-tree-compiler wget python3-dev python3-pip python3-setuptools python3-tk \ 
        python3-wheel xz-utils file make gcc gcc-multilib g++-multilib libsdl2-dev libmagic1 python3-venv 

RUN     apt-get install --no-install-recommends -y automake autoconf build-essential texinfo libtool libftdi-dev libusb-1.0-0-dev pkg-config

        # Add user
RUN     useradd -ms /bin/bash ${user} -G sudo && \
        echo "${user}:${user}" | chpasswd && \
        echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers

        # Install Zephyr SDK
RUN     cd /opt && \
        wget https://github.com/zephyrproject-rtos/sdk-ng/releases/download/v0.16.4/zephyr-sdk-0.16.4_linux-x86_64.tar.xz && \
        wget -O - https://github.com/zephyrproject-rtos/sdk-ng/releases/download/v0.16.4/sha256.sum | shasum --check --ignore-missing && \
        tar xvf zephyr-sdk-0.16.4_linux-x86_64.tar.xz

RUN     cd /opt/zephyr-sdk-0.16.4 && ./setup.sh -t all -c && rm /opt/zephyr-sdk-0.16.4_linux-x86_64.tar.xz

USER    ${user}
ENV     HOME=/home/${user}
ENV     ZEPHYR_BASE=/mnt/zephyrproject/zephyr

        # Add python packages requirements files
ADD     zephyrproject/zephyr/scripts/*.txt ${HOME}

SHELL ["/bin/bash", "-c"]
        # Create venv for zephyr 
RUN     cd /home/${user} && python3 -m venv .zephyr-venv && \
        source .zephyr-venv/bin/activate && pip install west \
        pip install -r requirements.txt && rm *.txt
SHELL ["/bin/sh", "-c"]
        
        # Install OpenOCD
RUN     cd ${HOME} && git clone https://github.com/raspberrypi/openocd.git --branch rp2040-v0.12.0 --depth=1 --no-single-branch && \
        cd openocd && ./bootstrap && ./configure && make -j4

USER    root
RUN     cd /home/${user}/openocd && make install && usermod -aG plugdev ${user}

USER    ${user}


WORKDIR /mnt
CMD bash -c 'source ~/.zephyr-venv/bin/activate; bash'
# ENTRYPOINT [ "/bin/bash" ]