#!/usr/bin/env sh
#
#     git default-branch
#     🌳  What's in a name? It doesn't matter.
#     Return the name of a repository's default branch
#
#     author: Lucas Larson
#     URL: https://github.com/LucasLarson/git-default-branch
#     license: GNU Affero General Public License v3.0 or later
#
# shellcheck disable=SC2312

git_default_branch() {
  case "${1-}" in
    -v | --verbose)
      set -o xtrace
      shift
      ;;

    *)
      # check if there’s a `remote` with a default branch and
      # if so, then use that name for `default_branch`
      # https://overflow.adminforge.de/questions/44750379/placeholder
      if command git symbolic-ref refs/remotes/origin/HEAD >/dev/null 2>&1; then
        default_branch="$(
          command git symbolic-ref refs/remotes/origin/HEAD \
            | command sed -e 's/refs\/remotes\/origin\///'
        )"

      # check for `main`, which, if it exists, is most likely to be default
      elif test -n "$(command git branch --list -- 'main')"; then
        default_branch='main'

      # check for a branch called `master` (prepan Git)
      elif test -n "$(command git branch --list -- 'master')"; then
        default_branch='master'

      # check for a branch called `trunk` (Subversion)
      # https://web.archive.org/web/20220121194601/developer.ibm.com/?p=231875
      elif test -n "$(command git branch --list -- 'trunk')"; then
        default_branch='trunk'

      # check for a branch called `HEAD` (CVS)
      elif test -n "$(command git branch --list -- 'HEAD')"; then
        default_branch='HEAD'

      # check for branches called `mainline`, `default`
      # https://github.com/progit/progit2/commit/3680ec7865
      elif test -n "$(command git branch --list -- 'mainline')"; then
        default_branch='mainline'
      elif test -n "$(command git branch --list -- 'default')"; then
        default_branch='default'

      else
        # fail with explanation
        printf 'unable to detect a\n'
        printf '\140main\140, \140master\140, \140trunk\140, or default\n'
        printf 'branch in this repository\n'
        return 2
      fi

      # return the result
      printf '%s\n' "${default_branch}"
      unset -- default_branch

      # undo `set -x` silently
      { set +o xtrace; } 2>/dev/null
      ;;
  esac
}

git_default_branch "${@}"
