#!/usr/bin/env bash

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

DEST=${1:-${HOME}/zephyr-sdk}
#DEST=${1:-${HOME}/.local/zephyr-sdk}

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:1}-linux-x86_64-setup.run
SDK_URL=https://github.com/${USER}/${PROJECT}/releases/download/${RELEASE}

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

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.sh
fi

#  'west' is the tool that manages the entire life-cycle of a Zephyr-based project.
echo "*** Getting zephyr source code ***"

west init ${HOME}/zephyrproject
cd ${HOME}/zephyrproject
west update
west espressif update

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

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

echo "Installing Zephyr’s toolchain."
#Zephyr’s SDK adds several additional tools for the host. Download the SDK installer:

cd ${HOME}
wget -O /var/tmp/${SDK_FILENAME} ${SDK_URL}/{SDK_FILENAME}

echo "Running the installer, this will install the SDK under the ${DEST}-${RELEASE:1} folder."
chmod +x /var/tmp/${SDK_FILENAME}
/var/tmp/${SDK_FILENAME} -- -d ${DEST}-${RELEASE:1}
