#!/bin/bash

# omarchy:summary=Remove or uninstall the selected launcher entry
# omarchy:args=<desktop-id> <name>
# omarchy:hidden=true
# omarchy:requires-sudo=true

set -e

desktop_id="${1-}"
entry_name="${2-}"

if [[ -z $desktop_id ]]; then
  echo "Usage: omarchy-remove-launcher-entry <desktop-id> <name>" >&2
  exit 1
fi

desktop_file_name="$desktop_id"
if [[ $desktop_file_name != *.desktop ]]; then
  desktop_file_name="$desktop_file_name.desktop"
fi

user_desktop_dirs=()
desktop_dirs=()
if [[ -n ${XDG_DATA_HOME-} ]]; then
  user_desktop_dirs+=("$XDG_DATA_HOME/applications")
else
  user_desktop_dirs+=("$HOME/.local/share/applications")
fi
desktop_dirs+=("${user_desktop_dirs[@]}")

if [[ -n ${XDG_DATA_DIRS-} ]]; then
  IFS=: read -ra data_dirs <<<"$XDG_DATA_DIRS"
  for data_dir in "${data_dirs[@]}"; do
    desktop_dirs+=("$data_dir/applications")
  done
else
  desktop_dirs+=("/usr/local/share/applications" "/usr/share/applications")
fi

desktop_file=""
for dir in "${desktop_dirs[@]}"; do
  candidate="$dir/$desktop_file_name"
  if [[ -f $candidate ]]; then
    desktop_file="$candidate"
    break
  fi
done

if [[ -z $desktop_file ]]; then
  echo "Could not find launcher entry: $desktop_file_name" >&2
  exit 1
fi

is_user_desktop_file() {
  local dir desktop_dir

  desktop_dir="${desktop_file%/*}"
  for dir in "${user_desktop_dirs[@]}"; do
    [[ $desktop_dir == $dir ]] && return 0
  done

  return 1
}

desktop_name="${desktop_file##*/}"
desktop_name="${desktop_name%.desktop}"
exec_line="$(sed -n 's/^Exec=//p' "$desktop_file" | head -1)"

if [[ $exec_line =~ omarchy-launch-webapp|omarchy-webapp-handler ]]; then
  OMARCHY_REMOVE_NOTIFY=false omarchy-webapp-remove "$desktop_name"
  exit 0
fi

if [[ $exec_line =~ (^|[[:space:]])(\$TERMINAL|xdg-terminal-exec)[[:space:]].*-e([[:space:]]|$) ]]; then
  OMARCHY_REMOVE_NOTIFY=false omarchy-tui-remove "$desktop_name"
  exit 0
fi

if is_user_desktop_file; then
  display_name="${entry_name:-$desktop_name}"
  rm -f "$desktop_file"
  update-desktop-database "${desktop_file%/*}" &>/dev/null || true
  exit 0
fi

if package_name="$(pacman -Qqo "$desktop_file" 2>/dev/null | head -1)" && [[ -n $package_name ]]; then
  display_name="${entry_name:-$desktop_name}"
  quoted_package="$(printf '%q' "$package_name")"
  quoted_display="$(printf '%q' "$display_name")"
  exec omarchy-launch-floating-terminal-with-presentation "echo Uninstalling $quoted_display...; sudo pacman -Rns $quoted_package"
fi

if omarchy-cmd-present flatpak && flatpak info "${desktop_file_name%.desktop}" >/dev/null 2>&1; then
  flatpak_id="${desktop_file_name%.desktop}"
  quoted_flatpak="$(printf '%q' "$flatpak_id")"
  exec omarchy-launch-floating-terminal-with-presentation "flatpak uninstall $quoted_flatpak"
fi

echo "Don't know how to uninstall $desktop_file_name" >&2
exit 1
