#!/bin/sh
set -eu
ROOT='/Users/guman/Documents/Codex/2026-09-27/https-www-amazon-com-electric-drill/outputs/三款PCBA工程包-v1.39-2026-10-08'
WORK='/Users/guman/Documents/Codex/2026-09-27/https-www-amazon-com-electric-drill/work/tri-product-continuation-2026-10-10.nosync/drill_foc_target_probe_r1'
TARGET="$ROOT/固件/drill_target"
OUT="$WORK/build"
CC=${ARM_GCC:-arm-none-eabi-gcc}
OBJCOPY=${ARM_OBJCOPY:-arm-none-eabi-objcopy}
SIZE=${ARM_SIZE:-arm-none-eabi-size}
mkdir -p "$OUT"
FLAGS="-mcpu=cortex-m4 -mthumb -mfloat-abi=soft -DSTM32G431xx -std=c11 -Os -g3 -ffreestanding -fno-builtin -fno-common -ffunction-sections -fdata-sections -Wall -Wextra -Werror"
INCLUDES="-I$TARGET/Device/Include -I$ROOT/固件/lamp_target/CMSIS/Core/Include -I$ROOT/固件/lamp_target/include -I$ROOT/固件/drill_driver -I$TARGET/src"
$CC $FLAGS $INCLUDES -c "$TARGET/Device/Source/Templates/system_stm32g4xx.c" -o "$OUT/system.o"
$CC $FLAGS $INCLUDES -c "$TARGET/src/runtime.c" -o "$OUT/runtime.o"
$CC $FLAGS $INCLUDES -c "$WORK/drill_foc_probe_main.c" -o "$OUT/probe_main.o"
$CC $FLAGS $INCLUDES -c "$TARGET/src/drill_safe_gpio.c" -o "$OUT/drill_safe_gpio.o"
$CC $FLAGS $INCLUDES -c "$ROOT/固件/drill_driver/motor_foc.c" -o "$OUT/motor_foc.o"
$CC -mcpu=cortex-m4 -mthumb -mfloat-abi=soft -x assembler-with-cpp -c "$TARGET/startup/startup_stm32g431_minimal.s" -o "$OUT/startup.o"
$CC -mcpu=cortex-m4 -mthumb -mfloat-abi=soft -nostdlib -T "$TARGET/linker/stm32g431cb.ld" \
  -Wl,-Map="$OUT/drill_foc_probe.map",--cref,--build-id=none,--no-undefined,--gc-sections,--print-memory-usage -Wl,-z,noexecstack \
  "$OUT/startup.o" "$OUT/system.o" "$OUT/runtime.o" "$OUT/drill_safe_gpio.o" "$OUT/motor_foc.o" "$OUT/probe_main.o" -lgcc -o "$OUT/drill_foc_probe.elf"
$OBJCOPY -O binary "$OUT/drill_foc_probe.elf" "$OUT/drill_foc_probe.bin"
$SIZE "$OUT/drill_foc_probe.elf" > "$OUT/size.txt"
python3 "$WORK/verify_probe.py" "$OUT/drill_foc_probe.elf" "$OUT/drill_foc_probe.bin" "$OUT/drill_foc_probe.map" > "$OUT/build_verification.json"
cat "$OUT/build_verification.json"
