#!/usr/bin/env 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"

# Cancelling is a normal thing to do here and it has to read like one. gum says
# so in its own words and leaves -- `not submitted` from input, `nothing
# selected` from choose, both on exit 1, while Ctrl-C exits 130 and says nothing
# at all -- and `set -e` then ended the script with nothing of its own to add.
# The caller, omarchy-launch-floating-terminal-with-presentation, shows
# omarchy-show-done after anything that is not exit 130, so escaping a prompt
# was answered with "Done!" over a shortcut that was never created.
#
# One sentence, in our words, and leave on 130 so that banner stays away.
cancel() {
  if [[ -n ${CANCELLING:-} ]]; then
    exit 130
  fi
  CANCELLING=1

  # gum wrote its line and then restored the terminal, so the cursor sits just
  # below it and the line can be written over. Exit 130 is Ctrl-C, where gum
  # printed nothing and the line above belongs to the prompt.
  if (( ${1:-0} == 1 )) && [[ -t 2 ]]; then
    printf '\033[1A\033[2K\r' >&2
  fi

  omarchy-show-done "Cancelled. No shortcut was created."
  exit 130
}

# Read one answer into the named variable, or stop the flow. gum is the only
# thing here a person can say no to.
ask() {
  local target="$1" value status=0

  shift
  value=$("$@") || status=$?
  (( status == 0 )) || cancel "$status"
  printf -v "$target" '%s' "$value"
}

trap 'cancel 130' INT

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"
  ask APP_NAME gum input --prompt "Name> " --placeholder "My TUI"
  ask APP_EXEC gum input --prompt "Launch Command> " --placeholder "lazydocker or bash -c 'dust; read -n 1 -s'"
  ask WINDOW_STYLE gum choose --header "Window style" float tile
  ask ICON_REF gum input --prompt "Icon URL/name> " --placeholder "See https://dashboardicons.com or enter an installed icon name"

  # Enter on an empty prompt is gum's quieter no: exit 0 with nothing to hand
  # back. There is nothing to build out of nothing, so it lands where escaping
  # lands rather than on an error about arguments nobody passed.
  if [[ -z $APP_NAME || -z $APP_EXEC || -z $ICON_REF ]]; then
    cancel 0
  fi
else
  APP_NAME="$1"
  APP_EXEC="$2"
  WINDOW_STYLE="$3"
  ICON_REF="$4"

  if [[ -z $APP_NAME || -z $APP_EXEC || -z $ICON_REF ]]; then
    echo "You must set app name, app command, and icon URL/name!" >&2
    exit 1
  fi
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
