#!/usr/bin/env bash

main() {

  preview_cmd="head -200 {}"

  while [ "$#" -gt 0 ]; do
    case "$1" in
      -r | --root)
        cd || exit
        shift
        ;;
      -H | --hidden)
        options="${options}-H"
        shift
        ;;
      -d | --dir)
        filter_dir="true"
        preview_cmd="tree -C {}"
        shift
        ;;
      -h | --help)
        cat <<EOF
Usage: ffd [-h] [-d] [-r] [-H] ...

Display basic fdfind result through fzf.

Optional arguments:
  -h, --help      show this help message and exit.
  -d, --dir       find directories and print the selected value.
  -r, --root      search from home directory.
  -H, --hidden    include hidden files/directories.
EOF
        exit 0
        ;;
      *)
        echo "Invalid argument: ${1}" >&2
        exit 1
        ;;
    esac
  done

  if [ -z "${filter_dir}" ]; then
    options="${options}-tf"
  else
    options="${options}-td"
  fi

  result=$(fd "${options}" | fzf --preview "${preview_cmd}" --exit-0)
  [ -z "${result}" ] && exit 1

  if [ -z "${filter_dir}" ]; then
    ${EDITOR:-vi} "${result}"
  else
    echo "${result}"
  fi
}

main "$@"
