#!/bin/bash

# Build and Flash Script for Pico RP2350
# This script compiles the project and flashes it to the board
# Board selection is done in board_config.h (not via CMake)

set -e  # Exit on error

PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BUILD_DIR="${PROJECT_DIR}/build"
UF2_FILE="${BUILD_DIR}/basic1.uf2"
NINJA="${HOME}/.pico-sdk/ninja/v1.12.1/ninja"

echo "=========================================="
echo "  Pico RP2350 Build and Flash Script"
echo "=========================================="
echo ""

# Detect which board is selected in board_config.h
SELECTED_BOARD=$(grep "^#define BOARD_" "${PROJECT_DIR}/board_config.h" | grep -v "^//" | head -1 | awk '{print $2}')
echo "Selected board: ${SELECTED_BOARD}"
echo "(Change in board_config.h to build for different board)"
echo ""

# Check if build directory exists and has build.ninja
if [ ! -f "${BUILD_DIR}/build.ninja" ]; then
    echo "⚠ Build not configured. Running cmake..."
    cd "${PROJECT_DIR}"
    cmake -B build -G Ninja
    echo ""
fi

# Step 1: Build the project
echo "Step 1: Building project..."
cd "${BUILD_DIR}"

if [ -f "${NINJA}" ]; then
    "${NINJA}"
else
    ninja
fi

if [ $? -ne 0 ]; then
    echo "❌ Build failed!"
    exit 1
fi

echo "✓ Build successful!"
echo ""

# Check if UF2 file was created
if [ ! -f "${UF2_FILE}" ]; then
    echo "❌ Error: ${UF2_FILE} not found!"
    exit 1
fi

echo "UF2 file created: ${UF2_FILE}"
echo ""

# Step 2: Flash to board using picotool
echo "Step 2: Flashing to board using picotool..."
echo "Make sure your board is connected and in BOOTSEL mode"
echo "(Hold BOOTSEL button while plugging in USB)"
echo ""

PICOTOOL="${HOME}/.pico-sdk/picotool/2.2.0-a4/picotool/picotool"

if [ ! -f "${PICOTOOL}" ]; then
    echo "❌ picotool not found at: ${PICOTOOL}"
    exit 1
fi

# Try to load the UF2
"${PICOTOOL}" load "${UF2_FILE}" -fx

if [ $? -eq 0 ]; then
    echo ""
    echo "✓ Successfully flashed to board!"
    echo "✓ Board will automatically reboot and run the program"
else
    echo ""
    echo "❌ Flash failed! Make sure:"
    echo "   - Board is in BOOTSEL mode (hold BOOTSEL while plugging in)"
    echo "   - USB cable is connected"
    echo "   - You have permission to access USB devices"
    exit 1
fi

echo ""
echo "=========================================="
echo "Done!"
echo "=========================================="
