#!/bin/bash

# Wrapper to launch walker with elephant provider, or fallback to rofi if walker is missing.

if command -v walker >/dev/null 2>&1; then
    # The setsid backgrounded commands below MUST redirect all std fds to
    # /dev/null. If they inherit stdout from a $(...) caller (e.g. nomarchy-menu
    # doing `$(menu ...)`), bash waits for those fds to close on every return,
    # which hangs the terminal after each menu selection.
    if ! pgrep -x elephant > /dev/null; then
        setsid uwsm-app -- elephant </dev/null >/dev/null 2>&1 &
        disown
    fi

    if ! pgrep -f "walker --gapplication-service" > /dev/null; then
        setsid uwsm-app -- walker --gapplication-service </dev/null >/dev/null 2>&1 &
        disown
    fi

    # dmenu mode reads stdin and is invoked many times in quick succession
    # by nomarchy-menu. Wrapping each call in uwsm-app (systemd-run --scope)
    # creates a fresh transient scope per invocation, which breaks chained
    # submenus — subsequent walker calls don't see a usable stdin and exit
    # without showing anything. Invoke walker directly for dmenu.
    if [[ "$*" == *"--dmenu"* ]]; then
        exec walker "$@"
    fi

    exec uwsm-app -- walker --width 644 --maxheight 300 --minheight 300 "$@"
elif command -v rofi >/dev/null 2>&1; then
    # Convert walker arguments to rofi arguments if possible
    # This is a very basic mapping for --dmenu
    if [[ "$*" == *"--dmenu"* ]]; then
        exec rofi -dmenu "$@"
    else
        exec rofi -show drun
    fi
else
    notify-send "Error" "Neither walker nor rofi found." -u critical
    exit 1
fi
