#!/bin/bash

# dmenugtranslate
#
# Translate the current clipboard with the help of dmenu
#
# Utilized gtranslate. Install instructions here:
# https://git.sr.ht/~yerinalexey/gtranslate
# https://gitlab.com/-/snippets/2343500

text=$(xclip -o -selection clipboard)
map=~/.local/share/dabruh/gtranslate-lang-map
FILE="/tmp/dmenugtranslate"

from="$(cut -d, -f1 2>/dev/null <"$FILE")"
to="$(cut -d, -f2 2>/dev/null <"$FILE")"

[ -n "$from" ] && LAST_FROM="$from"
[ -n "$to" ] && LAST_TO="$to"

# Inject the last used value on top. Remove the auto option for "Translate to".
FROM_MAP="$(echo "$LAST_FROM" | cat - "$map" | grep -v "^$" | cut -d= -f1 | uniq)"
TO_MAP="$(echo "$LAST_TO" | cat - "$map" | grep -Ev "^(Automatic=|$)" | cut -d= -f1 | uniq)"

# Get user selection via dmenu from language map file.
from=$(dmenu -i -l 30 -p "Translate from" <<<"$FROM_MAP")
[ -z "$from" ] && exit 1
from_code="$(grep "^$from=" "$map" | cut -d '=' -f2)"

to=$(dmenu -i -l 30 -p "Translate to" <<<"$TO_MAP")
[ -z "$to" ] && exit 1
to_code="$(grep "^$to=" "$map" | cut -d '=' -f2)"

echo "$from=$from_code,$to=$to_code" >"$FILE"

translation="$(docker run --rm --attach STDOUT --name dmenugtranslate gtranslate:latest gtranslate-query "$from_code" "$to_code" "$text")"
rc=$?

if [ $rc -ne 0 ]; then
    e="Translation from $from_code to $to_code failed. Input: '$text'"
    notify-send "$e" &
    echo "ERROR: $e" 1>&2
    exit 2
fi

echo "$translation"
printf '%s' "$translation" | xclip -selection clipboard
notify-send "Translation from $from_code to $to_code copied to clipboard." &
alacritty --class translation -e bash -c "echo '$translation' | less" &
