#!/usr/bin/env bash

# omarchy:summary=Install one of the approved terminals and set it as the default for Omarchy (Super + Return etc).
# omarchy:args=<alacritty|foot|ghostty|kitty>
# omarchy:requires-sudo=true

if (($# == 0)); then
  echo "Usage: omarchy-install-terminal [alacritty|foot|ghostty|kitty]"
  exit 1
fi

package="$1"

# Map package name to desktop entry ID
case "$package" in
alacritty) desktop_id="Alacritty.desktop" ;;
foot) desktop_id="foot.desktop" ;;
ghostty) desktop_id="com.mitchellh.ghostty.desktop" ;;
kitty) desktop_id="kitty.desktop" ;;
*)
  echo "Unknown terminal: $package"
  exit 1
  ;;
esac

echo "Installing $package..."

# Install package
if omarchy-pkg-add $package; then
  # Copy custom desktop entries with X-TerminalArg* keys
  if [[ $package == "alacritty" ]]; then
    mkdir -p ~/.local/share/applications
    cp "$OMARCHY_PATH/default/alacritty/$desktop_id" ~/.local/share/applications/
  elif [[ $package == "foot" ]]; then
    mkdir -p ~/.local/share/applications
    cp "$OMARCHY_PATH/applications/$desktop_id" ~/.local/share/applications/
  fi

  # Copy default config for optional terminals when missing
  if [[ ! -e ~/.config/$package ]]; then
    cp -Rpf "$OMARCHY_PATH/config/$package" ~/.config/
  fi

  # Based: Ghostty comes with UbuntuMono Nerd Font, the face the former dev
  # tooling paired it with, from the Nerd Fonts release when no package
  # carries it, and becomes the system font.
  if [[ $package == "ghostty" ]] && ! fc-list 2>/dev/null | grep -Fqi "UbuntuMono Nerd Font"; then
    font_dir=~/.local/share/fonts/UbuntuMonoNerdFont
    font_tmp=$(mktemp -d)
    if curl -fsSL https://github.com/ryanoasis/nerd-fonts/releases/latest/download/UbuntuMono.zip -o "$font_tmp/UbuntuMono.zip" \
      && mkdir -p "$font_dir" && unzip -qo "$font_tmp/UbuntuMono.zip" -d "$font_dir"; then
      fc-cache -f "$font_dir" >/dev/null 2>&1 || true
      omarchy-font-set "UbuntuMono Nerd Font" || true
    else
      echo "Could not fetch UbuntuMono Nerd Font; Ghostty keeps the current font" >&2
    fi
    rm -rf "$font_tmp"
  fi

  # Update xdg-terminals.list to prioritize the proper terminal
  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
else
  echo "Failed to install $package"
fi
