#!/bin/sh
# rikkiti-terminal — launch the user's configured terminal emulator.
#
# Single source of truth for "open a terminal" across the desktop's shell-side
# callers (rikkiti-update, Terminal=true .desktop apps via appdb, …). The
# compositor's $mod+Return and rikkiti-files have their own in-language readers
# of the same setting; this mirrors their resolution order so every path agrees.
#
# Resolution order:
#   1. `terminal = <name>` in ~/.config/rikkiti/defaults.conf  (Settings ▸
#      Default Applications ▸ Terminal)
#   2. a probe of the desktop's preferred emulators (kitty, foot, alacritty)
#   3. x-terminal-emulator (the Debian alternative), then xterm
#
# Usage:
#   rikkiti-terminal              open an interactive shell
#   rikkiti-terminal -e CMD [ARGS…]   run CMD in the terminal
CONF="${XDG_CONFIG_HOME:-$HOME/.config}/rikkiti/defaults.conf"

term=""
if [ -r "$CONF" ]; then
	# Last `terminal = value` wins; strip surrounding whitespace.
	term=$(sed -n 's/^[[:space:]]*terminal[[:space:]]*=[[:space:]]*//p' "$CONF" | tail -n1 | tr -d '[:space:]')
fi

# Fall back if unset or the configured one isn't installed. Probe the desktop's
# preferred emulators BEFORE the x-terminal-emulator alternative: on Debian that
# alternative frequently points at xterm even when kitty/foot are installed —
# which is how updates opened "sh in an xterm" despite Settings showing kitty.
# Mirrors the compositor's and rikkiti-files' chain (kitty || foot || x-t-e || xterm).
if [ -z "$term" ] || ! command -v "$term" >/dev/null 2>&1; then
	term=""
	for t in kitty foot alacritty; do
		if command -v "$t" >/dev/null 2>&1; then term="$t"; break; fi
	done
	if [ -z "$term" ] && command -v x-terminal-emulator >/dev/null 2>&1; then
		term=x-terminal-emulator
	fi
	if [ -z "$term" ] && command -v xterm >/dev/null 2>&1; then
		term=xterm
	fi
fi

if [ -z "$term" ]; then
	command -v notify-send >/dev/null 2>&1 && notify-send -u critical \
		"Terminal" "No terminal emulator found. Install one or set it in Settings ▸ Default Applications."
	exit 1
fi

# No command requested → just open the terminal.
if [ "$1" != "-e" ]; then
	exec "$term"
fi
shift  # drop -e; "$@" is the command + args

# Different emulators take a command differently: kitty/foot run it directly,
# gnome-terminal wants `--`, the xterm family uses `-e`.
case "$(basename "$term")" in
	kitty|foot)      exec "$term" "$@" ;;
	gnome-terminal)  exec "$term" -- "$@" ;;
	*)               exec "$term" -e "$@" ;;
esac
