#!/bin/bash
# Wrapper script for Vocab Dictionary
# Clears ALL Electron/Node/Chromium environment variables that could be
# inherited from the host environment (IDE, terminal, CI, etc.) and cause
# the app to malfunction. The app must behave identically regardless of
# where it's launched from.

# --- Clear Electron/Node variables that change runtime behavior ---
unset ELECTRON_RUN_AS_NODE          # Forces Electron into Node.js mode (no GUI)
unset ELECTRON_NO_ATTACH_CONSOLE    # Suppresses console output
unset ELECTRON_ENABLE_LOGGING       # Enables verbose logging
unset ELECTRON_DISABLE_SECURITY_WARNINGS
unset ELECTRON_OVERRIDE_DIST_PATH
unset ELECTRON_SAFE_REUSE_BRIDGE   # Affects contextBridge behavior

unset NODE_OPTIONS                  # Could inject --inspect, --require, etc.
unset NODE_PATH                     # Could hijack module resolution
unset NODE_ENV                      # Could trigger dev-mode code paths
unset NODE_EXTRA_CA_CERTS
unset NODE_REPL_EXTERNAL_MODULE

unset CHROME_DESKTOP                # Could override .desktop integration
unset CHROME_VERSION_OVERRIDE
unset CHROME_FLAGS_DESKTOP

# --- Keep: DISPLAY, WAYLAND_DISPLAY, HOME, XDG_*, DBUS, LANG, PATH ---
# These are required for the app to function (GUI, locale, file access)

# Resolve real path (follow symlinks) to find vocab-dict.bin in the same dir
REAL_PATH=$(readlink -f "$0")
REAL_DIR=$(dirname "$REAL_PATH")
BIN="$REAL_DIR/vocab-dict.bin"

# --no-sandbox: chrome-sandbox SUID bit is unreliable across distros
GPU_FLAGS=""

# Detect NVIDIA — these systems commonly hit GPU process launch failures
# (error_code=1002) with Electron on Linux
if ls /proc/driver/nvidia >/dev/null 2>&1; then
  GPU_FLAGS="--disable-gpu --in-process-gpu"
fi

# Try launching. If the process exits immediately with a GPU-related crash,
# retry with --disable-gpu as a fallback (covers non-NVIDIA GPU issues).
#
# IMPORTANT: When the app is already running and the user calls
# `vocab-dict --ocr-capture` (or any other CLI arg), the second process
# will fail to get the single-instance lock and exit immediately (within
# 3 seconds). The running instance handles the arg via the 'second-instance'
# IPC event. We must NOT treat this as a crash and retry — doing so would
# launch a third process that also fails the lock, appearing as a double
# launch to the user.
if [ -n "$GPU_FLAGS" ]; then
  exec "$BIN" --no-sandbox $GPU_FLAGS "$@"
else
  # First attempt: normal launch
  "$BIN" --no-sandbox "$@" &
  PID=$!
  # Wait briefly — if it exits within 3 seconds, could be a GPU crash
  # or a single-instance-lock rejection (app already running)
  sleep 3
  if kill -0 $PID 2>/dev/null; then
    # Still running, all good — wait for it in foreground
    wait $PID
  else
    # Exited within 3 seconds. Could be:
    # 1. GPU crash → retry with --disable-gpu
    # 2. Single-instance lock rejected → app already running, arg was
    #    forwarded via IPC. Don't retry.
    # Check exit code: Electron exits with 0 when single-instance lock
    # is rejected (app.quit() is called cleanly). GPU crashes exit with
    # non-zero codes.
    wait $PID
    EXIT_CODE=$?
    if [ $EXIT_CODE -eq 0 ]; then
      # Clean exit — likely single-instance lock rejection or normal quit
      exit 0
    else
      # Non-zero exit — likely a GPU crash, retry with GPU disabled
      exec "$BIN" --no-sandbox --disable-gpu --in-process-gpu "$@"
    fi
  fi
fi
