#!/bin/bash

SCRIPT_DIR="$(cd "$(dirname "$(readlink -f "$0")")" && pwd)"
PROJECT_PATH="$(cd "$SCRIPT_DIR/.." && pwd)"

# Default values that can be overridden by environment variables
# The ':=' operator means "use the environment variable if set, otherwise use this default"
: "${BOARD_FQBN:=esp32:esp32:esp32s3usbotg:USBMode=hwcdc}"
: "${LIBRARY_PATH:=$PROJECT_PATH}"
: "${BUILD_PATH:=$PROJECT_PATH/build}"
: "${BASE_INO_SKETCH_PATH:=$PROJECT_PATH/example/start}"
: "${COMPILE_COMMANDS:=compile_commands.json}"


mkdir -p "$BUILD_PATH"

if ! command -v arduino-cli >/dev/null 2>&1; then
    echo "Error: arduino-cli is not installed or not in PATH"
    echo "Please install it from https://arduino.github.io/arduino-cli/latest/installation/"
    exit 1
fi

echo "Generating clangd configuration for $BOARD_FQBN in $BUILD_PATH"
echo "Based on compilation of $BASE_INO_SKETCH_PATH"
echo "This may take a while and will not produce any output until it's done."
echo "Please be patient..."

if ! arduino-cli compile \
    --fqbn "$BOARD_FQBN" \
    --library "$LIBRARY_PATH" \
    --only-compilation-database \
    --build-path "$BUILD_PATH" \
    "$BASE_INO_SKETCH_PATH"; then
    echo "Error: Failed to generate compilation database"
    exit 1
fi

# Create symbolic link with error handling
if [ -f "$BUILD_PATH/$COMPILE_COMMANDS" ]; then
    ln -sf "$BUILD_PATH/$COMPILE_COMMANDS" "$PROJECT_PATH/$COMPILE_COMMANDS"
    echo "Successfully placed clangd configuration in project root"
    echo "You no longer have to use the Arduino IDE for code completion \o/"
    echo "Feel free to use any editor that supports clangd (e.g via LSP)"
    echo "For example, Visual Studio Code with the 'clangd' extension, or VIM (with YouCompleteMe), or Emacs (with Eglot), or ..."
    echo "Refer to https://clangd.llvm.org/installation#editor-plugins for more information"

else
    echo "Error: Could not link \"complile_commands.json\" to the root directory. Please manually copy where needed."
    exit 1
fi
