#!/bin/bash

# omarchy:summary=Set the default terminal used by xdg-terminal-exec
# omarchy:args=[alacritty|foot|ghostty|kitty]
# omarchy:examples=omarchy default terminal ghostty | omarchy default terminal kitty

installing=false
if [[ ${1:-} == "--install" ]]; then
  installing=true
  shift
fi

terminal_binary_for_desktop_id() {
  case "$1" in
  Alacritty.desktop) TERMINAL_BINARY="alacritty" ;;
  foot.desktop) TERMINAL_BINARY="foot" ;;
  com.mitchellh.ghostty.desktop) TERMINAL_BINARY="ghostty" ;;
  kitty.desktop) TERMINAL_BINARY="kitty" ;;
  *) return 1 ;;
  esac
}

# Fast-path reading Omarchy's xdg-terminals.list directly in bash when called
# without args (the menu guard hot path), avoiding xdg-terminal-exec's ~15ms
# shell scan for the standard config.
fast_default_terminal() {
  [[ -z ${XTE_EXECARG_COMPAT:-}${XTE_DEBUG:-}${XTE_CACHE_ENABLED:-} ]] || return 1

  local config_dir="${XDG_CONFIG_HOME:-$HOME/.config}"
  local list="$config_dir/xdg-terminals.list"
  local desktop line binary=""
  local -a desktops

  IFS=: read -ra desktops <<<"${XDG_CURRENT_DESKTOP:-}"
  for desktop in "${desktops[@]}"; do
    [[ -n $desktop && -e $config_dir/${desktop,,}-xdg-terminals.list ]] && return 1
  done

  [[ -r $list ]] || return 1

  while IFS= read -r line || [[ -n $line ]]; do
    line=${line%$'\r'}
    line=${line#"${line%%[![:space:]]*}"}
    [[ -z $line || $line == \#* ]] && continue
    [[ $line == [/+-]* ]] && return 1
    if [[ -z $binary ]]; then
      terminal_binary_for_desktop_id "$line" || return 1
      binary=$TERMINAL_BINARY
    fi
  done <"$list"

  [[ -n $binary ]] && type -P "$binary" >/dev/null 2>&1 || return 1
  echo "$binary"
}

if (($# == 0)); then
  if fast_default_terminal; then
    exit 0
  fi
  desktop_id=$(xdg-terminal-exec --print-id 2>/dev/null || true)
  desktop_id=${desktop_id%%:*}
  if terminal_binary_for_desktop_id "$desktop_id"; then
    echo "$TERMINAL_BINARY"
  else
    echo "$desktop_id"
  fi
  exit 0
fi

case "$1" in
alacritty) terminal="alacritty"; desktop_id="Alacritty.desktop"; name="Alacritty"; glyph= ;;
foot) terminal="foot"; desktop_id="foot.desktop"; name="Foot"; glyph= ;;
ghostty) terminal="ghostty"; desktop_id="com.mitchellh.ghostty.desktop"; name="Ghostty"; glyph= ;;
kitty) terminal="kitty"; desktop_id="kitty.desktop"; name="Kitty"; glyph= ;;
*)
  echo "Usage: omarchy-default-terminal <alacritty|foot|ghostty|kitty>"
  exit 1
  ;;
esac

if omarchy-cmd-missing "$terminal"; then
  if [[ $installing == "false" ]]; then
    exec omarchy-launch-floating-terminal-with-presentation omarchy-default-terminal --install "$terminal"
  else
    omarchy-install-terminal "$terminal" || exit 1
  fi
fi

cat >~/.config/xdg-terminals.list <<EOF
# Terminal emulator preference order for xdg-terminal-exec
# The first found and valid terminal will be used
$desktop_id
EOF

omarchy-notification-send -g $glyph "$(omarchy-i18n default.terminalSet "$name")"
