#!/usr/bin/bash
# Ensure file descriptors are properly set up
exec < /dev/null
exec > /dev/tty
exec 2> /dev/tty

# Find available languages by checking traineddata files
AVAILABLE_LANGS=$(find /usr/share/tessdata -name "*.traineddata" | sed 's|.*/||' | sed 's|\.traineddata$||' | grep -v "osd" | sort)

# Exit if no languages are found
if [ -z "$AVAILABLE_LANGS" ]; then
  notify-send "OCR error" "No language data found in /usr/share/tessdata"
  exit 1
fi

# Let user select language using wmenu
LANG=$(echo "$AVAILABLE_LANGS" | wmenu -p "Select OCR language:")

# Exit if no language was selected
if [ -z "$LANG" ]; then
  notify-send "OCR canceled" "No language selected"
  exit 1
fi

# Capture screenshot of selected area
slurp | grim -g - - > /tmp/screenshot.png

# Perform OCR with selected language and save original text
tesseract -l "${LANG}" /tmp/screenshot.png stdout | grep -v '^$' > /tmp/ocr_output.txt

# Copy the original OCR'd text to secondary clipboard
cat /tmp/ocr_output.txt | wl-copy

# Run the OCR'd text through translate-shell
cat /tmp/ocr_output.txt | trans -brief > /tmp/translated_output.txt

# Copy the translated text to primary clipboard
cat /tmp/translated_output.txt | wl-copy --primary

# Show notification with the translated text
notify-send -t 10000 -h string:x-canonical-private-synchronous:scanned "Translated: $(wl-paste --primary)"

# Clean up temporary files
rm /tmp/screenshot.png /tmp/ocr_output.txt /tmp/translated_output.txt
