#!/usr/bin/env bash
# Superscribe as an Omarchy dictation backend: omarchy-dictation-superscribe start|stop|toggle
#
# Omarchy's contract (its manual, "Text Extraction & Dictation"): return promptly, with a nonzero status on failure,
# and let stop succeed when the backend is idle or unavailable, so omarchy-dictation-use can always switch to another
# backend. Superscribe takes the commands over D-Bus through its own CLI (superscribe dictate ...), which fails when
# Superscribe is not running. So stop counts "not running" and "not installed" as stopped, and start and toggle open
# Superscribe first, as Omarchy's Hex adapter opens Hex, then pass the command on once it answers.
set -u

usage() { echo 'Usage: omarchy-dictation-superscribe <start|stop|toggle>' >&2; exit 1; }

# The running app, not one of these CLI calls (same executable, with "dictate" in its arguments). The name is
# Superscribe when started from /opt/superscribe and superscribe through the /usr/bin link.
running() {
    local pid
    for pid in $(pgrep -u "$(id -u)" -x '[Ss]uperscribe' 2>/dev/null); do
        [[ $(tr '\0' ' ' < "/proc/$pid/cmdline" 2>/dev/null) == *' dictate '* ]] || return 0
    done
    return 1
}

case ${1:-} in
    start|toggle)
        command -v superscribe >/dev/null 2>&1 || { echo 'Superscribe is not installed.' >&2; exit 1; }
        if running; then exec superscribe dictate "$1"; fi
        setsid -f superscribe >/dev/null 2>&1 < /dev/null
        # It answers once it owns its D-Bus name, a second or two after it starts.
        for _ in $(seq 40); do
            sleep 0.25
            superscribe dictate "$1" 2>/dev/null && exit 0
        done
        exec superscribe dictate "$1"
        ;;
    stop)
        command -v superscribe >/dev/null 2>&1 || exit 0
        error=$(superscribe dictate stop 2>&1) && exit 0
        running || exit 0
        printf '%s\n' "$error" >&2
        exit 1
        ;;
    *) usage ;;
esac
