#!/bin/bash

# =============================
# Arduino Project Compiler 🚀
# =============================


# 🛠 Configurations (EDIT THESE)

# BOARD_FQBN="esp32:esp32:XIAO_ESP32C6"   # Change this to your board FQBN
BOARD_FQBN="esp32:esp32:esp32"   # Change this to your board FQBN
# BOARD_FQBN="esp32:esp32:heltec_wifi_lora_32_V3"  
# BOARD_FQBN="esp32:esp32:m5stack_stickc_plus"  
# BOARD_FQBN="esp32:esp32:XIAO_ESP32S3"  
SKETCH_DIR="$PWD"                                # Current directory (your sketch)
BUILD_DIR="$SKETCH_DIR/build"                    # Output build folder



# Function to draw progress bar
draw_progress_bar() {
    local progress=$1
    local width=50
    local filled=$((progress * width / 100))
    local empty=$((width - filled))
    
    printf "\r🔄 OTA Progress: ["
    printf "%*s" "$filled" | tr ' ' '#'
    printf "%*s" "$empty" | tr ' ' '-'
    printf "] %d%%" "$progress"
}

# Function to send MQTT command
send_mqtt_command() {
    local command="$1"
    local device_id="$2"
    
    echo "🚀 Triggering $command for device ID: $device_id"
    
    # Send MQTT command
    mosquitto_pub -t esp32 -m "{
  \"cmd\": \"$command\",
  \"id\": \"request123\",
  \"deviceID\": \"$device_id\"
}"
    
    echo "✅ $command command sent successfully!"
}

# Function to monitor OTA progress for a specific device
monitor_ota_progress() {
    local device_id="$1"
    echo "📡 Listening for OTA progress updates..."
    echo ""
    
    # Initialize progress bar
    draw_progress_bar 0
    
    # Listen for OTA progress messages
    mosquitto_sub -t esp32/ota/progress | while IFS= read -r line; do
        # Extract progress from JSON message
        if echo "$line" | grep -q "\"device\":\"$device_id\""; then
            progress=$(echo "$line" | sed -n 's/.*"otaProgress":\([0-9]*\).*/\1/p')
            if [ -n "$progress" ] && [ "$progress" -eq "$progress" ] 2>/dev/null; then
                draw_progress_bar "$progress"
                
                # Check if OTA is complete
                if [ "$progress" -eq 100 ]; then
                    echo ""
                    echo "🎉 OTA completed successfully for device: $device_id"
                    break
                fi
            fi
        fi
    done
}

# Check if first argument is "flash" to compile and trigger FOTA
if [ "$1" = "flash" ]; then
    # Set device ID - use provided one or default
    if [ -n "$2" ]; then
        DEVICE_ID="$2"
    else
        DEVICE_ID="ABC123"  # Change this to your preferred default device ID
    fi
    
    echo "🔨 Starting compilation and flash process for device: $DEVICE_ID"
    echo ""
    
    # Compile first
    echo "🔨 Compiling project at $SKETCH_DIR for board $BOARD_FQBN..."
    
    # Clean previous build
    rm -rf "$BUILD_DIR"
    
    # Compile sketch with UPDATE_SIGN defined for signed OTA support
    arduino-cli compile --fqbn "$BOARD_FQBN" --output-dir "$BUILD_DIR" "$SKETCH_DIR"
    
    # Check compilation success
    if [ $? -eq 0 ]; then
        echo "✅ Compilation successful!"
        BIN_FILE=$(find "$BUILD_DIR" -name "*.bin")
        echo "📄 BIN file generated at: $BIN_FILE"
        echo ""
        
        # Now trigger FOTA
        send_mqtt_command "fota" "$DEVICE_ID"
        
        # Monitor OTA progress
        monitor_ota_progress "$DEVICE_ID"
        
    else
        echo "❌ Compilation failed. Skipping FOTA."
        exit 1
    fi
    
    exit 0
fi

# Check if we have both command and device ID arguments
if [ -n "$1" ] && [ -n "$2" ] && [ "$1" != "fota" ] && [ "$1" != "flash" ]; then
    COMMAND="$1"
    DEVICE_ID="$2"
    
    # Send MQTT command
    send_mqtt_command "$COMMAND" "$DEVICE_ID"
    
    exit 0
fi

# Show help if only one argument or no arguments for MQTT commands
if [ -n "$1" ] && [ -z "$2" ] && [ "$1" != "fota" ] && [ "$1" != "flash" ]; then
    echo "❌ Error: Device ID is required"
    echo "Usage: sh build.sh <COMMAND> <DEVICE_ID>"
    echo "Examples:"
    echo "  sh build.sh fota LD2420          # FOTA update with progress"
    echo "  sh build.sh setdeviceid RLY65    # Set device ID"
    echo "  sh build.sh reboot ESP32_01      # Reboot device"
    echo "  sh build.sh status SENSOR_02     # Get device status"
    echo "  sh build.sh flash [DEVICE_ID]    # Compile and flash (device ID optional)"
    echo ""
    echo "Or run without arguments to compile the sketch"
    exit 1
fi

# Legacy support: Check if first argument is "fota" (backward compatibility)
if [ "$1" = "fota" ]; then
    if [ -z "$2" ]; then
        echo "❌ Error: Device ID is required for FOTA command"
        echo "Usage: sh build.sh fota <DEVICE_ID>"
        echo "Example: sh build.sh fota LD2420"
        exit 1
    fi
    
    COMMAND="fota"
    DEVICE_ID="$2"
    
    # Send MQTT command
    send_mqtt_command "$COMMAND" "$DEVICE_ID"
    
    # Monitor OTA progress
    monitor_ota_progress "$DEVICE_ID"
    
    exit 0
fi



# =============================
# Compilation Starts
# =============================

echo "🔨 Compiling project at $SKETCH_DIR for board $BOARD_FQBN..."

# Clean previous build
rm -rf "$BUILD_DIR"

# Compile sketch with UPDATE_SIGN defined for signed OTA support
arduino-cli compile --fqbn "$BOARD_FQBN" --build-property "compiler.cpp.extra_flags=-DUPDATE_SIGN" --build-property "compiler.c.extra_flags=-DUPDATE_SIGN" --output-dir "$BUILD_DIR" "$SKETCH_DIR"

# Check success
if [ $? -eq 0 ]; then
    echo "✅ Compilation successful!"
    BIN_FILE=$(find "$BUILD_DIR" -name "*.bin")
    echo "📄 BIN file generated at: $BIN_FILE"
    # mosquitto_pub -t esp32 -m "{\"cmd\": \"fota\", \"id\": \"test-123\"}"
else
    echo "❌ Compilation failed."
fi

