#!/bin/bash

# omarchy:summary=Create a desktop launcher for a terminal UI app
# omarchy:args=[name command window-style icon-url-or-name]

set -e

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

safe_icon_name() {
  printf '%s\n' "$1" \
    | tr '[:upper:]' '[:lower:]' \
    | sed 's/[^[:alnum:]]\+/-/g; s/^-//; s/-$//'
}

icon_name_from_ref() {
  local ref="$1"
  local name
  name=$(basename "$ref")

  if [[ $name == *.* ]]; then
    safe_icon_name "${name%.*}"
  else
    printf '%s\n' "$name"
  fi
}

install_user_icon() {
  local source="$1"
  local name="$2"
  local ext="${source##*.}"

  [[ $ext == "$source" ]] && ext="png"
  mkdir -p "$ICON_DIR"
  cp "$source" "$ICON_DIR/$name.$ext"
  gtk-update-icon-cache "$HOME/.local/share/icons/hicolor" &>/dev/null || true
  printf '%s\n' "$name"
}

if (( $# != 4 )); then
  echo -e "\e[32mLet's create a TUI shortcut you can start with the app launcher.\n\e[0m"
  APP_NAME=$(gum input --prompt "Name> " --placeholder "My TUI")
  APP_EXEC=$(gum input --prompt "Launch Command> " --placeholder "lazydocker or bash -c 'dust; read -n 1 -s'")
  WINDOW_STYLE=$(gum choose --header "Window style" float tile)
  ICON_REF=$(gum input --prompt "Icon URL/name> " --placeholder "See https://dashboardicons.com or enter an installed icon name")
else
  APP_NAME="$1"
  APP_EXEC="$2"
  WINDOW_STYLE="$3"
  ICON_REF="$4"
fi

if [[ -z $APP_NAME || -z $APP_EXEC || -z $ICON_REF ]]; then
  echo "You must set app name, app command, and icon URL/name!"
  exit 1
fi

DESKTOP_FILE="$HOME/.local/share/applications/$APP_NAME.desktop"
mkdir -p "$(dirname "$DESKTOP_FILE")"

if [[ $ICON_REF =~ ^https?:// ]]; then
  ICON_VALUE=$(safe_icon_name "$APP_NAME")
  mkdir -p "$ICON_DIR"
  if ! curl -sL -o "$ICON_DIR/$ICON_VALUE.png" "$ICON_REF"; then
    echo "Error: Failed to download icon."
    exit 1
  fi
  gtk-update-icon-cache "$HOME/.local/share/icons/hicolor" &>/dev/null || true
elif [[ -f $ICON_REF ]]; then
  ICON_VALUE=$(install_user_icon "$ICON_REF" "$(safe_icon_name "$APP_NAME")")
else
  # Bundled Omarchy icons are package-owned under /usr/share/icons/hicolor.
  ICON_VALUE=$(icon_name_from_ref "$ICON_REF")
fi

if [[ $WINDOW_STYLE == "float" ]]; then
  APP_CLASS="TUI.float"
else
  APP_CLASS="TUI.tile"
fi

cat >"$DESKTOP_FILE" <<EOF
[Desktop Entry]
Version=1.0
Name=$APP_NAME
Comment=$APP_NAME
Exec=xdg-terminal-exec --app-id=$APP_CLASS -e $APP_EXEC
Terminal=false
Type=Application
Icon=$ICON_VALUE
StartupNotify=true
EOF

chmod +x "$DESKTOP_FILE"

if (( $# != 4 )); then
  echo -e "You can now find $APP_NAME using the app launcher (SUPER + SPACE)\n"
fi
