#!/usr/bin/env bash
TMPFILE=$(mktemp /tmp/ocr_XXXXXX.png)
trap 'rm -f "$TMPFILE"' EXIT

# Fire Spectacle silently in region-selection mode
spectacle -r -b -n -o "$TMPFILE" 2>/dev/null

if [ -s "$TMPFILE" ]; then
    # Run Tesseract on stdout
    TEXT=$(tesseract "$TMPFILE" - 2>/dev/null)

    if [ -n "$TEXT" ]; then
        if [ "$XDG_SESSION_TYPE" = "wayland" ]; then
            printf '%s' "$TEXT" | wl-copy
        else
            printf '%s' "$TEXT" | xclip -selection clipboard
        fi
        notify-send "Text Saved" "Text saved straight to clipboard." -i edit-paste
    else
        notify-send "Text Failed To Save" "No legible text found in capture." -i dialog-warning
    fi
fi
