#!/usr/bin/env sh
#
# see: https://github.com/junegunn/fzf/blob/master/ADVANCED.md#controlling-ripgrep-search-and-fzf-search-simultaneously

tmpfile="$(mktemp "${TMPDIR:-/tmp}"/"$(basename "$0")".XXXXXX)" || tmpfile=/tmp/test$$
# export TEMP=$(mktemp -u)
trap 'rm -f "$tmpfile"' EXIT

INITIAL_QUERY="${*:-}"
# shellcheck disable=SC2016
TRANSFORMER='
  rg_pat={q:1}      # The first word is passed to ripgrep
  fzf_pat={q:2..}   # The rest are passed to fzf

  if ! [ -r "${tmpfile}" ] || [ ${rg_pat} != $(cat "${tmpfile}") ]; then
    echo "${rg_pat}" > "${tmpfile}"
    printf "reload:sleep 0.1; rg --column --line-number --no-heading --color=always --smart-case %q || true" "${rg_pat}"
  fi
  echo "+search:${fzf_pat}"
'
fzf --ansi --disabled --query "${INITIAL_QUERY}" \
    --with-shell 'bash -c' \
    --bind "start,change:transform:${TRANSFORMER}" \
    --color "hl:-1:underline,hl+:-1:underline:reverse" \
    --delimiter : \
    --preview 'bat --color=always {1} --highlight-line {2}' \
    --preview-window 'up,60%,border-line,+{2}+3/3,~3' \
    --bind 'enter:become(vim {1} +{2})'
