#!/bin/sh -e
#
# ftags - fuzzy search ctags in current directory or given path(arg1)
# dependencies: fzy (fzf)

case "$#" in
  1)
    cd "${1?no directory given}"
    shift
    ;;
  *) ;;
esac

if [ -e "tags" ]; then
  if command -v fzy >/dev/null 2>&1; then
    line=$(awk 'BEGIN { FS="\t" } !/^!/ { print toupper($4)"\t"$1"\t"$2"\t"$3 }' tags \
      | cut -c1-80 | fzy -p 'tags > ' -q "$*")
  elif command -v fzf >/dev/null 2>&1; then
    line=$(awk 'BEGIN { FS="\t" } !/^!/ { print toupper($4)"\t"$1"\t"$2"\t"$3 }' tags \
      | cut -c1-80 | fzf --nth=1,2)
  fi
  file=$(printf '%b' "${line}" | cut -f 3)
  tag=$(printf '%b' "${line}" | cut -f 2)
  ${EDITOR:-vi} "${file}" -c "silent tag ${tag}"
  # ${EDITOR:-vi} "$(cut -f3 <<<${line})" -c "silent tag $(cut -f2 <<<${line})"
else
  printf '%b\n' "${0##*/}: \047tags\047 file not found!" >&2
  exit 2
fi
