#!/bin/bash
#
# NebiDE Wayland Debug Launcher
# Captures all output to a log file for debugging purposes
# Supports real-time debugging with nebide-rtd

# Create log directory if it doesn't exist
LOG_DIR="$HOME/.cache/nebide-wayland"
mkdir -p "$LOG_DIR"

# Generate log filename with current date and time
LOG_FILE="$LOG_DIR/debug_$(date '+%Y-%m-%d_%H-%M-%S').log"

# Create a symlink to the latest log file for easy access
ln -sf "$LOG_FILE" "$LOG_DIR/latest.log"

# Log script startup
echo "=== NebiDE Wayland Debug Session Started at $(date) ===" > "$LOG_FILE"
echo "Log file: $LOG_FILE" >> "$LOG_FILE"
echo "System information:" >> "$LOG_FILE"
echo "- Kernel: $(uname -r)" >> "$LOG_FILE"
echo "- NebiDE Version: $(dpkg -l | grep nebide | awk '{print $2 " " $3}' || echo "Package not found")" >> "$LOG_FILE"
echo "- Graphics: $(glxinfo | grep "OpenGL renderer" || echo "glxinfo not available")" >> "$LOG_FILE"
echo "- Environment:" >> "$LOG_FILE"
echo "  WLR_RENDERER_ALLOW_SOFTWARE=1" >> "$LOG_FILE"
echo "  WLR_NO_HARDWARE_CURSORS=1" >> "$LOG_FILE"
echo "  NEBIDE_DEBUG_LOG_FILE=$LOG_FILE" >> "$LOG_FILE"
echo "=======================================================" >> "$LOG_FILE"
echo "" >> "$LOG_FILE"

# Launch NebiDE with debug output captured to log file
echo "Starting NebiDE Wayland session with debugging enabled..." | tee -a "$LOG_FILE"
echo "All debug output will be saved to: $LOG_FILE"
echo "You can view the logs in real-time using: nebide-rtd"

# Export the log file location for other tools
export NEBIDE_DEBUG_LOG_FILE="$LOG_FILE"

# Run NebiDE with output redirected to log file
NEBIDE_DEBUG_LOG_FILE="$LOG_FILE" WLR_RENDERER_ALLOW_SOFTWARE=1 WLR_NO_HARDWARE_CURSORS=1 dbus-run-session /System/NebiDE\ Files/scripts/run.sh >> "$LOG_FILE" 2>&1

# Note: We don't add & at the end to keep the script in foreground and allow
# proper capture of all output including shutdown events
