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

FIRM=${FIRMWARE_DIR:-/firmware}

echo "=== Préparation image flash ==="
MERGE_ARGS=(
    --chip esp32 merge_bin
    -o /tmp/flash.bin
    --flash_mode dio
    --flash_freq 40m
    --flash_size 4MB
    0x1000  "$FIRM/bootloader.bin"
    0x8000  "$FIRM/partitions.bin"
    0x10000 "$FIRM/firmware.bin"
)
# Inclure LittleFS si disponible (lancer "pio run -t buildfs" pour le générer)
if [ -f "$FIRM/littlefs.bin" ]; then
    echo "  → LittleFS inclus (0x290000)"
    MERGE_ARGS+=(0x290000 "$FIRM/littlefs.bin")
else
    echo "  ⚠ littlefs.bin absent — webserver sans fichiers statiques"
    echo "    Lancer : pio run -t buildfs"
fi
MERGE_ARGS+=(--fill-flash-size 4MB)

python3 -m esptool "${MERGE_ARGS[@]}"
echo "  flash.bin prêt ($(du -sh /tmp/flash.bin | cut -f1))"

echo "=== Démarrage stub Modbus RTU ==="
python3 /emulator/modbus_stub.py &

echo "=== Démarrage serveur UI ==="
python3 /emulator/server.py &

echo "=== Lancement QEMU ESP32 ==="
echo "  WebServer ESP32 → http://localhost:10080"
echo "  UI debug        → http://localhost:8888"
echo ""

# UART0 → stdio (Serial debug)
# UART1 → null
# UART2 → TCP server port 1235 (stub Modbus se connecte ici)
exec qemu-system-xtensa \
    -nographic \
    -M esp32 \
    -drive file=/tmp/flash.bin,if=mtd,format=raw \
    -nic user,model=open_eth,hostfwd=tcp::10080-:80 \
    -serial mon:stdio \
    -serial null \
    -serial tcp::1235,server,nowait \
    2>&1 | tee /tmp/serial.log
