#!/usr/bin/env bash
# Wayland-native VimTeX viewer: Zathura + DBus forward search + hyprctl focus
# No xdotool required.
#
# VimTeX config:
#   vimtex_view_method          = "general"
#   vimtex_view_general_viewer  = "zathura-synctex"
#   vimtex_view_general_options = "--synctex-forward @line:@col:@tex @pdf"

synctex=""
if [[ "${1:-}" == "--synctex-forward" ]]; then
    synctex="$2"
    pdf="$(realpath "$3")"
else
    pdf="$(realpath "$1")"
fi

# Inverse search reuses the nvim socket inherited from the calling nvim instance
inverse="nvim --server ${NVIM} --remote-send ':VimtexInverseSearch %{line}:%{column} \"%{input}\"\\<cr\\>'"

# Find a zathura process that has this exact PDF path in its cmdline
find_pid() {
    for p in $(pgrep -x zathura 2>/dev/null); do
        tr '\0' '\n' < "/proc/$p/cmdline" 2>/dev/null | grep -qxF "$pdf" \
            && echo "$p" && return
    done
}

pid="$(find_pid)"

if [[ -n "$pid" ]]; then
    # Window already open: forward search via DBus, then focus
    if [[ -n "$synctex" ]]; then
        line="${synctex%%:*}"
        rest="${synctex#*:}"; col="${rest%%:*}"; input="${rest#*:}"
        gdbus call --session \
            --dest "org.pwmt.zathura.PID-${pid}" \
            --object-path /org/pwmt/zathura \
            --method org.pwmt.zathura.SynctexView \
            "$input" "$line" "$col" >/dev/null 2>&1 || true
    fi
    hyprctl dispatch "hl.dsp.focus({ window = \"pid:${pid}\" })" >/dev/null 2>&1 || true
else
    # Open fresh zathura with inverse search hook
    if [[ -n "$synctex" ]]; then
        zathura -x "$inverse" --synctex-forward "$synctex" "$pdf" &
    else
        zathura -x "$inverse" "$pdf" &
    fi
    zpid=$!
    # Give the window ~400ms to map, then focus it
    (sleep 0.4 && hyprctl dispatch "hl.dsp.focus({ window = \"pid:${zpid}\" })" >/dev/null 2>&1) &
fi
