#!/bin/sh

# FIXME: fix "history" commands

# shellcheck source=/dev/null
. "$(fzf-share)/completion.bash"
# Disable fzf key-bindings
# readline > fzf
# . "$(fzf-share)/key-bindings.bash"

export FZF_CTRL_T_OPTS='
  --preview "(cat {} || tree -C {}) 2> /dev/null"
  --select-1
  --exit-0
'

export FZF_ALT_C_OPTS='--preview "tree -C {} | head -200"'

# FIXME:
# g '^\w.*json_destroy('
g() {
  # shellcheck disable=2086
  fn=$(git grep -n -- "$1" ${2:-} | \
         cut -d: -f -2            | \
         fzf --select-1 \
             --exit-0   \
             --preview "echo {}       | \
                          cut -d: -f1 | \
                          xargs -I% awk -v bounds=25 -v pat=\"$1\" -v n=\$(echo {} | cut -d: -f2) '
                            (n - bounds < NR) && (NR < n + bounds) && (NR != n) { print }
                            NR==n { gsub(pat, \"\033[1;33m&\033[1;000m\"); print }
                          ' %")
  if [ -n "$fn" ]; then
    f="$(echo "$fn" | cut -d: -f1)"
    n="$(echo "$fn" | cut -d: -f2)"
    # shellcheck disable=2068
    history -s g "$@"
    history -s vi "+$n" "$f"
    vi "+$n" "$f"
  fi
}

f() {
  # FIXME: speed
  # profile="f-shell-function$(pwd | sed -e 's_/_-_g')"
  # file="$(git ls-files | grep ${2:-.} | remembering -p "$profile" -c "fzf --select-1 --exit-0 --preview 'cat {}'")"
  # shellcheck disable=2086
  file="$(git ls-files | grep ${2:-.} | fzf --select-1 --exit-0 --preview 'cat {}')"
  if [ -n "$file" ]; then
    # shellcheck disable=2068
    # history -s f $@
    history -s "$1" "$file"
    "$1" "$file"
  fi
}

V_FILES="$(echo '
~/annex/txt/TODOs.md
~/tmp/scratch.txt
'"$(find ~/annex/txt/*.md -not -name TODOs.md |
	sed 's|^/home/andreh|~|' |
	LANG=POSIX.UTF-8 sort)"'
~/annex/bin/misc/git/mrconfig.ini
~/dev/libre/package-repository/dependencies.dot
~/dev/others/dinheiros/dinheiros.ledger
~/dev/libre/dotfiles/configuration.nix
' | tr ' ' '\n' | grep .)"

v() {
  f="$(echo "$V_FILES" | fzf --select-1 --exit-0 --query "$1")"
  if [ -n "$f" ]; then
    history -s vi $f
    vi "$HOME/${f#'~/'}"
  fi
}

cn() {
	CHOICE="$(git log --oneline | fzf)"
	git log --oneline | grep -nF "$CHOICE" | cut -d: -f1
}

cm() {
	n="$(cn)"
	git rev-parse "HEAD~$((n - 1))"
}
