#!/bin/bash

# Script to build for all supported board configurations
# This script temporarily modifies board_config.h to build each variant

set -e  # Exit on error

PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BOARD_CONFIG="${PROJECT_DIR}/board_config.h"
BOARD_CONFIG_BACKUP="${BOARD_CONFIG}.backup"

# Define board configurations as parallel arrays (compatible with Bash 3.2+)
BOARD_NAMES=("feather_tft" "pico2_tft" "pico2_eink")
BOARD_DEFINES=("BOARD_FEATHER_TFT" "BOARD_PICO2_TFT" "BOARD_PICO2_EINK")

echo "Building for all supported board configurations..."
echo "Note: This will temporarily modify board_config.h"
echo ""

# Backup original board_config.h
cp "${BOARD_CONFIG}" "${BOARD_CONFIG_BACKUP}"
echo "✓ Backed up board_config.h"

# Function to restore on exit
cleanup() {
    echo ""
    echo "Restoring original board_config.h..."
    mv "${BOARD_CONFIG_BACKUP}" "${BOARD_CONFIG}"
}
trap cleanup EXIT

# Loop through boards
for i in "${!BOARD_NAMES[@]}"; do
    BOARD_NAME="${BOARD_NAMES[$i]}"
    BOARD_DEFINE="${BOARD_DEFINES[$i]}"
    
    echo ""
    echo "========================================"
    echo "Building for: ${BOARD_NAME}"
    echo "Using config: ${BOARD_DEFINE}"
    echo "========================================"
    
    # Restore backup
    cp "${BOARD_CONFIG_BACKUP}" "${BOARD_CONFIG}"
    
    # Comment out all board defines and uncomment the target one
    sed -i.tmp "s/^#define BOARD_/\/\/ #define BOARD_/g" "${BOARD_CONFIG}"
    sed -i.tmp "s/^\/\/ #define ${BOARD_DEFINE}/#define ${BOARD_DEFINE}/g" "${BOARD_CONFIG}"
    rm -f "${BOARD_CONFIG}.tmp"
    
    echo "✓ Modified board_config.h for ${BOARD_NAME}"
    
    # Build directory for this board
    BUILD_DIR="build_${BOARD_NAME}"
    
    # Clean and create build directory
    rm -rf "$BUILD_DIR"
    mkdir "$BUILD_DIR"
    cd "$BUILD_DIR"
    
    # Configure and build
    cmake -G Ninja ..
    ninja
    
    # Copy output files with board-specific names
    if [ -f "basic1.uf2" ]; then
        cp "basic1.uf2" "../basic1_${BOARD_NAME}.uf2"
        echo "✓ Created: basic1_${BOARD_NAME}.uf2"
    fi
    
    if [ -f "basic1.dis" ]; then
        cp "basic1.dis" "../basic1_${BOARD_NAME}.dis"
    fi
    
    cd ..
done

echo ""
echo "========================================"
echo "Build complete! UF2 files:"
ls -lh basic1_*.uf2 2>/dev/null || echo "No UF2 files found"
echo "========================================"
echo ""
echo "Note: Original board_config.h has been restored"
