#!/bin/sh

# shellcheck disable=SC2034

# variables
branch_local=$(git branch | fzf --query "$@")
branch_local=$(git for-each-ref --sort=-committerdate refs/heads/ --format='%(HEAD) %(align:35)%(color:yellow)%(refname:short)%(color:reset)%(end) - %(color:red)%(objectname:short)%(color:reset) - %(align:40)%(contents:subject)%(end) - %(authorname) (%(color:green)%(committerdate:relative)%(color:reset))' | fzf --height 30 | awk '{ print $1 }')
branch_remote=$(git branch -r | sed 's/^ *origin\///' | fzf --height 30)
commit_to_copy=$(git log --oneline | fzf | awk '{ print $1 }')
commits_to_copy=$(git log --oneline | fzf -m | tac | awk '{ print $1 }')

# ga | [g]it [a]dd
if [ -z "$1" ]; then
  git status --short | fzf --multi \
    --preview="echo {} | awk '{ print \$NF }' | xargs git diff -- " \
    | awk '{ print $NF }' | xargs git add
fi

# git-bd | [b]ranch [d]elete
# shellcheck disable=SC2016
git branch | sed 's/^[* ]*//' | fzf --multi \
  --preview 'git diff $(git merge-base HEAD {})..{} | delta' \
  --bind 'ctrl-d:preview-half-page-down,ctrl-u:preview-half-page-up' \
  | xargs -r git branch -D

git branch | sed 's/^[* ]*//' | fzf --multi --preview='git log --oneline {}' \
  xargs -r git branch -D

# git-fcommits | [f]uzzy commits
commit=${1:-HEAD}
git show --stat=120 --format="" "${commit}" \
  | grep '|' \
  | fzf --ansi \
    --disabled \
    --bind 'j:down,k:up,q:abort' \
    --preview="echo {} | sed 's/ *|.*//' | xargs -I% git show --color=always ${commit} -- %" \
    --preview-window=right:60%

# git-delete-branches | select and delete branches
git branch | grep -v "^[^ ]" \
  | grep -vE "  (master|main)$" \
  | grep -vE "  dura/" \
  | sed s:^..::g \
  | fzf -m --height 40% --reverse --preview 'git log --oneline -20 {}' \
  | xargs git branch -D

# git-mru | checkout
git for-each-ref --sort=-committerdate --count=10 refs/heads/ \
  --format='%(refname:short)' \
  | grep -E -v "$(git branch --show-current)" \
  | fzf --layout=reverse-list --header='Choose recent branch:' \
  | xargs git checkout

