#!/bin/sh
set -e

orig_dir=$(pwd)
mkdir -p "$orig_dir/include/cmsis/m-profile"

temp_dir=$(mktemp -d)
cd "$temp_dir"

if command -v curl >/dev/null 2>&1; then
    curl -LO https://github.com/ARM-software/CMSIS_6/archive/refs/heads/main.zip
else
    wget -O main.zip https://github.com/ARM-software/CMSIS_6/archive/refs/heads/main.zip
fi

unzip main.zip
cmsis_dir=$(find . -maxdepth 1 -type d -name "CMSIS_6*" | head -n 1)

for file in core_cm4 cmsis_version cmsis_gcc cmsis_compiler; do
    cp "$cmsis_dir/CMSIS/Core/Include/$file.h" "$orig_dir/include/cmsis/"
done
for file in cmsis_gcc_m armv7m_cachel1 armv7m_mpu; do
    cp "$cmsis_dir/CMSIS/Core/Include/m-profile/$file.h" "$orig_dir/include/cmsis/m-profile/"
done

cd "$orig_dir"
rm -rf "$temp_dir"
echo "CMSIS files copied to ./include/cmsis/"
