#!/usr/bin/env bash
#
# ---
# source: https://github.com/doitian/dotfiles-public/blob/master/default/bin/fzf-finder

set -e
set -u
[ -n "${DEBUG:-}" ] && set -x || true

POSITIONAL_ARGS=()
FZF_FINDER_PREVIEW="${FZF_FINDER_PREVIEW:-true}"
OPT_DIRECTORY="."
OPT_RECURSIVE=

usage() {
  echo "Usage: fzf-finder [-R|--recursive] [-d|--directory DIRECTORY] [--no-preview]" >&2
}

open_dwim() {
  open "$1"
}

KEEP_OPTS=()
while [[ $# -gt 0 ]]; do
  case $1 in
  --no-preview)
    KEEP_OPTS+=("$1")
    FZF_FINDER_PREVIEW=
    shift # past argument
    ;;
  -d | --directory)
    OPT_DIRECTORY="$2"
    shift # past argument
    shift # past value
    ;;
  -R | --recursive)
    OPT_RECURSIVE=true
    shift
    ;;
  -h | --help)
    usage
    exit 0
    ;;
  -* | --*)
    echo "Unknown option $1"
    usage
    exit 1
    ;;
  *)
    POSITIONAL_ARGS+=("$1") # save positional arg
    shift                   # past argument
    ;;
  esac
done

export FZF_FINDER_PREVIEW
set -- "${POSITIONAL_ARGS[@]+"${POSITIONAL_ARGS[@]}"}" # restore positional parameters

if [[ $# -gt 1 ]]; then
  shift
  echo "Unknown args $*"
  exit 1
fi

if [[ $# -gt 0 ]]; then
  OPT_DIRECTORY="$1"
fi

if [[ -d "$OPT_DIRECTORY" ]]; then
  cd "$OPT_DIRECTORY"
else
  dog "$OPT_DIRECTORY"
  echo "Enter to continue"
  read
  exec "fzf-finder"
fi

FZF_ARGS=(--header "$(pwd)/" --ansi --multi --nth='2..')
if [ -n "$FZF_FINDER_PREVIEW" ]; then
  FZF_ARGS+=(--preview 'dog {2..}')
fi

if [[ "$OPT_RECURSIVE" == "true" ]]; then
  exec fzf "${FZF_ARGS[@]}"
fi

FZF_ARGS+=(--header "$PWD
^h:up ^l:drill ^o:open ^v:edit" --header-first)
FZF_ARGS+=(--bind "ctrl-r:clear-screen")
FZF_ARGS+=(--bind "ctrl-l:become(fzf-finder -d {2..})" --bind "ctrl-h:become(fzf-finder -d ..)")
FZF_ARGS+=(--bind "right:become(fzf-finder -d {2..})" --bind "left:become(fzf-finder -d ..)")
FZF_ARGS+=(--bind "ctrl-o:execute-silent(open {+2..})")
FZF_ARGS+=(--bind "ctrl-v:execute(nvim {+2..})")
FZF_ARGS+=(--bind "enter:abort+become(printf \"\$PWD/%s\n\" {+2..})")
eza --icons --color=always | fzf "${FZF_ARGS[@]}"
