#!/usr/bin/env bash
#
# ---
# see: https://bluz71.github.io/2018/11/26/fuzzy-finding-in-bash-with-fzf.html
# source: https://github.com/unixorn/git-extra-commands/blob/main/bin/git-fzf-log-browser

set -e

if [ -n "${DEBUG}" ]; then
  set -x
fi

# send message to stderr. exclude >&2 if you don't want it that way.
# return a code specified by $2 or 1 by default.
fail() {
  printf '%s\n' "$1" >&2
  exit "${2-1}"
}

has() {
  command -v "$@" >/dev/null 2>&1
}

git_fzf_log_browser() {
  selections=$(
    git log --graph --format="%C(yellow)%h%C(red)%d%C(reset) - %C(bold green)(%ar)%C(reset) %s %C(blue)<%an>%C(reset)" --color=always "$@" \
      | fzf --ansi --no-sort --no-height \
        --bind='ctrl-y:execute-silent(echo {} | grep -o '\''[a-f0-9]\{7\}'\'' | head -1 | pbcopy)' \
        --preview="echo {} | grep -o '[a-f0-9]\{7\}' | head -1 |
                      xargs -I@ sh -c 'git show --color=always @'"
  )
  if [ -n "${selections}" ]; then
    commits=$(echo "${selections}" | sed 's/^[* |]*//' | cut -d' ' -f1 | tr '\n' ' ')
    # shellcheck disable=SC2086
    git show ${commits}
  fi
}

if ! has fzf; then
  fail "You need fzf (https://github.com/junegunn/fzf) to use this script."
fi

# shellcheck disable=SC2068
git_fzf_log_browser $@
