#!/bin/bash
# VimTeX inverse search callback wrapper
# This script is called by sioyek for inverse search
# It uses nvr to connect to the running Neovim instance

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
SERVERNAME_FILE="/tmp/vimtex-servername"

# VimTeX calls: nvim --headless -c "VimtexInverseSearch LINE 'FILE'"
# Parse the VimtexInverseSearch command to extract LINE and FILE
# Then use nvr --remote +LINE FILE which is more reliable

CMD=""
while [[ $# -gt 0 ]]; do
    case $1 in
    --headless)
        shift
        ;;
    -c)
        shift
        CMD="$1"
        shift
        ;;
    *)
        shift
        ;;
    esac
done

if [[ -n $CMD ]]; then
    # Extract line number and file from: VimtexInverseSearch LINE 'FILE'
    if [[ $CMD =~ VimtexInverseSearch\ ([0-9]+)\ \'(.+)\' ]]; then
        LINE="${BASH_REMATCH[1]}"
        FILE="${BASH_REMATCH[2]}"

        if [[ -f $SERVERNAME_FILE ]]; then
            SERVERNAME=$(cat "$SERVERNAME_FILE")
            exec "$SCRIPT_DIR/path-shim" nvr --servername "$SERVERNAME" --remote-silent +"$LINE" "$FILE"
        else
            exec "$SCRIPT_DIR/path-shim" nvr --remote-silent +"$LINE" "$FILE"
        fi
    fi
fi
