#!/bin/bash
set -e

echo "=== Starting full build (chunk_build, supports .skip) ==="

# Check required environment variables
: "${ARDUINO_IDE_PATH:?Error: ARDUINO_IDE_PATH not set}"
: "${ARDUINO_USR_PATH:?Error: ARDUINO_USR_PATH not set}"

echo "Arduino IDE: $ARDUINO_IDE_PATH"
echo "Arduino User: $ARDUINO_USR_PATH"
echo ""

BOARD="${BOARD:-01studio}"
FQBN="${FQBN:-Kendryte:K230:01studio:debug=off}"

echo "Build configuration:"
echo "  Board: $BOARD"
echo "  FQBN: $FQBN"
echo ""

# Ensure we're running next to sketch_utils.sh (you are in tools/untestd in CI)
chmod +x ./sketch_utils.sh

CHUNK_INDEX="${CHUNK_INDEX:-0}"
CHUNKS_CNT="${CHUNKS_CNT:-1}"

run_chunk_build() {
  local path="$1"
  if [ ! -d "$path" ]; then
    echo "Path not found, skip: $path"
    return 0
  fi

  echo ""
  echo "=== chunk_build path: $path ==="

  ./sketch_utils.sh chunk_build \
    -ai "$ARDUINO_IDE_PATH" -au "$ARDUINO_USR_PATH" \
    -b "$BOARD" -fqbn "$FQBN" \
    -p "$path" \
    -i "$CHUNK_INDEX" -m "$CHUNKS_CNT"
}

# 1) libraries 下所有 examples（会自动跳过含 .skip 的 sketch 目录）
run_chunk_build "$CI_PROJECT_DIR/libraries"

# 2) tests 下的 sketches（如果有）
run_chunk_build "$CI_PROJECT_DIR/tests"

echo ""
echo "=== Full build finished ==="
