#!/bin/sh
# Starchaser owns crash notices for this window.
export QS_DISABLE_CRASH_HANDLER=1 STARCHASER_QML_APP=ask
# summary: Open the Ask window with a question.
# Open Ask Starchaser with a question (Super+Space > type > "Ask: …"). One window: if it's open, ask there.
# The launcher's Ask box passes the question after `--`, so a typed "--help" is asked like any other question;
# anyone else gets the usage for -h/--help.
case "${1:-}" in
    -h|--help)
        cat <<'H'
Usage: starchaser ask ui [--] [question]

Opens the Ask Starchaser window. With a question, it is asked right away; with
none, Ask just opens. There is only one Ask window: if it is already open, it
comes to the front and keeps its conversation, and your question is asked there.

Put -- before a question that starts with a dash:
  starchaser ask ui -- "-h means what?"

Example:
  starchaser ask ui "How much battery is left?"
H
        exit 0 ;;
    --) shift ;;
    -?*) echo "starchaser ask ui: unknown option '$1'" >&2
        echo 'Usage: starchaser ask ui [--] [question]' >&2
        echo "Run 'starchaser ask ui --help' for more help." >&2
        exit 2 ;;
esac
# Opened from the taskbar: drop what its keeper set for the taskbar alone (drawing without the GPU after full graphics
# memory, the driver's implicit sync), so this window keeps the GPU. A QT_QUICK_BACKEND set by hand stays. QA r179.
if [ "${STARCHASER_KEEPER_PART:-}" = cockpit ]; then unset QT_QUICK_BACKEND __NV_DISABLE_EXPLICIT_SYNC STARCHASER_KEEPER_PART; fi
CFG="$HOME/.config/quickshell/ask"
# Ask takes over from the main menu (Super+Space): close it, or Ask opens underneath it (the menu sits on the overlay
# layer) and only Escape shows it. Nothing happens when the menu is closed or isn't running.
qs -p "$HOME/.config/quickshell/cockpit" ipc call -- menu hide >/dev/null 2>&1 </dev/null || true
# `--` so Quickshell never reads the question (or a function name like "show") as one of its own options.
qs -p "$CFG" ipc call -- ask ask "$*" >/dev/null 2>&1 && exit 0
# No desktop to show a window on (no Wayland socket: over SSH, or after the session ended): say so and stop, without
# starting Quickshell, which would abort there and leave a crash report behind (round 30).
nodesk() {
    echo "starchaser ask ui: couldn't open Ask (is a desktop session running?)" >&2
    return 1
}
have_desktop() {
    d="${WAYLAND_DISPLAY:-wayland-0}"
    case "$d" in /*) ;; *) d="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/$d" ;; esac
    [ -S "$d" ] || return 1
    # the socket file outlives a compositor that crashed; the compositor holds a lock on <socket>.lock while it runs,
    # so a lock this script can take means nobody is serving that socket
    if [ -e "$d.lock" ] && command -v flock >/dev/null 2>&1 && flock -n "$d.lock" true 2>/dev/null; then
        return 1
    fi
    return 0
}
have_desktop || { nodesk; exit 1; }
# Started from inside a systemd unit (a systemd-run wrapper, an app scope), the unit's end would take Ask down with it:
# then Ask gets a scope of its own. INVOCATION_ID is set only inside a unit. Only when a scope can actually be made
# (a quick try first): with no user service manager, Ask starts the plain way rather than not at all.
RUN=""
if [ -n "${INVOCATION_ID:-}" ] && command -v systemd-run >/dev/null 2>&1 \
        && systemd-run --user --scope --quiet --collect -- true >/dev/null 2>&1; then
    RUN="systemd-run --user --scope --quiet --collect --"
fi
# Not running yet. Two quick launches must not open two windows: the first takes the lock and starts Ask (holding the
# lock about 2 s while it loads); a second one waits for it and asks through it.
ask() { qs -p "$CFG" ipc call -- ask ask "$*" >/dev/null 2>&1; }
# Start Ask with the question. -n: if another Ask is still loading (a slow start, after the 2 s lock), Quickshell
# refuses to open a second window and exits right away; then the question goes to that one once it answers.
start() {
    have_desktop || { nodesk; return 1; }
    # $RUN unquoted on purpose: empty, or the systemd-run words that start Ask in a scope of its own
    STARCHASER_ASK_Q="$*" setsid -w $RUN qs -n -p "$CFG" 9>&- >/dev/null 2>&1 &
    pid=$!
    sleep 2
    kill -0 "$pid" 2>/dev/null && return 0
    j=0
    while [ $j -lt 30 ]; do
        ask "$@" && return 0
        sleep 0.2; j=$((j + 1))
    done
    # (the loop itself ends with status 0: without this a launch that failed at once was reported as fine)
    nodesk
}
LOCK="${XDG_RUNTIME_DIR:-/tmp}/starchaser-ask-ui.lock"
exec 9>"$LOCK"
if flock -n 9; then
    ask "$@" && exit 0   # started while we waited for the lock
    start "$@"
    exit $?
fi
i=0
while [ $i -lt 20 ]; do
    ask "$@" && exit 0
    sleep 0.2; i=$((i + 1))
done
flock 9   # still not answering: once the first launch is done waiting, ask once more, then start it ourselves
ask "$@" && exit 0
start "$@"
exit $?
