#!/usr/bin/env bash

# omarchy:summary=Control the Omarchy menu (toggle / summon / close / refresh)
# omarchy:args=[toggle|summon|close|refresh|ping|tui] [route]
# omarchy:examples=omarchy menu | omarchy menu toggle system | omarchy menu summon style.theme | omarchy menu refresh

# Thin wrapper around the standard plugin IPC surface. The menu is the
# first-party `omarchy.menu` plugin; routes are passed as JSON payload.
# Where no shell answers, omarchy-menu-tui draws the same menu in the terminal.

set -euo pipefail

verb="${1-toggle}"
route="${2-root}"

menu_payload() {
  jq -nc --arg menu "$1" '{ menu: $menu }'
}

case "$verb" in
  toggle | summon)
    # The shell draws the menu inside the graphical session it runs in. A
    # caller with no WAYLAND_DISPLAY (ssh, a tty) is outside that session, and
    # the GNOME and KDE editions have no shell to answer. Both get the terminal
    # menu when there is a terminal to draw it in; without one, the shell's
    # own answer says what is missing.
    if [[ -n ${WAYLAND_DISPLAY:-} ]] && omarchy-shell shell "$verb" omarchy.menu "$(menu_payload "$route")" 2>/dev/null; then
      exit 0
    fi
    if : 2>/dev/null <>/dev/tty; then
      exec omarchy-menu-tui "$route"
    fi
    exec omarchy-shell shell "$verb" omarchy.menu "$(menu_payload "$route")"
    ;;
  tui)
    exec omarchy-menu-tui "${@:2}"
    ;;
  close)
    exec omarchy-shell shell hide omarchy.menu
    ;;
  refresh | ping)
    exec omarchy-shell shell call omarchy.menu "$verb" "{}"
    ;;
  -h | --help | help)
    cat <<USAGE
Usage: omarchy menu [verb] [route]

Verbs:
  toggle [route]   Open the menu at <route>, or close it if already open. Default verb.
  summon [route]   Always open the menu (no close-if-visible toggle).
  close            Close the menu if it is visible.
  refresh          Re-parse the menu JSONC files.
  ping             Health check.
  tui [route]      Draw the menu in this terminal. toggle and summon do the
                   same on their own where no shell answers: over ssh, on a
                   tty, on the GNOME and KDE editions.

Route is an item id (e.g. setup.power) or alias (e.g. power). Defaults to
"root", which opens the top-level menu.
USAGE
    exit 0
    ;;
  *)
    echo "omarchy-menu: unknown verb '$verb'. Try 'omarchy menu --help'." >&2
    exit 2
    ;;
esac
