#!/bin/sh -e
#
# desc: `$EDITOR` last with fzf

if ! command -v fzf >/dev/null 2>&1; then
  tail -n11000 "$1" \
    | v - -c 'setlocal buftype=nofile bufhidden=hide noswapfile | match | $'
else
  case "$#" in
    1)
      if [ -d "$1" ]; then
        command -p -- find -L -- "$1" -path '*/.git' -prune -o -type f \
          -exec ls -Atp -- {} + \
          | head -n 30 \
          | fzf --delimiter '/' --with-nth=-1 --preview-window 'right' \
            --preview 'bat --color=always --style=snip {}' \
            --bind "enter:execute:(${EDITOR:-vi} {} >/dev/tty </dev/tty)"
      else
        if echo "$1" | grep -qE '[0-9]'; then
          command -p -- find -- . -path '*/.git' -prune -o -type f \
            -exec ls -Atp -- {} + \
            | sed "s|${PWD}/||" \
            | head -n "${1:-30}" \
            | fzf --preview-window 'right' \
              --preview 'bat --color=always --style=snip {}' \
              --bind "enter:become(${EDITOR:-vi} {1})"
        else
          exit 1
        fi
      fi
      ;;
    2)
      if echo "$1" | grep -qE "[0-9]"; then
        command -p -- find -L -- "$2" -path '*/.git' -prune -o -type f \
          -exec ls -Atp -- {} + \
          | head -n "$1" \
          | fzf --delimiter '/' --with-nth=-1 --preview-window 'right' \
            --preview='bat --color=always --style=snip {}' \
            --bind "enter:execute(echo {+} | xargs -o ${EDITOR:-vi})"
      else
        command -p -- find -L "$1" -path '*/.git' -prune -o -type f \
          -exec ls -Atp -- {} + \
          | head -n "$2" \
          | fzf --delimiter '/' --with-nth=-1 --preview-window 'right' \
            --preview='bat --color=always --style=snip {}' \
            --bind "enter:execute(echo {+} | xargs -o ${EDITOR:-vi})"
      fi
      ;;
    *)
      find . -path '*/.git' -prune -o -type f -exec ls -Atp -- {} + \
        | sed "s|${PWD}/||" \
        | fzf --exit-0 --preview-window 'hidden:right' \
          --preview='bat --color=always --style=snip {}' \
          --bind "enter:become(${EDITOR:-vi} {1})"
      ;;
  esac
fi
