#!/usr/bin/env bash
# Toggle the astal-menu popup (or open it to a section). Forwards a verb to the
# resident daemon over D-Bus; if the daemon isn't running yet, starts it first.
# (No `set -e`: a non-zero `grep`/`busctl` in the wait loop is expected and must
# not abort the script before it forwards the verb.)
#
#   menu-toggle.sh            -> --toggle
#   menu-toggle.sh appdrawer  -> open with the app drawer expanded

BUS="eu.abdelbaki.astalmenu"
APP="${HOME}/.config/astal-menu/main.py"

case "${1:-}" in
    appdrawer) VERB="--appdrawer" ;;
    show)      VERB="--show" ;;
    hide)      VERB="--hide" ;;
    *)         VERB="--toggle" ;;
esac

registered() { busctl --user list 2>/dev/null | grep -q "$BUS"; }

if ! registered; then
    "${HOME}/.config/scripts/astal-menu-start.sh" >/dev/null 2>&1 &
    for _ in $(seq 1 25); do
        if registered; then break; fi
        sleep 0.2
    done
fi

# If it still didn't register, this invocation just becomes the primary instance
# (Gio single-instance handles the routing either way).
exec python3 "$APP" "$VERB"
