#!/usr/bin/env bash
# Internal wrapper - sets LD_LIBRARY_PATH and handles OpenGL compatibility
# This wrapper doesn't have capabilities, so it can set environment vars
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
runner="$SCRIPT_DIR/obfusgated_vpn.network"
export LD_LIBRARY_PATH="$SCRIPT_DIR/lib:$LD_LIBRARY_PATH"
cd "$SCRIPT_DIR"

CONFIG_DIR="$HOME/.config/obfusgated-vpn"
FORCE_SW_FILE="$CONFIG_DIR/force-software-rendering"
FAILED_HW_FILE="$CONFIG_DIR/hardware-rendering-failed"

# ============================================================
# CRITICAL: Check for sudo/root BEFORE starting Flutter
# Flutter creates a window immediately when the binary starts,
# so we must check here in the wrapper, not in Dart code
# ============================================================
check_sudo() {
  # Check SUDO_USER environment variable
  if [ -n "$SUDO_USER" ]; then
    return 0  # Running with sudo
  fi
  # Check effective UID
  if [ "$(id -u)" = "0" ]; then
    return 0  # Running as root
  fi
  return 1  # Not running as sudo/root
}

show_sudo_error() {
  local lang="${LANG%%_*}"
  lang="${lang:-en}"
  
  local title="ObfusGated VPN - Do not run with sudo"
  local message="This application cannot be run with sudo or as root."
  local details="Running as root causes:
    • No keyring access (secure storage)
    • Screen renders as black
    • D-Bus session issues"
  local solution="Run the application as your normal user:
    obfusgated-vpn

    The app will request admin privileges when needed."
  
  # Localized messages
  case "$lang" in
    ru)
      title="ObfusGated VPN - Не запускайте с sudo"
      message="Это приложение нельзя запускать с sudo или от имени root."
      details="Запуск от root вызывает:
    • Нет доступа к связке ключей
    • Чёрный экран
    • Проблемы с D-Bus"
      solution="Запустите как обычный пользователь:
    obfusgated-vpn

    Приложение запросит права при необходимости."
      ;;
    de)
      title="ObfusGated VPN - Nicht mit sudo ausführen"
      message="Diese Anwendung kann nicht mit sudo ausgeführt werden."
      ;;
    es)
      title="ObfusGated VPN - No ejecutar con sudo"
      message="Esta aplicación no puede ejecutarse con sudo o como root."
      ;;
    fr)
      title="ObfusGated VPN - Ne pas exécuter avec sudo"
      message="Cette application ne peut pas être exécutée avec sudo."
      ;;
  esac
  
  # Print to terminal
  echo "" >&2
  echo "══════════════════════════════════════════════════════════════════════" >&2
  echo "  $title" >&2
  echo "══════════════════════════════════════════════════════════════════════" >&2
  echo "" >&2
  echo "  $message" >&2
  echo "" >&2
  echo "  $details" >&2
  echo "" >&2
  echo "  $solution" >&2
  echo "" >&2
  echo "══════════════════════════════════════════════════════════════════════" >&2
  echo "" >&2
  
  # Try to show GUI dialog (won't work well under sudo, but try anyway)
  if command -v zenity >/dev/null 2>&1; then
    zenity --error --title="$title" --text="$message\n\n$details\n\n$solution" --width=500 2>/dev/null &
    sleep 2
    kill $! 2>/dev/null || true
  fi
}

# Check for sudo BEFORE anything else
if check_sudo; then
  show_sudo_error
  exit 77
fi

# Check for --debug flag
DEBUG_MODE=false
FILTERED_ARGS=()
for arg in "$@"; do
  if [ "$arg" = "--debug" ] || [ "$arg" = "-d" ]; then
    DEBUG_MODE=true
  else
    FILTERED_ARGS+=("$arg")
  fi
done
set -- "${FILTERED_ARGS[@]}"

# Filter function to remove noisy native plugin logs
# Only used in production mode (not --debug)
filter_output() {
  grep -v -E \
    -e "^method call " \
    -e "^SystemTray::" \
    -e "^value_to_menu_item " \
    -e "Portal operation not allowed" \
    -e "Unable to load.*from the cursor theme" \
    -e "Failed to read XDG desktop portal" \
    -e "^\*\* \(com\.obfusgated" \
    -e "^Gdk-Message:" \
    -e "^$" \
    2>/dev/null || true
}

# Check for force software rendering flag (user preference or previous failure)
if [ -f "$FORCE_SW_FILE" ] || [ -f "$FAILED_HW_FILE" ]; then
  export LIBGL_ALWAYS_SOFTWARE=1
fi

# Detect if running in a VM or problematic OpenGL environment
detect_needs_software_rendering() {
  # Check for common VM indicators
  if grep -qi 'hypervisor\|vmware\|virtualbox\|qemu\|kvm\|xen\|parallels' /proc/cpuinfo 2>/dev/null; then
    return 0  # Needs software rendering
  fi
  
  # Check if running under VirtualBox (if lspci exists)
  if command -v lspci >/dev/null 2>&1; then
    if lspci 2>/dev/null | grep -qi 'virtualbox'; then
      return 0
    fi
    # Check for VMware
    if lspci 2>/dev/null | grep -qi 'vmware'; then
      return 0
    fi
  fi
  
  # Check systemd-detect-virt if available
  if command -v systemd-detect-virt >/dev/null 2>&1; then
    if systemd-detect-virt -q 2>/dev/null; then
      return 0
    fi
  fi
  
  return 1  # Hardware rendering should be fine
}

# Run app and handle crashes OR graphics errors
run_with_fallback() {
  local start_time=$(date +%s)
  local log_file="/tmp/obfusgated-vpn-startup-$$.log"
  
  # Start app in background, capturing output to log
  # In debug mode: show all output; in normal mode: filter noisy logs
  if $DEBUG_MODE; then
    "$runner" --debug "$@" > >(tee "$log_file") 2>&1 &
  else
    "$runner" "$@" > >(tee "$log_file" | filter_output) 2>&1 &
  fi
  APP_PID=$!
  
  # Monitor the process for the first 5 seconds
  local check_interval=0.5
  local checks=10
  local graphics_error_found=0
  local sudo_error_found=0
  
  for ((i=0; i<checks; i++)); do
    sleep $check_interval
    
    # Check if process died
    if ! kill -0 $APP_PID 2>/dev/null; then
      break
    fi
    
    # Check log for sudo/root error messages (should not retry)
    if grep -Eiq "Do not run with sudo|cannot be run with sudo|running as root" "$log_file"; then
      sudo_error_found=1
      break
    fi
    
    # Check log for known graphics failure patterns
    if grep -Eiq "DRI3 error|libEGL warning|failed to create context|GLX error|OpenGL error|glXCreateContext failed" "$log_file"; then
      graphics_error_found=1
      break
    fi
  done
  
  # If process is still running but we found graphics errors (not sudo), kill it
  if [ $graphics_error_found -eq 1 ] && [ $sudo_error_found -eq 0 ] && kill -0 $APP_PID 2>/dev/null; then
    kill $APP_PID 2>/dev/null
    wait $APP_PID 2>/dev/null
  else
    # Wait for process to exit normally or crash
    wait $APP_PID
  fi
  
  local exit_code=$?
  local end_time=$(date +%s)
  local runtime=$((end_time - start_time))
  
  # Cleanup log
  rm -f "$log_file"
  
  # Exit code 77 = sudo/root error - do NOT retry with software rendering
  # This is an intentional exit, not a graphics crash
  if [ $exit_code -eq 77 ] || [ $sudo_error_found -eq 1 ]; then
    return $exit_code
  fi
  
  # Logic to determine if we should fallback to software rendering:
  # 1. Quick crash (runtime < 5s && exit != 0) that's not a sudo error
  # 2. Detected graphics error in logs (even if it didn't crash yet)
  if { [ $runtime -lt 5 ] && [ $exit_code -ne 0 ]; } || [ $graphics_error_found -eq 1 ]; then
    if [ -z "$LIBGL_ALWAYS_SOFTWARE" ]; then
      echo "" >&2
      if [ $graphics_error_found -eq 1 ]; then
        echo "[WARNING] Detected critical graphics errors in output." >&2
      else
        echo "[WARNING] Application crashed quickly (exit code: $exit_code)." >&2
      fi
      echo "This is likely a driver/OpenGL issue." >&2
      echo "[INFO] Restarting in Safe Mode (Software Rendering)..." >&2
      echo "" >&2
      
      # Notify user if zenity is available
      if command -v zenity >/dev/null 2>&1; then
        zenity --notification --window-icon="$PKG_ROOT/usr/share/icons/hicolor/256x256/apps/$APP_ID.png" \
          --text="Graphics error detected. Restarting in Safe Mode..." &
      fi
      
      # Remember this failure for next time
      mkdir -p "$CONFIG_DIR"
      echo "Hardware rendering failed on $(date). Reason: Graphics error detected or crash." > "$FAILED_HW_FILE"
      
      # Retry with software rendering
      export LIBGL_ALWAYS_SOFTWARE=1
      if $DEBUG_MODE; then
        exec "$runner" --debug "$@"
      else
        exec "$runner" "$@" 2>&1 | filter_output
      fi
    fi
  fi
  
  return $exit_code
}

# If we detect a VM environment, use software rendering directly
if detect_needs_software_rendering; then
  export LIBGL_ALWAYS_SOFTWARE=1
  if $DEBUG_MODE; then
    exec "$runner" --debug "$@"
  else
    exec "$runner" "$@" 2>&1 | filter_output
  fi
fi

# Check for --software-rendering flag passed by user
for arg in "$@"; do
  if [ "$arg" = "--software-rendering" ]; then
    export LIBGL_ALWAYS_SOFTWARE=1
    if $DEBUG_MODE; then
      exec "$runner" --debug "$@"
    else
      exec "$runner" "$@" 2>&1 | filter_output
    fi
  fi
done

# If software rendering is already set (from previous failure), just run
if [ -n "$LIBGL_ALWAYS_SOFTWARE" ]; then
  if $DEBUG_MODE; then
    exec "$runner" --debug "$@"
  else
    exec "$runner" "$@" 2>&1 | filter_output
  fi
fi

# Normal execution with automatic fallback on crash
run_with_fallback "$@"
