#!/bin/bash
# get_crash_log.sh - Retrieve crash log from Cricket device
# Always saves locally then clears from device
# Saved to: platforms/Cricket_ESP32_P4/crash_logs/ (relative to project root)
#
# ═══════════════════════════════════════════════════════════════════════════════
# CRASH LOG FORMAT - What gets captured:
# ═══════════════════════════════════════════════════════════════════════════════
#
# The firmware captures crash info to RTC memory (survives reboot) for:
#   - Panic/Assert failures
#   - Task Watchdog (TWDT) - task stuck too long
#   - Interrupt Watchdog (IWDT) - interrupt handler stuck
#   - Stack Overflow
#   - Brownout (if slow enough to capture)
#
# Crash log includes:
#   - Exception:       Human-readable exception type (e.g., "Task watchdog got triggered")
#   - Description:     Additional details about the crash
#   - Task Name:       Which FreeRTOS task was running when crash occurred
#   - PC:              Program Counter (memory address of crash location)
#   - Uptime:          How long device ran before crash
#   - Free Heap:       Memory status at crash time
#   - Sniffer Running: Whether audio sniffer was active
#
# ═══════════════════════════════════════════════════════════════════════════════
# TO FIND THE EXACT CODE LINE FROM A PC ADDRESS:
# ═══════════════════════════════════════════════════════════════════════════════
#
#   cd /path/to/M5Tab5-HalUD/platforms/Cricket_ESP32_P4
#   riscv32-esp-elf-addr2line -e build/cricket.elf 0x42015A8C
#
# Output example:
#   /path/to/app_main.cpp:3456 (process_audio_frame)
#
# This tells you the exact file, line number, and function where the crash occurred.
#
# Note: You must have the same build/cricket.elf that was flashed to the device.
#       If you rebuild, the addresses will change!
#
# ═══════════════════════════════════════════════════════════════════════════════

CRICKET_HOST="${CRICKET_HOST:-192.168.50.242}"

# Determine save directory based on user
# Uses project-relative path under platforms/Cricket_ESP32_P4/crash_logs/
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$(dirname "$SCRIPT_DIR")")"  # Go up from tools -> cricket_firmware_website -> Cricket_ESP32_P4

# Fallback paths for different users
if [[ "$USER" == "ming" ]]; then
    SAVE_DIR="${PROJECT_DIR}/crash_logs"
    if [[ ! -d "$(dirname "$PROJECT_DIR")" ]]; then
        # Ming's path might be different
        SAVE_DIR="/Users/ming/Development/esp32/cricket/crash_logs"
    fi
else
    SAVE_DIR="${PROJECT_DIR}/crash_logs"
fi

echo "╔══════════════════════════════════════════════════════════════╗"
echo "║               Cricket Crash Log Retrieval                    ║"
echo "║         (Always saves locally, then clears device)           ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""

echo "📡 Fetching from http://${CRICKET_HOST}/crash_log ..."
echo ""

RESPONSE=$(curl -s -w "\n%{http_code}" "http://${CRICKET_HOST}/crash_log" 2>&1)
HTTP_CODE=$(echo "$RESPONSE" | tail -1)
BODY=$(echo "$RESPONSE" | sed '$d')

if [[ "$HTTP_CODE" == "000" ]]; then
    echo "❌ Cannot reach Cricket device at ${CRICKET_HOST}"
    echo "   Make sure the device is powered on and connected to WiFi."
    exit 1
fi

echo "────────────────────────────────────────────────────────────────"
echo "$BODY"
echo "────────────────────────────────────────────────────────────────"
echo ""

if [[ "$BODY" == *"No crash log found"* ]]; then
    echo "✅ Good news - no crashes recorded!"
else
    # Always save to local file
    mkdir -p "$SAVE_DIR"
    TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
    FILENAME="crash_log_${TIMESTAMP}.txt"
    FILEPATH="${SAVE_DIR}/${FILENAME}"
    echo "$BODY" > "$FILEPATH"
    echo "💾 Saved to: $FILEPATH"
    echo ""
    
    # Always clear after saving
    echo "🗑️  Clearing crash log from device..."
    curl -s -X DELETE "http://${CRICKET_HOST}/crash_log" > /dev/null
    echo "✅ Crash log cleared from device"
    echo ""
    echo "💡 To find the exact code line from a PC address:"
    echo "   riscv32-esp-elf-addr2line -e build/cricket.elf 0xADDRESS"
fi
