#!/usr/bin/env bash
set -Eeuo pipefail

echo "== ci/build.sh =="

export CI_PROJECT_DIR="${CI_PROJECT_DIR:-$(pwd)}"
export HOME="${HOME:-/root}"

# ---- GitHub compatible vars: prevent unbound in install scripts ----
export GITHUB_WORKSPACE="${GITHUB_WORKSPACE:-$CI_PROJECT_DIR}"
export GITHUB_REPOSITORY="${GITHUB_REPOSITORY:-${CI_PROJECT_PATH:-unknown/unknown}}"
export GITHUB_REF="${GITHUB_REF:-${CI_COMMIT_REF_NAME:-}}"
export GITHUB_SHA="${GITHUB_SHA:-${CI_COMMIT_SHA:-}}"
export GITHUB_EVENT_NAME="${GITHUB_EVENT_NAME:-gitlab}"
export GITHUB_EVENT_PATH="${GITHUB_EVENT_PATH:-/dev/null}"

# ---- OS flags expected by install scripts ----
# IMPORTANT: linux runner => OS_IS_LINUX must be 1
: "${OS_IS_WINDOWS:=0}"
: "${OS_IS_MACOS:=0}"
: "${OS_IS_LINUX:=1}"
export OS_IS_WINDOWS OS_IS_MACOS OS_IS_LINUX

BOARD="${BOARD:-01studio}"
FQBN="${FQBN:-Kendryte:K230:01studio:debug=off}"
MODE="${MODE:-incremental}"   # incremental | full

cd "${CI_PROJECT_DIR}/tools/untestd"
chmod +x *.sh || true

bash gitlab-ci-env-check.sh

# 先 bootstrap（补齐变量 + 生成 repo get_enhanced.py + 导出函数）
source "${CI_PROJECT_DIR}/ci/bootstrap.sh"

# 再安装（这些脚本内部引用 OS_IS_* / GITHUB_*，现在不会 unbound）
source ./install-arduino-ide.sh
source ./install-arduino-core-k230.sh
source ./install-arduino-library.sh

# core install 完之后再 patch core get.py + toolchain path
patch_core_get_py
setup_toolchain_path_and_links

echo "Build mode: $MODE  board=$BOARD fqbn=$FQBN"

export BOARD FQBN

if [ "$MODE" = "full" ]; then
  SAVED_ARDUINO_BUILD_DIR="${ARDUINO_BUILD_DIR:-}"
  unset ARDUINO_BUILD_DIR
  bash build-all-sketches.sh
  rc=$?
  if [ -n "${SAVED_ARDUINO_BUILD_DIR}" ]; then export ARDUINO_BUILD_DIR="${SAVED_ARDUINO_BUILD_DIR}"; fi
  exit $rc
else
  bash incremental-build.sh
fi

echo "OK: build done"
