#!/usr/bin/env sh
#
# git-branch-status - branch ahead/behind status vs origin/master for all branches

tmpfile="$(mktemp "$(basename "$0")".XXXXXX)" || tmpfile=/tmp/test$$
trap 'rm -- "$tmpfile"' EXIT

git for-each-ref --format='%(refname:short) %(upstream:short)' refs/ \
  | while read -r local remote; do
    if [ -x "${remote}" ]; then
      branches="
      ${local}
      "
    else
      branches="${local}
      ${remote}
      "
    fi
    for branch in ${branches}; do
      master="origin/main"
      git rev-list --left-right "${branch}"..."${master}" -- 2>/dev/null \
        >"${tmpfile}" || continue
      LEFT_AHEAD=$(grep -c '^<' "${tmpfile}")
      RIGHT_AHEAD=$(grep -c '^>' "${tmpfile}")
      echo "${branch} (ahead ${LEFT_AHEAD}) | (behind ${RIGHT_AHEAD}) ${master}"
    done
  done | grep -v "^origin/main" | sort | uniq
