#!/bin/bash

# omarchy:summary=Launch a TUI command in the default terminal with Omarchy styling
# omarchy:args=[--app-id=<app-id>] [--title=<title>] <command> [args...]

APP_ID=""
TITLE=""
while [[ ${1:-} == --app-id=* || ${1:-} == --title=* ]]; do
  case $1 in
  --app-id=*) APP_ID="${1#--app-id=}" ;;
  --title=*) TITLE="${1#--title=}" ;;
  esac
  shift
done
[[ -z $APP_ID ]] && APP_ID="org.omarchy.$(basename -- "$1")"

# Without --title, the window is named after the command it runs.
if [[ -z $TITLE ]]; then
  TITLE=$1
  if [[ $TITLE == "env" ]]; then
    skip=0
    for arg in "${@:2}"; do
      if (( skip )); then skip=0; continue; fi
      [[ $arg == "-u" ]] && { skip=1; continue; }
      [[ $arg != -* && $arg != *=* ]] && { TITLE=$arg; break; }
    done
  fi
  TITLE=$(basename -- "$TITLE")
fi

# An agent runs its commands with colors and paging switched off (NO_COLOR=1 with
# PAGER=cat), and a window it opens would inherit both and come up without
# colors. The window is for a person, so that pair stops here. NO_COLOR or a
# pager the user chose for themselves stays.
if [[ ${NO_COLOR:-} == "1" && ${PAGER:-} == "cat" ]]; then
  unset NO_COLOR PAGER
  [[ ${GIT_PAGER:-} == "cat" ]] && unset GIT_PAGER
fi

# Emit OSC 2 inside the terminal instead of passing --title so initialTitle
# stays the terminal's own name (used by Hyprland scroll/focus rules) and
# Ghostty doesn't lock the title against runtime updates.
exec "$OMARCHY_PATH/bin/omarchy-launch-terminal" --dir="$PWD" --app-id="$APP_ID" -e \
  sh -c 'printf "\033]2;%s\007" "$1"; shift; exec "$@"' _ "$TITLE" "$@"
