#!/bin/bash

# omarchy:summary=Launch an app or focus an existing window matching a pattern
# omarchy:args=<window-pattern> [<launch-command>|-- <command> [args...]]

if (($# == 0)); then
  echo "Usage: omarchy-launch-or-focus [window-pattern] [launch-command|-- command [args...]]"
  exit 1
fi

WINDOW_PATTERN="$1"
WINDOW_ADDRESS=$(hyprctl clients -j | jq -r --arg p "$WINDOW_PATTERN" '.[]|select((.class|test("\\b" + $p + "\\b";"i")) or (.title|test("\\b" + $p + "\\b";"i")))|.address' | head -n1)

if [[ -n $WINDOW_ADDRESS ]]; then
  hyprctl dispatch "hl.dsp.focus({ window = \"address:$WINDOW_ADDRESS\" })" >/dev/null 2>&1 || hyprctl dispatch focuswindow "address:$WINDOW_ADDRESS"
elif [[ ${2:-} == "--" ]]; then
  shift 2
  if (($# == 0)); then
    echo "Usage: omarchy-launch-or-focus [window-pattern] [launch-command|-- command [args...]]" >&2
    exit 1
  fi
  exec setsid "$@"
elif (($# >= 2)); then
  eval exec setsid "$2"
else
  exec setsid uwsm-app -- "$WINDOW_PATTERN"
fi
