#!/bin/bash
# Inverse search callback for sioyek/vimtex/skim
# Usage: nvim-vimtex-callback LINE FILE

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

# Read servername if available and server still exists
SERVERNAME_ARG=""
if [[ -f $SERVERNAME_FILE ]]; then
    SERVERNAME=$(cat "$SERVERNAME_FILE")
    if [[ -n $SERVERNAME && -e $SERVERNAME ]]; then
        SERVERNAME_ARG="--servername $SERVERNAME"
    fi
fi

# If first arg is a number, assume sioyek direct format: LINE FILE
if [[ $1 =~ ^[0-9]+$ ]]; then
    LINE="$1"
    FILE="$2"
    exec "$SCRIPT_DIR/path-shim" nvr $SERVERNAME_ARG --remote-silent +"$LINE" "$FILE"
fi

# Otherwise parse VimTeX format: --headless -c "VimtexInverseSearch LINE 'FILE'"
CMD=""
while [[ $# -gt 0 ]]; do
    case $1 in
    --headless)
        shift
        ;;
    -c)
        shift
        CMD="$1"
        shift
        ;;
    *)
        shift
        ;;
    esac
done

if [[ -n $CMD ]]; then
    if [[ $CMD =~ VimtexInverseSearch\ ([0-9]+)\ \'(.+)\' ]]; then
        LINE="${BASH_REMATCH[1]}"
        FILE="${BASH_REMATCH[2]}"
        exec "$SCRIPT_DIR/path-shim" nvr $SERVERNAME_ARG --remote-silent +"$LINE" "$FILE"
    fi
fi
