#!/bin/bash

# omarchy:summary=Remove a terminal UI desktop launcher
# omarchy:args=[name]

set -e

ICON_DIR="$HOME/.local/share/icons/hicolor/256x256/apps"
OLD_ICON_DIR="$HOME/.local/share/applications/icons"
DESKTOP_DIR="$HOME/.local/share/applications/"

TUIS=()
TUI_PATHS=()
while IFS= read -r -d '' file; do
  if grep -qE '^Exec=.*(\$TERMINAL|xdg-terminal-exec).*-e' "$file"; then
    TUIS+=("$(basename -- "${file%.desktop}")")
    TUI_PATHS+=("$file")
  fi
done < <(find "$DESKTOP_DIR" -name '*.desktop' -print0 2>/dev/null)

path_for_tui() {
  local wanted="$1" i
  for i in "${!TUIS[@]}"; do
    if [[ ${TUIS[$i]} == "$wanted" ]]; then
      printf '%s\n' "${TUI_PATHS[$i]}"
      return 0
    fi
  done
}

if (( $# == 0 )); then
  if ((${#TUIS[@]})); then
    mapfile -t SORTED_TUIS < <(printf '%s\n' "${TUIS[@]}" | sort)
    APP_NAME=$(omarchy-menu-select "$(omarchy-i18n tui.selectRemove)" "${SORTED_TUIS[@]}" -- --width 520 --maxheight 520)
  else
    echo "No TUIs to remove."
    exit 1
  fi
else
  APP_NAME="$*"
fi

if [[ -z $APP_NAME ]]; then
  echo "You must select a TUI to remove."
  exit 1
fi

desktop_file=$(path_for_tui "$APP_NAME")
if [[ -z $desktop_file && ( $APP_NAME == */* || $APP_NAME == "." || $APP_NAME == ".." ) ]]; then
  echo "Invalid TUI name: $APP_NAME" >&2
  exit 1
fi

safe_icon_name() {
  local name
  name=$(printf '%s\n' "$1" \
    | tr '[:upper:]' '[:lower:]' \
    | sed 's/[^[:alnum:]]\+/-/g; s/^-//; s/-$//')
  if [[ -n $name ]]; then
    printf '%s\n' "$name"
  else
    printf 'tui-%s\n' "$(printf '%s' "$1" | sha256sum | cut -c1-12)"
  fi
}

icon_name=$(safe_icon_name "$APP_NAME")
rm -f "${desktop_file:-$DESKTOP_DIR/$APP_NAME.desktop}"
rm -f "$ICON_DIR/$icon_name.png"
if [[ $APP_NAME != */* && $APP_NAME != "." && $APP_NAME != ".." ]]; then
  rm -f "$ICON_DIR/$APP_NAME.png" "$OLD_ICON_DIR/$APP_NAME.png"
fi
if [[ ${OMARCHY_REMOVE_NOTIFY:-true} != "false" ]]; then
  omarchy-notification-send -g  "$(omarchy-i18n tui.removed)" "$APP_NAME"
fi
update-desktop-database "$DESKTOP_DIR" &>/dev/null || true
