#!/bin/bash

# This script fixes taskbar stacking issues for the NeuralLoom Chrome PWA on Ubuntu/Debian.
# It aligns StartupWMClass in the PWA desktop entry to match the window class.

DESKTOP_DIR="$HOME/.local/share/applications"
if [ ! -d "$DESKTOP_DIR" ]; then
  echo "Error: Application shortcut directory not found at $DESKTOP_DIR"
  exit 1
fi

# Find all chrome-chrome-*.desktop files that contain 'NeuralLoom'
DE_FILES=$(grep -l -i "NeuralLoom" "$DESKTOP_DIR"/chrome-*.desktop 2>/dev/null)

if [ -z "$DE_FILES" ]; then
  echo "Could not find any NeuralLoom Chrome PWA shortcut (.desktop) in $DESKTOP_DIR."
  echo "Please make sure you have installed the NeuralLoom PWA via Google Chrome first."
  exit 1
fi

for de_file in $DE_FILES; do
  echo "Found NeuralLoom PWA desktop shortcut: $(basename "$de_file")"
  
  # Extract App ID from the Exec line (chrome --app-id=...)
  APP_ID=$(grep -oP '(?<=--app-id=)[a-z0-9]+' "$de_file")
  
  if [ -z "$APP_ID" ]; then
    echo "  Error: Could not extract PWA App ID from execution command."
    continue
  fi
  
  WM_CLASS="crx_$APP_ID"
  echo "  Extracted App ID: $APP_ID"
  echo "  Target StartupWMClass: $WM_CLASS"
  
  # Remove existing StartupWMClass entries
  sed -i '/^StartupWMClass=/d' "$de_file"
  
  # Append new entry
  echo "StartupWMClass=$WM_CLASS" >> "$de_file"
  echo "  Updated $de_file successfully."
done

# Restart the desktop shell runner / database to reload desktop entries
if command -v update-desktop-database &> /dev/null; then
  update-desktop-database "$DESKTOP_DIR"
  echo "Desktop entry database updated."
fi

echo "PWA Stacking fix completed successfully. Please restart your NeuralLoom app from the application menu."
