#!/usr/bin/env bash

# https://www.zephyrproject.org/zephyr-rtos-on-esp32/
# https://zmk.dev/docs/development/setup/

## build basic blinky
# BOARD_NAME=esp32s3_devkitm
# cd ~/zephyrproject/zephyr
# west build -p always -b ${BOARD_NAME} samples/basic/blinky

# Manual flash instructions https://github.com/seemoo-lab/openhaystack/wiki/Flashing-nRF-with-OpenOCD---ST-Link
openocd \
  -f ${ZEPHYR_SDK_INSTALL_DIR}/sysroots/${MACHINE}-pokysdk-linux/usr/share/openocd/scripts/interface/stlink.cfg \
  -f ${ZEPHYR_SDK_INSTALL_DIR}/sysroots/${MACHINE}-pokysdk-linux/usr/share/openocd/scripts/target/nrf51.cfg
#
# $ telnet localhost 4444
# $ help
#
# You can backup the existing firmware:
# $ dump_image /Your/File/Path/flash.bin 0 0x40000
# $ dump_image /tmp/zephyr-shell_flash.bin 0 0x40000
#
# Erase the flash using
# $ nrf5 mass_erase

# Verify and program your device by using (use the .bin not .hex file)
# $ program /your/path/to/the/firmware.bin verify
# $ program /your/path/to/the/firmware.bin
#
# $ program /home/default/zephyrproject/zephyr/build/zephyr/zephyr.bin verify
# $ program /home/default/zephyrproject/zephyr/build/zephyr/zephyr.bin
#
# $ program /tmp/zephyr-shell_flash.bin verify
# $ program /tmp/zephyr-shell_flash.bin
#
# openocd \
#    -f ${ZEPHYR_SDK_INSTALL_DIR}/sysroots/${MACHINE}-pokysdk-linux/usr/share/openocd/scripts/interface/stlink.cfg \
#    -f ${ZEPHYR_SDK_INSTALL_DIR}/sysroots/${MACHINE}-pokysdk-linux/usr/share/openocd/scripts/target/nrf51.cfg \
#    -c init \
#    -c "reset halt" \
#    -c "nrf51 mass_erase" \
#    -c "program build/zephyr/zephyr.hex verify reset" \
#    -c exit

DEST=${1:-${HOME}}

ARCH=$(dpkg --print-architecture)
MACHINE=$(uname -m)
PYTHON_VERSION='3.12.4'

# zephyr version
# ZEPHYR_VERSION=$(lastversion --format tag zephyr)  # 3.7.0
ZEPHYR_VERSION='v3.5.0' # zmk lags https://zmk.dev/blog

# sdk version
USER=zephyrproject-rtos
PROJECT=sdk-ng
API_URL=https://api.github.com/repos/${USER}/${PROJECT}/releases/latest
RELEASE=$(curl -s ${API_URL} | grep tarball_url | cut -d '"' -f 4 | awk -F "/" {'print $8'})
SDK_FILENAME=zephyr-sdk-${RELEASE#v}_linux-${MACHINE}_minimal.tar.xz # 41.8 MB
# SDK_FILENAME=zephyr-sdk-${RELEASE#v}_linux-${MACHINE}.tar.xz            # 1.35 GB
SDK_URL=https://github.com/${USER}/${PROJECT}/releases/download/${RELEASE}

# fetch the sdk
wget -c ${SDK_URL}/${SDK_FILENAME}
wget -c -O - ${SDK_URL}/sha256.sum | shasum --check --ignore-missing

SDK_DEST=${DEST}/zephyr-sdk-${RELEASE#v}
PROJECT_DEST=${DEST}/zephyrproject

mkdir -p ${SDK_DEST}
mkdir -p ${PROJECT_DEST}

# unpack the sdk
tar xvf ${SDK_FILENAME}

# https://docs.zephyrproject.org/latest/develop/env_vars.html#env-vars-important
ZEPHYR_ENV_FILE="${HOME}/.zshrc.d/001_zephyr.zsh"
cat <<-EOF | tee ${ZEPHYR_ENV_FILE}
# zephyr specific
export MACHINE=$(uname -m)
export ZEPHYR_TOOLCHAIN_VARIANT=zephyr
export ZEPHYR_SDK_INSTALL_DIR="${SDK_DEST}"

EOF

RSS_FEED="https://github.com/${USER}/${PROJECT}/releases.atom"
# xdg-open ${RSS_FEED}
echo ${RSS_FEED}

echo "*** Installing dependencies. ***"
sudo apt-get update

sudo apt install --no-install-recommends -y autoconf automake \
  build-essential bzip2 ccache coccinelle cmake device-tree-compiler dfu-util \
  git gperf gcc g++ gcc-multilib g++-multilib libsdl2-dev libtool python3-dev \
  python3-pip python3-setuptools python3-tk python3-wheel ninja-build file make \
  wget xz-utils

echo "*** Getting Zephyr and installing Python dependencies. ***"
# Install west and ensure that ${HOME}/.local/bin is part of your PATH environment variable:

# echo "*** Installing west with pip3 ***"
# pip3 install -U --user west
# echo 'export PATH=${HOME}/.local/bin:”$PATH”' >>${HOME}/.bashrc

# if [[ -d ${HOME}/.zshrc.d ]]; then
# 	echo 'export PATH=${HOME}/.local/bin:"$PATH"' >>${HOME}/.zshrc.d/001_dot_local_path.zsh
# fi

# ensure a conda env exists for zephyr python requirements
if which conda >/dev/null 2>&1; then
  echo "Conda is already installed."
else
  echo "Conda is not installed. Installing..."
  bash /var/tmp/automate/020_conda.sh ${HOME}
fi

. /opt/conda/etc/profile.d/conda.sh

# https://www.nordicsemi.com/Products/Development-tools/nRF-Command-Line-Tools/Download?lang=en#infotabs
# https://nsscprodmedia.blob.core.windows.net/prod/software-and-other-downloads/desktop-software/nrf-command-line-tools/sw/versions-10-x-x/10-24-2/nrf-command-line-tools_10.24.2_amd64.deb
# py -3 -m pip install --pre -U git+https://github.com/makerdiary/uf2utils.git@main

if [[ ! -d "${HOME}/.conda/envs/zephyr" ]]; then
  echo "Creating the zephyr environment with conda."
  conda create -n zephyr python=${PYTHON_VERSION}
  conda activate zephyr
  pip install --no-input west pynrfjprog dtsh
  echo "Zephyr environment created successfully."
else
  echo "Zephyr environment already exists."
fi

# Create west configuation file.
cat <<EOF | tee ${HOME}/.westconfig
[zephyr]
# base-prefer = configfile

[build]
# pristine = auto
#board = nrf52840dk/nrf52840
#dir-fmt = build/\${board}
#guess-dir = runners
EOF

echo "Installing Zephyr's toolchain."
#Zephyr's SDK adds several additional tools for the host. Download the SDK installer:
# use the sdk setup script to add the target toolchains and the host tools.

#  'west' is the tool that manages the entire life-cycle of a Zephyr-based project.
# west init -m https://github.com/zephyrproject-rtos/zephyr --mr v2.5.0 zephyrproject

echo "*** Getting zephyr source code ***"

# Move into the conda venv
conda activate zephyr
west init -m https://github.com/${USER}/zephyr --mr ${ZEPHYR_VERSION} ${PROJECT_DEST}

pushd ${PROJECT_DEST}/zephyr
# enable autoswitching with zsh-autoswitch-conda (use echo not mkcenv)
echo zephyr >.cenv
# sed -i '|\.venv|a|\.cenv' .gitignore
sed -i '/\.venv/a\.cenv' .gitignore

west update
conda deactivate
popd

pushd ${ZEPHYR_SDK_INSTALL_DIR}

# enable autoswitching with zsh-autoswitch-conda (use echo not mkcenv)
echo zephyr >.cenv
# sed -i '|\.venv|a|\.cenv' .gitignore
sed -i '/\.venv/a\.cenv' .gitignore

conda activate zephyr
bash ./setup.sh
# bash ./setup.sh -t x86_64-zephyr-elf
bash ./setup.sh -t arm-zephyr-eabi
bash ./setup.sh -t xtensa-espressif_esp32_zephyr-elf
bash ./setup.sh -t xtensa-espressif_esp32s3_zephyr-elf
bash ./setup.sh -h
popd

# install udev rules
sudo cp ~/zephyr-sdk-${RELEASE#v}/sysroots/x86_64-pokysdk-linux/usr/share/openocd/contrib/60-openocd.rules /etc/udev/rules.d
sudo udevadm control --reload

# add 'west' completion to zsh - use /usr/share/when packaging for debian
COMPLETION_FILE="/usr/share/zsh/site-functions/_west"
COMPLETION_FILE="${HOME}/.zshrc.d/001_west-completion.zsh"
west completion zsh >${COMPLETION_FILE}

echo "Exporting a Zephyr CMake package."
west zephyr-export

echo "Installing additional python dependencies via pip3."
pip install -r \
  ${HOME}/zephyrproject/zephyr/scripts/requirements.txt

conda deactivate
