#!/usr/bin/env bash
# nebide-disable-dbusactivatable.sh
# Only process .desktop files that ALREADY contain "DBusActivatable=".
# Safe: copies files to ~/.local/share/applications and modifies the copies; does NOT edit /usr/share files.
# Usage:
#   ./nebide-disable-dbusactivatable.sh --dry-run
#   ./nebide-disable-dbusactivatable.sh

set -euo pipefail

DRY_RUN=0
if [[ "${1:-}" == "--dry-run" ]]; then
  DRY_RUN=1
fi

SRC_DIRS=(/usr/share/applications /usr/local/share/applications "$HOME/.local/share/applications")
DEST_DIR="$HOME/.local/share/applications"
BACKUP_BASE="$DEST_DIR/nebide-backups"
TIMESTAMP="$(date +%Y%m%d-%H%M%S)"
BACKUP_DIR="$BACKUP_BASE/$TIMESTAMP"

mkdir -p "$DEST_DIR"
mkdir -p "$BACKUP_BASE"

echo ">>> nebide-disable-dbusactivatable"
echo ">>> Destination: $DEST_DIR"
echo ">>> Backup dir: $BACKUP_DIR"
if [[ $DRY_RUN -eq 1 ]]; then
  echo ">>> DRY RUN mode: no files will be written. Run without --dry-run to apply."
fi
echo

process_file() {
  local src="$1"
  local base
  base="$(basename "$src")"
  local dst="$DEST_DIR/$base"

  # only process .desktop
  [[ "$base" == *.desktop ]] || return

  # skip unreadable
  [[ -r "$src" ]] || { echo "   - skipping unreadable: $src"; return; }

  # check if file already contains DBusActivatable=
  if ! grep -qE '^DBusActivatable=' "$src"; then
    echo "   - SKIP (no DBusActivatable=): $base"
    return
  fi

  echo "-> Will process: $base"

  if [[ $DRY_RUN -eq 1 ]]; then
    echo "   (dry) would copy $src -> $dst and set DBusActivatable=false, prefix Exec if needed"
    return
  fi

  # backup existing dest if exists
  mkdir -p "$BACKUP_DIR"
  if [[ -e "$dst" ]]; then
    cp -a "$dst" "$BACKUP_DIR/$base.orig"
  fi

  # copy system file to local override
  cp -a "$src" "$dst"

  # 1) Ensure DBusActivatable=false (replace existing line)
  if grep -qE '^DBusActivatable=' "$dst"; then
    sed -i 's/^DBusActivatable=.*/DBusActivatable=false/' "$dst"
    echo "   - DBusActivatable set to false"
  fi

  # 2) Prefix Exec line with env XDG_CURRENT_DESKTOP=GNOME if not already present
  if grep -qE '^Exec=' "$dst"; then
    # pick first Exec= line
    execline="$(grep -m1 '^Exec=' "$dst" | sed 's/^Exec=//')"
    # if already contains XDG_CURRENT_DESKTOP= skip
    if echo "$execline" | grep -q 'XDG_CURRENT_DESKTOP='; then
      echo "   - Exec already contains XDG_CURRENT_DESKTOP -> skip prefix"
    else
      # Replace only the first Exec= occurrence with prefixed variant
      # preserve placeholders (%U %u %F %f etc.) by inserting env before command
      sed -i "0,/^Exec=/{s|^Exec=.*$|Exec=$execline|}" "$dst"
    fi
  else
    echo "   - No Exec= line found (unexpected), skipped prefix"
  fi

  echo "   -> Modified copy: $dst (backup at $BACKUP_DIR/$base.orig if existed)"
}

# gather unique files (preserve order: prefer user's local copy if present)
declare -A seen
files=()
for d in "${SRC_DIRS[@]}"; do
  [[ -d "$d" ]] || continue
  while IFS= read -r -d '' f; do
    name="$(basename "$f")"
    # prefer existing ~/.local version if present: record presence and skip lower-priority duplicates
    if [[ -n "${seen[$name]:-}" ]]; then
      continue
    fi
    seen["$name"]=1
    files+=("$f")
  done < <(find "$d" -maxdepth 1 -type f -name '*.desktop' -print0)
done

if [[ ${#files[@]} -eq 0 ]]; then
  echo "No .desktop files found in source dirs."
  exit 0
fi

echo "Found ${#files[@]} .desktop files to inspect."
echo

for f in "${files[@]}"; do
  process_file "$f"
done

echo
if [[ $DRY_RUN -eq 1 ]]; then
  echo "DRY RUN complete. Re-run without --dry-run to apply changes."
else
  echo "Done. Backups stored at: $BACKUP_DIR"
  echo "To revert for a file, copy its backup from $BACKUP_DIR back into $DEST_DIR"
fi

exit 0
