#!/usr/bin/env bash
#
# git-fuzz - create a commit or stage files via fzf selection
# if the first arg is "add", files are staged rather than committed.
# all remaining args are passed to the last git command (add or commit).
# dependencies: git-fzf-diff

# TODO: fix broken prep-commit-msg hook when there is no unifying path

# shellcheck disable=SC2312

# using bash because of pipefail
set -e
# shellcheck disable=SC3040
(set -o pipefail 2>/dev/null) && set -o pipefail

fzfpipe() {
  # take input from git-status short/porcelain and return a list of selected files
  cut -c2- \
    | git fzf-diff -d' ' --nth=2.. \
      --bind="alt-enter:execute(${EDITOR:-vi} '$(git rev-parse --show-toplevel)/{2..}'),alt-d:execute(git restore --worktree --staged '$(git rev-parse --show-toplevel)/{2..}')" \
      --preview="test {1} != \? && git diff --color HEAD --unified=4 -- {2..} | $(git config interactive.diffFilter | grep . || echo "${PAGER:-less}") || find {2..} -type f | xargs -I% diff --recursive --color=always -u /dev/null %" | cut -c3-
}

# shellcheck disable=SC2046
test $(git ls-tree HEAD "${PWD}" 2>/dev/null | wc -l) -gt 1 && wd="${PWD}"
# shellcheck disable=SC2164
cd "$(git rev-parse --show-toplevel)"
tmpdir="${TMPDIR:-/tmp}/git"
prefix="${tmpdir}/fuzz"
mkdir -p "${prefix}"
# remove tmpdir on exit
trap 'rm -rf "$tmpdir"' 0
trap 'exit 2' HUP QUIT INT TERM

case "$1" in
  add)
    shift
    git status --porcelain --no-renames --untracked-files=all "${wd}" \
      | grep -v '^\\w ' | fzfpipe \
      | xe -L 1 git -c advice.addEmptyPathspec=false add --verbose "$@"
      # | xargs -rd '\n' -L 1 git -c advice.addEmptyPathspec=false add --verbose "$@"
    ;;
  *)
    git status --porcelain --no-renames "${wd}" \
      | grep -E -v '\.config/(audacity|puddletag|Stretchly|falkTX|JOSM)/' \
      | sed 's/^\\(\\w\\) / \\1/' | fzfpipe >"${prefix}/files"

    cat "${prefix}/files" \
      | xargs -rd '\n' ls -fd 2>/dev/null >"${prefix}/files-existing" \
      || true

    git -c advice.addEmptyPathspec=false add --intent-to-add \
      --pathspec-from-file="${prefix}/files-existing"
    git commit -v --only --pathspec-from-file="${prefix}/files" "$@"
    ;;
esac
